Showing posts with label core-java. Show all posts
Showing posts with label core-java. Show all posts

Sunday, 15 January 2012

What are variables default values?

Variables declared in methods and in blocks are called local variables. Local variable are not initialized when they are created at method invocation. Therefore, a local variable must be initialized explicitly before being used. Otherwise the compiler will flag it as error when the containing method or block is executed.

Example:

public class SomeClassName{
public static void main(String args[]){ int total; System.out.println("The incremented total is " + total + 3); //(1)
}
}
The compiler complains that the local variable total used in println statement at (1) may not be initialized.
Initializing the local variable total before usage solves the problem:

public class SomeClassName{

public static void main(String args[]){int total = 45; //Local variable initialized with value 45 System.out.println("The incremented total is " + total+ 3); //(1)
}
}

Fields initialization

If no initialization is provided for an instance or static variable, either when declared or in an initializer block, then it is implicitly initialized with the default value of its type.
An instance variable is initialized with the default value of its type each time the class is instantiated, that is for every object created from the class.
A static variable is initialized with the default value of its type when the class is first loaded.


Data Type

Default Value
booleanfalse
char
'/u0000'
Integer(byte,short,int,long)0L for long, 0 for others
Floating-point(float,double)0.0F or 0.0D
reference typenull


Note: Reference fields are always initialized with the value null if no initialization is provided

Example of default values for fields

public class House{

// Static variable
static long similarHouses; //Default value 0L when class is loaded.

// Instance variables
String houseName; //Implicitly set to default value null
int numberOfRooms=5; // Explicitly set to 5
boolean hasPet; // Implicitly set to default value false

//..
}

How to declare and initialize a variable

A variable in Java has a type, name and a value. A variable may store of value of either:
- a primitive data type such as int, boolean, char.
or
- a reference to an object, also called reference variable.


for example:
int i; //variable i that can store an int value. boolean isDone; //Variable isDone that can store a boolean value.//Variables a, f and r that can store a char value each:
char a,f,r;

//Equivalent to the three separate declarations:
char a; char f; char r;

What we just deed above is called variable declaration. By declaring variable we are implicitly allocating memory for these variables and determining the value types that can be stored in them.
So, in the example above, we named a variable: isDone that can store a boolean value, but not initialized yet.

Giving a variable a value when declared is called initialization. Further, we can declare and initialize a variable in one go. For example, we could have declared and initialized our variables of the previous example:

int i = 101; //variable i initialized with the value 101://variable isDone initialized with the boolean value true.
boolean isDone = true;
// variables a,f and r initialized with the values 'a','f' and 'r' //respectively: char a = 'a', f='f', r='r';
//
equivalent to:
char a = 'a';char f = 'f';char r = 'r';


Analogous to declaring variables to denote primitive values, we can declare a variable denoting an object reference, that's; a variable having one of the following reference types: a class, an array, or an interface.

For instance (see also Class Instantiation ):
//declaring a redCar and a blueCar of class Car.
Car redCar, blueCar;

Please note that declarations above do not create any object of type Car. These are just variables that can store references to objects of class Car but no reference is created yet.
A reference variable has to be instantiated before being used. So:// declaring and initializing the redCar reference variable
Car redCar=new Car("red");
An object of class Car is created using the keyword new together with the Constructor call Car("red"), then stored in the variable redCar which is now ready to be manipulated.

Floats


Java Literals

A constant value in a program is denoted by a literal. Literals represent numerical (integer or floating-point), character, boolean or string values.

Example of literals:

Integer literals:
33 0 -9
Floating-point literals:
.3 0.3 3.14
Character literals:
'(' 'R' 'r' '{'
Boolean literals:(predefined values)
true false

String literals:
"language" "0.2" "r" ""

Note: Three reserved identifiers are used as predefined literals:
true and false representing boolean values.
null representing the null reference.



Let's have a closer look at our literals and type of data they can represent:

Integer Literals


Integer data types consist of the following primitive data types: int,long, byte, and short.
int is the default data type of an integer literal.
An integer literal, let's say 3000, can be specified as long by appending the suffix L (or l) to the integer value: so 3000L (or 3000l) is interpreted as a long literal.

There is no suffix to specify short and byte literals directly; 3000S , 3000B,
3000s, 3000b

Integer literals can also be specified as octal (base 8), or hexadecimal (base 16). Octal and hexadecimal have 0 and 0x prefix respectively. So 03 and 0x3 are representation of integer three in octal and hexa-decimal respectively.


Floating-point Literals

Floating-point data consist of float and double types.
The default data type of floating-point literals is double, but you can designate it explicitly by appending the D (or d) suffix. However, the suffix F (or f) is appended to designate the data type of a floating-point literal as float.

We can also specify a floating-point literal in scientific notation using Exponent (short E or e), for instance: the double literal 0.0314E2 is interpreted as
0.0314 *10
² (i.e 3.14).

Examples of double literals:
0.0 0.0D 0d0.7 7D .7d
9.0 9. 9D

6.3E-2 6.3E-2D 63e-1
Examples of float literals:
0.0f 0f 7F .7f9.0f 9.F 9f
6.3E-2f 6.3E-2F 63e-1f


Note: The decimal point and the exponent are both optional and at least one digit must be specified.


Boolean Literals

As mentioned before, true and false are reserved literals representing the truth-values true and false respectively. Boolean literals fall under the primitive data type: boolean.

Character Literals

Character literals have the primitive data type character. A character is quoted in single quote (').

Note: Characters in Java are represented by the 16-bit Unicode character set.

String Literals

A string literal is a sequence of characters which has to be double-quoted (") and occur on a single line.

Examples of string literals:

"false or true"
"result = 0.01"

"a"

"Java is an artificial language"

String literals are objects of the class String, so all string literals have the type String.


Escape (aka backslash) sequences are used inside literal strings to allow print formatting as well as preventing certain characters from causing interpretation errors. Each escape sequence starts with a backslash. The available sequences are:
SeqUsage SeqUsage
\bbackspace \\backslash
\fformfeed \"double quote
\nnewline \'single quote
\rcarriage return \###Octal encoded character
\thorizontal tab \uHHHHUnicode encoded character

Java primitive data types

In Java, primitive data types can be categorized within three types:
  1. Integral types:
    • signed integers : byte,short,int and long.
    • unsigned character values, char,denoting all the 65536 characters in the 16-bit Unicode character set.
  2. Floating-point types: float and double, representing fractional signed numbers.
  3. Boolean type: boolean, representing logical values, the two literals, true or false.

A primitive data value can't act as an object in a Java program unless wrapped. Therefore, each primitive data type has a corresponding wrapper class that can be used to represent its value as an object.

Playing with double datatype using Java

Do you guess the output values of the following code snippets (in  Java) ? .


                        double d5 =99999.99;
                        double d6 =999999.99;
                        double d7 =9999999.99;
                        double d8 =99999999.99;
                        double d9 =999999999.99;
                        double d10=9999999999.99;

                        System.out.println("d5 ="+d5);
                        System.out.println("d6 ="+d6);
                        System.out.println("d7 ="+d7);
                        System.out.println("d8 ="+d8);
                        System.out.println("d9 ="+d9);
                        System.out.println("d10="+d10);

Here is the output:




d5 =99999.99
d6 =999999.99
d7 =9999999.99
d8 =9.999999999E7
d9 =9.9999999999E8
d10=9.99999999999E9

Have you noticed the values of d8, d9 and d10?. The output value is in  E (exponential) format. Java is internally doing this conversion while convert the datatype double to String.  If the value is  greater than or equal to 10-3 but less than 107, then the output will be normal. Otherwise the value will be in Exponential.

To print the values all in normal format, use the "java.text.DecimalFormat" class. Check the following code snippet.


                        DecimalFormat d = new DecimalFormat("##.##");
                        System.out.println("d5 ="+d.format(d5));
                        System.out.println("d6 ="+d.format(d6));
                        System.out.println("d7 ="+d.format(d7));
                        System.out.println("d8 ="+d.format(d8));
                        System.out.println("d9 ="+d.format(d9));
                        System.out.println("d10="+d.format(d10));
The output is


d5 =99999.99
d6 =999999.99
d7 =9999999.99
d8 =99999999.99
d9 =999999999.99
d10=9999999999.99

Refer the following URL to get the more details about the Double,.

Thursday, 22 September 2011

Java: Rounding off to 2 decimal places

Seeking the simplest way to round off a float value to 2 decimal places, i found these:

Method 1:
x = (double)int((x+0.005)*100.0)/100.0;

Method 2:
x = Math.round(x*100.0) / 100.0;

Method 3:
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();

Method 4:
f = (float) (Math.round(n*100.0f)/100.0f);

Method 5:
double r = 5.1234;
System.out.println(r); // r is 5.1234
int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP); // setScale is immutable
r = bd.doubleValue();
System.out.println(r); // r is 5.12

[source: www.thescripts.com, accuracy unchecked]

How I did it:
float percentage = score.floatValue()/(qapairs.length*10)*100; //my float value
percentage = Float.valueOf((new DecimalFormat("###.00").format(percentage)));

Saturday, 9 July 2011

Introduction to operators in java

Operators in java are similar to c++ and c.
Operators are actions that manipulate, combine or compare variables.
They fall into several categories as follows:
OperatorsSymbols
Assignment+= -= *= \= %=
Arithmetic+ - * / % (modulus)
++ (increment) -- (decrement)
String Concatenation+
Comparison or Relational Operators== , != , > , >= , < <=
Logical OR Boolean Comparison! & | ^ && || (&& are short circuit ops)
Bitwise Comparison~ & | ^ (xor) << >> >>>
Bitwise Assignment&= |= ^= (xor) <<= >>= >>>=
Conditional operator? (eg (expr1) ? expr2 : expr3 )
Object Creationnew (eg int a[] = new int[10];)
Class of Objectinstanceof
Casting of Type(var_type)

Note: Changes in data type are done explicitly using a cast operation. For examplea = (int) b; assumes a is of type int and b is of another type.

Number of Operands for Operators

Java operators can be classified as unary, binary, or ternary—meaning taking one, two, or three arguments, respectively. A unary operator may appear
before (prefix) its argument or after (postfix) its argument. A binary or ternary operator appears between its arguments.

Covering Various Operators in depth

Following are the operators in java:

Java Introduction

Friday, 8 July 2011

Java architecture

According to Sun Microsystems the Java architecture comprises of four components.Each of them is defined by Sun Microsystems.

The Components are:-

1 .Java Programming Language
2 .Java class file format
3. Java Virtual Machine
4. Java (API) Application Programming Interface.
Every Java program uses features of all the four components.They are used in following sequence:-

We write code in Java programming Language.
When we compile the .java file it creates a new file which is called as the class file(also called bytecode).
The .class file(or class file) is executed by the JVM.
When we execute the program the method calls are made through the Java API.The above

Sequence may be represented as following block diagram:-

Representing the same by flow diagram:

You can think of Java bytecodes as the machine code instructions for the Java Virtual Machine (Java VM). Every Java interpreter, whether it's a Java development tool or a Web browser that can run Java applets, is an implementation of the Java VM. The Java VM can also be implemented in hardware.
Java bytecodes help make "write once, run anywhere" possible. You can compile your Java program into bytecodes on any platform that has a Java compiler. The bytecodes can then be run on any implementation of the Java VM. For example, the same Java program can run on Windows NT, Solaris, and Macintosh.


The JVM and the Java API forms the basic Java runtime system and is must to execute any java program.The specification provided by the Sun Microsystems only lists the components features but this specification lacks the way how these features to be implemented.The implementation is always left to the designers.The JVM is provided by many vendors, mostly it comes along with the Operating System.All the JVM's must have some unique features that is why it is said that "Threads are JVM behaviour dependent".So its important to figure out how your JVM performs internal task of scheduling,memory related issues and other performance matrices.Although the JVM vendors and JVM functioning is a bit different but still all of them follow the Sun Microsystems Specification for Java Architecture.

Friday, 24 June 2011

How different variables stored in java - on Heap and stack

  • Instance variables and objects live on the heap.
  • Local variables live on the stack.

Let’s take a look at a Java program, and how its various pieces are created and map into the stack and the heap:

1. class Cub{ }
2.
3. class Lion {
4. Maine c; // instance variable
5. String name; // instance variable
6.
7. public static void main(String [] args) {
8.
9. Lion d; // local variable: d
10. d = new Lion();
11. d.go(d);
12. }
13. void go(Lion lion) { // local variable: Lion
14. c = new Cub();
15. lion.setName("Bakait");
16. }
17. void setName(String LionName) { // local var: LionName
18. name = LionName;
19. // do more stuff
20. }
21. }

  This is how the variables and methods get placed in the stack and heap during execution of the above piece of code.
  • Line 7—main() is placed on the stack.
  • Line 9—reference variable d is created on the stack, but there’s no Lion object yet.
  • Line 10—a new Lion object is created and is assigned to the d reference variable.
  • Line 11—a copy of the reference variable d is passed to the go() method.
  • Line 13—the go() method is placed on the stack, with the Lion parameter as a local variable.
  • Line 14—a new Maine object is created on the heap, and assigned to Lion’s instance variable.
  • Line 17—setName() is added to the stack, with the LionName parameter as its local variable.
  • Line 18—the name instance variable now also refers to the String object.
  • Notice that two different local variables refer to the same Lion object.
  • Notice that one local variable and one instance variable both refer to the same String Aiko.
  • After Line 19 completes, setName() completes and is removed from the stack. At this point the local variable LionName disappears too, although the String object it referred to is still on the heap.

Sunday, 15 May 2011

Explicit or direct Field Initialization in java

Because you can overload the constructor methods in a class, you can obviously build in many ways to set the initial state of the instance fields of your classes. It is always a good idea to make sure that, regardless of the constructor call, every instance field is set to something meaningful.
You can simply assign a value to any field in the class definition. For example,
class Employee

{

. . .

private String name = "";

}



This assignment is carried out before the constructor executes. This syntax is particularly useful if all constructors of a class need to set a particular instance field to the same value.

The initialization value doesn't have to be a constant value. Here is an example in which a field is initialized with a method call. Consider an Employee class where each employee has an id field. You can initialize it as follows:

class Employee

{

. . .

static int assignId()

{

int r = nextId;

nextId++;

return r;

}

. . .

private int id = assignId();

}



See cpp vs java in case of direct field initialization.

Difference between fields and local variables

There are few difference between fields and local variables. Fields are defined in the class, whereas local variables are local to the methods. The big difference comes in case of initialization.
You must always explicitly initialize local variables in a method. But if you don't initialize a field in a class, it is automatically initialized to a default (0, false, or null).

Monday, 25 April 2011

Java: count the number of one bits in an int

Integer.bitCount counts the number of one-bits in the two's complement binary representation of the specified int value. Example code:
public class CountOnes {
public static void main(String[] args) {
int[] i = { 1, 4, 7, 15 };
for (int j = 0; j < i.length; j++) {
System.out.printf("Number of 1's in %d: %d\n", i[j], Integer.bitCount(i[j]));
}
}
}

Friday, 22 April 2011

Casting Objects and instanceof

One of the difficulties of using a superclass array to hold many instances of subclass objects is that one can only access properties and methods that are in the superclass (ie. common to all). By casting an individual instance to its subclass form, one can refer to any property or method. But first take care to make sure the cast is valid by using the instanceof operator. Then perform the cast. As an example using the above Animal class:

if (ref[x] instanceof Dog) // ok right type of object
{
  Dog doggy = (Dog) ref[x]; // cast current instance to subclass
  doggy.someDogOnlyMethod();
}


Casts to subclass can be done implicitely but explicit casts are recommended. Casts to superclass must be done explicitly. Casts cannot be made between sibling classes.

Arrays of Base class objects

As with arrays of primitive types, arrays of objects allow much more efficient methods of access. Note in this example that once the array of Animals has been structured, it can be used to store objects of any subclass of Animal. By making the method speak() abstract, it can be defined for each subclass and any usage will be polymorphic (ie. adapted to the appropriate object type at runtime). It now becomes very easy to rehearse the speak() method for each object by object indexing.


public class AnimalArray
{
  public static void main(String args[])
  Animal ref[] = new Animal[3]; // assign space for array
  Cow aCow = new Cow("Bossy");  // makes specific objects
  Dog aDog = new Dog("Rover");
  Snake aSnake = new Snake("Earnie");

  // now put them in an array
  ref[0] = aCow; ref[1] = aDog; ref[2] = aSnake;

  // now demo dynamic method binding
  for (int x=0;x<3;++x) { ref[x].speak(); }
}

Polymorphism

Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. This is the third basic principle of object oriented programming. Overloading, overriding and dynamic method binding are three types of polymorphism.
Overloaded methods are methods with the same name signature but either a different number of parameters or different types in the parameter list. For example 'spinning' a number may mean increase it, 'spinning' an image may mean rotate it by 90 degrees. By defining a method for handling each type of parameter you control the desired effect.
Overridden methods are methods that are redefined within an inherited or subclass. They have the same signature and the subclass definition is used.
Dynamic (or late) method binding is the ability of a program to resolve references to subclass methods at runtime. As an example assume that three subclasses (Cow, Dog and Snake) have been created based on the Animal abstract class, each having their own speak() method. Although each method reference is to an Animal (but no animal objects exist), the program is will resolve the correct method reference at runtime.

public class AnimalReference
{
  public static void main(String args[])
  Animal ref                 // set up var for an Animal
  Cow aCow = new Cow("Bossy"); // makes specific objects
  Dog aDog = new Dog("Rover");
  Snake aSnake = new Snake("Ernie");

  // now reference each as an Animal
  ref = aCow; ref.speak();
  ref = aDog; ref.speak();
  ref = aSnake; ref.speak();
}

Object Creation and Destruction

To create an object of a particular class use the new operator. For example, now that there is a constructor for the Box class you can make specific instances or discrete copies of a box by using the assignment operator and the new memory allocation operator as in:
Box box_1=new Box(3,4,5);
Note: Once a class has been specified, a datatype exists with the same name.
You do not need to destroy or remove an object when it is no longer needed. Java automatically flags unused objects and applies garbage collection when appropriate. However you may occasionally need to use the finalize() method to insure that a non-Java resource such as a file handle or a window font character is released first. The general form is:
void finalize()
{
//cleanup code goes here
super.finalize() //parent too!
}

OOP in java