Tuesday 11 September 2012

scramble


MAP :

"harish" "viv" ]
public function({
println x.1;
}
function()


brings error 




whereas

id "harish" "viv" ]
public function({
println x.id;
}
function()

works fine giving output  harish

To solve the first problem we faced when we had integer as key
is


"harish" "viv" ]
public function({
println x.get(1);
}
function()

works fine giving output : harish


________________________________________________________________________________

Similarly
id "harish" "viv" ]
public function({
println x.get(id);
}
function()

flings error 






But
id "harish" "viv" ]
public function({
println x.get("id");
}
function()

works fine giving output as harish








































































































































































"def" keyword in groovy


def actually defines the scope of the variable being defined


4
public function({
println x;
}
function()


o/p -> 4

whereas 

def 4
public function({
println x;
}
function()


o/p -> 




so the the declaration without def makes it global .
But people say that it is good to use variable declarations with def 
so that , it does not unnecessarily interfere with the variables 
inside functions 

I got a rough idea from





















































































Tuesday 7 August 2012

Java and Python

the following info was flicked from 

Py and Ja 

1) In Py

>>> a = 10
>>> a = "harish"
>>>a
harish

2) In Ja 
class h {
public static void main(String[] args){
String a = "harish";
a = 7;
System.out.println(a);
}

}
o/p: 
a = 7;
    ^
  required: String
  found:    int
1 error

This difference makes
Python being called as dynamically typed language and java being statically typed language 

The explanation is given in the blog mentioned above .
String a ;  => declaration binds a variable to a type 
a = "harish" ; => definitions binds it to an object . object here is "harish" , now the system checks the type of the object "harish" . if its is a string then , it okays , or else it flings an error .
whereas in py 
the variable is bound only to object and no type .
so it can be changed whenever wanted and wherever wanted 

I believe :
actually because java has something called compilation and then running  . There is a compulsion that the variables need to be type referenced so that during run time it gets the object . 
Where as in python , there is no such compilation , so only running , so only objects need to  be assigned to variables and and as there is not type which is associated with the variable(because there is no prechecking like compilation ), we can change the object the variable is bound to . 

this makes Python a dynamically typed language and java a statically typed language 





Tuesday 17 July 2012

Multiple Catch statements in JAVA




Multiple catch Clauses
In some cases, more than one exception could be raised by a single piece of code. To handle
this type of situation, you can specify two or more catch clauses, each catching a different
type of exception. When an exception is thrown, each catch statement is inspected in order,
and the first one whose type matches that of the exception is executed. After one catch
statement executes, the others are bypassed, and execution continues after the try/catch
block. The following example traps two different exception types:
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
This program will cause a division-by-zero exception if it is started with no command-
line arguments, since a will equal zero. It will survive the division if you provide a
command-line argument, setting a to something larger than zero. But it will cause an
ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the program
attempts to assign a value to c[42].
Here is the output generated by running it both ways:
C:\>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.
When you use multiple catch statements, it is important to remember that exception
subclasses must come before any of their superclasses. This is because a catch statement
that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a
subclass would never be reached if it came after its superclass. Further, in Java, unreachable
code is an error. For example, consider the following program:
/* This program contains an error.
A subclass must come before its superclass in
a series of catch statements. If not,
unreachable code will be created and a
compile-time error will result.
*/
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
} catch(Exception e) {
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) { // ERROR - unreachable
System.out.println("This is never reached.");
}
}
}
If you try to compile this program, you will receive an error message stating that the
second catch statement is unreachable because the exception has already been caught. Since
ArithmeticException is a subclass of Exception, the first catch statement will handle all
Exception-based errors, including ArithmeticException. This means that the second catch
statement will never execute. To fix the problem, reverse the order of the catch statements.


Note : the above simple (yet appears to be recondite ) information was taken from Java - The complete reference  book.

Tuesday 3 July 2012

Rubbish

Dont read this ....
How serving webpages works ? (according to me )

we click url  and page correspondingly is served from server
we then give input and click submit
then this info is sent in request
then now 2 things can be done
1) either values are written directly in response by response.write () in the java program(servlet)
2) or use JSP ,where it is done in two ways
i) values are set in bean(bean should exists) in server and then got from bean by

<jsp:useBean id="mybean" scope="session" class="org.mypackage.hello.NameHandler" />
 <jsp:setProperty name="mybean" property="name" value="vivek" /> (sets value of the argument in url "name" and sets in bean )
 <jsp:getProperty name="mybean" property="name1"/> ( retrieves from bean)
ii) or write java code in scriptlet tag
when you create web app using struts additional files are ?
Name->Web Pages->WEB-INF ->
1) beans.xml
2) struts-config.xml
3)tiles-defs.xml
4)validation.xml
5) validator-rules.xml


Actually what we do in including struts is
actually in giving global url localhost:8080/global-url/ , it gets directed to somename.do ,,, as in index.jsp we have asked it to forward the request <jsp:forward page="somename.do"/> , this statement is equal to typing in url tab as localhost:8080/global-url/somename.do  . Dont interpret this statement as forwaring request to somename.do (as it looks smilar to redirecting to some.jsp) .. but this is eq to typing and clicking  url/somename.do .
now it goes and checks in web.xml . what to do with request localhost:8080/global-url/somename.do  
as there it is written as *.do as context path should be mapped to servlet org.apache.struts.action.ActionServlet , and also struts-config.xml are sent as parameters .........


so now thereafter it becomes regular servlet story , as  org.apache.struts.action.ActionServlet class has a reference to what i am saying. statement goes like this
 public class ActionServlet extends javax.servlet.http.HttpServlet { 
so  org.apache.struts.action.ActionServlet is our servlet java code 


and the struts-config.xml is like the original web.xml 


The idea of having this type of mapping is that they have servlet classes org.apache.struts.action.* written by themselves which does some of the basic tasks . 


As it completely deals with srtuts action , people have created their own nomenclature . like using 
<action-mapping> instead of <servlet-mapping>


Monday 25 June 2012

JAVA -abstract class and interface

Both Abstract class and interfaces are both like frameworks or outer skeleton .

They are to be implemented in child class which extends the parent class .

1) Interface is solely a skeleton .
Abstract class is not solely a skeleton , it also has implementations within it .

2) As interface is solely a skeleton , all methods inside a interface are abstract methods and variables are final and static .So , the implementing child class should implement all the methods inside the interface .
But when creating interface , we need not put the keyword abstract in front of all methods inside an interface as the definition of interface means it .
Abstract class can have within it, variables that are non static , methods that are not abstract  . So , the child class that implements the abstract class should implement all the abstract methods (if any ) . And leave the non abstract methods untouched .Needs to explicitly say which methods are abstract using keyword "abstract".
Neither abstract class nor interface can be instantiated . It can be only be implemented .
So if we don't implement all methods of interface and all abstract methods of an abstract class , then it means the child class that implements these child classes will also be considered as interfaces or abstract classes ,as they contain abstract methods which was inherited   (not implemented) and so the child classes cannot be instantiated , as abstract class and interface cannot be instantiated .

This brings in the idea that abstract classes and interfaces can be extended by other interface or class . A class that extends an interface must me either another interface or abstract class . So here all the methods of the interface need not be implemented in abstract class that extends it.

3) As the interface is solely abstract or skeleton , it is implemented by using keyword "implements" and not by using keyword "extends". As abstract may have implementations within it . It is implemented using keyword "extends "
In fact a interface can extend another interface using keyword "extends"


4) a child class can extend many interfaces at the same time , by separating interface names with "," .
a child class can extend only one abstract class .

JAVA -methods and keyword "this" and "super"


Methods :

 Wikipedia says "Methods define the behavior to be exhibited by instances of the associated class at program run time. Methods have the special property that at runtime, they have access to data stored in an instance of the class (or class instance or class object or object) they are associated with and are thereby able to control the state of the instance."  
So one thing is clear , during compilation the variables get set and  during run time the methods act on the variables of these instances . (Not sure)

Similar to variables we have 2 types
1) instance methods
2) class methods

Definitions are same as we saw in variables section .

Lets concentrate on which can access which ?

http://docs.oracle.com says

  • Instance methods can access instance variables and instance methods directly.
  • Instance methods can access class variables and class methods directly.
  • Class methods can access class variables and class methods directly.
  • Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
Lets not mug this up . Lets go by logic .

Instance methods are Object specific . so it can access that which are specific to instances(i.e., instance variables and methods ) and also those class methods and class variables which are common to all objects (as it knows which class's instance it is)
Class methods in not instance specific , it is common to all objects(or instances) , so it has no knowledge about the instance , as it is not instance specific . As it is totally unaware of the instances , it cannot access , instance variables and instance methods (which are instance specific) . Whereas it can access class methods and class variables .

So the keyword "this" is meaningless when used inside class methods .

Other classification
wikipedia gave three methods 

Abstract methods

An abstract method is one with only a signature and no implementation body. It is often used to specify that a subclass must provide an implementation of the method. Abstract methods are used to specify interfaces in some computer languages.[3]

[edit]Example

The following java code shows an abstract class that need to be extended:
abstract class Main{
 
        abstract int rectangle(int h,int w); //abstract method signature
}
The following subclass extends the main class:
public class Main2 extends Main{
 
        @Override
        int rectangle(int h,int w)
        {
                return h*w;
        }
 
}

Overloaded methods

http://java67.blogspot.in/2012/08/what-is-method-overriding-in-java-example-tutorial.html 
Overloaded methods are those with the same name but different formal parameters or return value type, if the language supports overloading on return type.[4] For example in the following C++, class geometry have two method named "area". But there parameter list is different which distinguish the methods. Many other languages provide this feature.
#include<iostream>
using namespace std;
class geometry
{
        public:
        static double area(double h,double w)
        {
                return h*w;
        }
        static double area(double r)
        {
                return r*r*3.14;
        }
 
};
int main()
{
        double rectangle_area=geometry().area(3,4);
        double circle_area=geometry().area(5);
        cout<<rectangle_area<<endl;
        cout<<circle_area<<endl;
        return 0;
}

[edit]Overridden methods

Overridden methods are those that are redefined in a subclass and hide methods of a superclass. It often creates confusion with overloaded methods. The main difference is overridden method is situated in a different class derived from a super class, while in case of overloaded method both methods can be in the same class. [5] Look at following example in java:
public class class1
{
        int f(int x)
        {
                return x+3;
        }
}
 
public class class2 extends class1
{
        @Override
        int f(int x) //overriding
        {
                return x*x;
        }
        int f(int x,int y) //overloading
        {
                return x*y;
        }
}

The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed.[2] Some languages allow a programmer to prevent a method from being overridden.

THIS :

For explanation on "this" refer the link below 

Inaddition read this 

Using this with a Constructor

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class, with a different implementation from the one in the Objects section.
public class Rectangle {
    private int x, y;
    private int width, height;
        
    public Rectangle() {
        this(0, 0, 0, 0);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor calls the four-argument constructor with four 0 values and the two-argument constructor calls the four-argument constructor with two 0 values. As before, the compiler determines which constructor to call, based on the number and the type of arguments.
If present, the invocation of another constructor must be the first line in the constructor.

Also refer 
Using "this" to return the instance that is using the class 


SUPER :

1) Used to call methods in superclass without the object name so no instantiation is needed to call super class's method .You may ask me question why we need this , when we can call using the object name.. Answer is this :this gives facility to access methods of super class from being inside child class .


public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod(); // calls the parent classes method printMethod
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    //calls the child classes method printMethod 
    }
}

2) Used to invoke superclass's constructor . .You may ask me that we already have this my using "this".
Ya , this calls constructor from inside the class whose constructor is called and not from outside the class .


The following example illustrates how to use the super keyword to invoke a superclass's constructor. Recall from the Bicycle example thatMountainBike is a subclass of Bicycle. Here is the MountainBike (subclass) constructor that calls the superclass constructor and then adds initialization code of its own:
public MountainBike(int startHeight, 
                    int startCadence,
                    int startSpeed,
                    int startGear) {
    super(startCadence, startSpeed, startGear);
    seatHeight = startHeight;
}   
Invocation of a superclass constructor must be the first line in the subclass constructor.
The syntax for calling a superclass constructor is
super();  
or:
super(parameter list);
With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.