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

Thursday, September 22, 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, July 9, 2011

Java Overview

Let's cover some of introductory chapters, which tells us about the strengths of java:

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

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.

Saturday, June 25, 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.

Monday, May 16, 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).

Sunday, May 1, 2011

Abstract Classes Have Constructors in decompiled code

1) In Java , we have default constructors provided for classes by the compiler (in case one is not declared).

2) The abstract classes can't be instantiated by using the new operator because they don't provide full implementation of all the methods.

Then does it make sense to have constructors inside abstract classes. Let us find it using a sample abstract class:
public abstract class Test{
   public abstract void doSomething();
}

The decompiled code for this class will show the truth about constructors in abstract classes in Java
public abstract class Test
{
    public Test()
    {
    }
    public abstract void doSomething();
}


Why?

The reason is that when a class extends any other class and an instance of the subclass is created then the constructor calls are chained and the super class constructors are invoked. This rule is no exception for abstract class

Moreover, having constructors in a class doesn't necessarily mean that instance of that class will be created using the new operator, but the constructors are intended for writing any initializing code.

Monday, April 25, 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]));
 }
    }
}

Saturday, April 23, 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

Inheritance among interfaces in java

Note the exception of extends with Interfaces
It is possible to use derivation in the definition of interfaces. And in Java it is possible for an interface to extend more than one base interface:
interface D extends E, F
{
}
 
In this case, the derived interface D comprises all the methods inherited from E and F as well as any new methods declared in the body of D.

Interfaces in java

Interfaces are similar to abstract classes but all methods are abstract and all properties are static final. Interfaces can be inherited (ie. you can have a sub-interface). As with classes the extends keyword is used for inheritence.Java does not allow multiple inheritance for classes (ie. a subclass being the extension of more than one superclass). An interface is used to tie elements of several classes together. Interfaces are also used to separate design from coding as class method headers are specified but not their bodies. This allows compilation and parameter consistency testing prior to the coding phase. Interfaces are also used to set up unit testing frameworks.
As an example, we will build a Working interface for the subclasses of Animal. Since this interface has the method called work(), that method must be defined in any class using the Working interface.

public interface Working
{
  public void work();
}

When you create a class that uses an interface, you reference the interface with the phrase implements Interface_list. Interface_list is one or more interfaces as multiple interfaces are allowed. Any class that implements an interface must include code for all methods in the interface. This ensures commonality between interfaced objects.


public class WorkingDog extends Dog implements Working
{
  public WorkingDog(String nm)
  {
    super(nm);    // builds ala parent
  }
  public void work()  // this method specific to WorkingDog
  {
    speak();
    System.out.println("I can herd sheep and cows");
  }
}


Also see Multiple inheritance in java

cpp vs Java : Abstract classes

CPP :
A class that contains at least one pure virtual function is said to be abstract. Because an abstract class contains one or more functions for which there is no definition (that is, a pure virtual function), no objects of an abstract class may be created. Instead, an abstract class constitutes an incomplete type that is used as a foundation for derived classes.
Although you cannot create objects of an abstract class, you can create pointers and references to an abstract class. This allows abstract classes to support run-time polymorphism, which relies upon base-class pointers and references to select the proper virtual function.

Class Syntax in Java

A class is a template or prototype for each of many object instances made to the class design. The class specifies the properties (data) and methods (actions) that objects can work with.

Syntax of Class

The syntax for a class is:
["public"] ["abstract"|"final"]"class" Class_name
  ["extends" object_name] ["implements" interface_name]
"{"
// properties declarations
// behavior declarations
"}"
The first optional group indicates the visibility or scope of accessibility from other objects. public means visible everywhere. The default (ie. omitted) is package (aka friendly) or visible within the current package only.
The second optional group indicates the capability of a class to be inherited or extended by other classes. abstract classes must be extended and final classes can never be extended by inheritance. The default (ie. omitted) indicates that the class may or may not be extended at the programmers discretion.
Class_name has initial letter capitalized by Java convention.
The third option of extends is described in the tutorial on inheritance.
The fourth option of implements is described in the tutorial on interfaces.
A simple example of a class specification is a box. The box has length, width and height properties as well as methods for setting dimensions and displaying its volume.
public class Box
{
  // what are the properties or fields
  private int length, width, height;

  // what are the actions or methods
  public void setLength(int p) {length=p;}
  public void setWidth(int p) {width=p;}
  public void setHeight(int p) {height=p;}
  public void showVolume() {System.out.println(length*width*height);}
}
Note 1: There is no main method in a class defining template!
Note 2: Class names begin with a capital. Use lowercase for all other names.
Note 3: It is good programming practice to write separate files for the class templates and the driver or main user program. This allows separate compilation as well as class reuse by other driver programs. A class file can contain more than one associated class but normally its filename is that of the first defined file. A driver program is named the same as the class that contains the main(). Its file may contain other classes as well.

Field Values or Properties
Methods
Types of methods


Chitika