Tuesday, May 21, 2013

test posst

Garbage collector  with eg
runnable inteface








what is benifits of finalize meethod
what are the different types of collections
diffferenect between comparator and comparable interface
what is the benifits of finalize method


what is static keyword? difference between instance variable/method and static variable/method?
wjat is "Exception" in java
what is use of finally block in java
what is serillization in java
what is transient variable
what is polymofphisam , encapsulation, inheritance in java
difference between string buffer and string builder
explain class loading in java




1. is java pass by value or pass by reference?
--> Pass by value in java means passing a copy of the value to be passed. Pass by reference in java means the passing the address itself. In Java the arguments are always passed by value. Java only supports pass by value.With Java objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same Java object. Java primitives too are passed by value.
Java passes everything( primitive and objective) by value.

2. diff between c++ and java
-->a.C++ supports pointers whereas Java does not pointers. But when many programmers questioned how you can work without pointers, the promoters began saying "Restricted pointers.” So we can say java supports Restricted pointers.

    b.At compilation time Java Source code converts into byte code .The interpreter execute this byte code at run time and gives output .Java is interpreted for the most part and hence platform independent. C++ run and compile using compiler which converts source code into machine level languages so c++ is plate from dependents

    c.Java is platform independent language but c++ is depends upon operating system machine etc. C++ source can be platform independent (and can work on a lot more, especially embedeed, platforms), although the generated objects are generally platofrom dependent but there is clang for llvm which doesn't have this restriction.

    d.Java uses compiler and interpreter both and in c++ their is only compiler

    e.C++ supports operator overloading multiple inheritance but java does not.

    f.C++ is more nearer to hardware then Java

    g.Everything (except fundamental types) is an object in Java (Single root hierarchy as everything gets derived from java.lang.Object).

    h.Java does is a similar to C++ but not have all the complicated aspects of C++ (ex: Pointers, templates, unions, operator overloading, structures etc..) Java does not support conditional compile (#ifdef/#ifndef type).

    i.Thread support is built-in Java but not in C++. C++11, the most recent iteration of the C++ programming language does have Thread support though.

    j.Internet support is built-in Java but not in C++. However c++ has support for socket programming which can be used.

    k.Java does not support header file, include library files just like C++ .Java use import to include different Classes and methods.

    l.Java does not support default arguments like C++.

    m.There is no scope resolution operator :: in Java. It has . using which we can qualify classes with the namespace they came from.

    n.There is no goto statement in Java.

    o.Exception and Auto Garbage Collector handling in Java is different because there are no destructors into Java.

    p.Java has method overloading, but no operator overloading just like c++.

    q.The String class does use the + and += operators to concatenate strings and String expressions use automatic type conversion,

    r.Java is pass-by-value.

    s.Java does not support unsigned integer.


3.why java is platform independent?
Typically, the compiled code is the exact set of instructions the CPU requires to "execute" the program. In Java, the compiled code is an exact set of instructions for a "virtual CPU" which is required to work the same on every physical machine.

So, in a sense, the designers of the Java language decided that the language and the compiled code was going to be platform independent, but since the code eventually has to run on a physical platform, they opted to put all the platform dependent code in the JVM.

This requirement for a JVM is in contrast to your Turbo C example. With Turbo C, the compiler will produce platform dependent code, and there is no need for a JVM work-alike because the compiled Turbo C program can be executed by the CPU directly.

With Java, the CPU executes the JVM, which is platform dependent. This running JVM then executes the Java bytecode which is platform independent, provided that you have a JVM availble for it to execute upon. You might say that writing Java code, you don't program for the code to be executed on the physical machine, you write the code to be executed on the Java Virtual Machine.

The only way that all this Java bytecode works on all Java virtual machines is that a rather strict standard has been written for how Java virtual machines work. This means that no matter what physical platform you are using, the part where the Java bytecode interfaces with the JVM is guaranteed to work only one way. Since all the JVMs work exactly the same, the same code works exactly the same everywhere without recompiling. If you can't pass the tests to make sure it's the same, you're not allowed to call your virtual machine a "Java virtual machine".

Of course, there are ways that you can break the portability of a Java program. You could write a program that looks for files only found on one operating system (cmd.exe for example). You could use JNI, which effectively allows you to put compiled C or C++ code into a class. You could use conventions that only work for a certain operating system (like assuming ":" separates directories). But you are guaranteed to never have to recompile your program for a different machine unless you're doing something really special (like JNI).




4.What is jvm?
A Java virtual machine (JVM) is a virtual machine that can execute Java bytecode. It is the code execution component of the Java software platform.

The Java Development Kit (JDK) is an Oracle Corporation product aimed at Java developers. Since the introduction of Java, it has been by far the most widely used Java Software Development Kit (SDK).

Java Runtime Environment, is also referred to as the Java Runtime, Runtime Environment

OpenJDK (Open Java Development Kit) is a free and open source implementation of the Java programming language.[2] It is the result of an effort Sun Microsystems began in 2006. The implementation is licensed under the GNU General Public License (GPL) with a linking exception.




5.difference between abstract class and interface?

    a.Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
    b.Variables declared in a Java interface is by default final. An  abstract class may contain non-final variables.
    c.Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
    d.Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
    e.An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
    f.A Java class can implement multiple interfaces but it can extend only one abstract class.
    g.Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
    h.In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.


6.What is Garbage collection in java?
1) objects are created on heap in Java  irrespective of there scope e.g. local or member variable. while its worth noting that class variables or static members are created in method area of Java memory space and both heap and method area is shared between different thread.
2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
3) Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic.
4) Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
5) Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
6) You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
7) There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
8) If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space
9) J2SE 5(Java 2 Standard Edition) adds a new feature called Ergonomics goal of ergonomics is to provide good performance from the JVM with minimum of command line tuning.

When an Object becomes Eligible for Garbage Collection
An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection.
Generally an object becomes eligible for garbage collection in Java on following cases:
1) All references of that object explicitly set to null e.g. object = null
2) Object is created inside a block and reference goes out scope once control exit that block.
3) Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.
4) If an object has only live references via WeakHashMap it will be eligible for garbage collection. To learn more about HashMap see here How HashMap works in Java.

Heap Generations for Garbage Collection in Java
Java objects are created in Heap and Heap is divided into three parts or generations for sake of garbage collection in Java, these are called as Young generation, Tenured or Old Generation and Perm Area of heap.
New Generation is further divided into three parts known as Eden space, Survivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent Minor Garbage collection if object survives its gets moved to survivor 1 and then Survivor 2 before Major Garbage collection moved that object to Old or tenured generation.

Permanent generation of Heap or Perm Area of Heap is somewhat special and it is used to store Meta data related to classes and method in JVM, it also hosts String pool provided by JVM as discussed in my string tutorial why String is immutable in Java. There are many opinions around whether garbage collection in Java happens in perm area of java heap or not, as per my knowledge this is something which is JVM dependent and happens at least in Sun's implementation of JVM. You can also try this by just creating millions of String and watching for Garbage collection or OutOfMemoryError.

Types of Garbage Collector in Java
Java Runtime (J2SE 5) provides various types of Garbage collection in Java which you can choose based upon your application's performance requirement. Java 5 adds three additional garbage collectors except serial garbage collector. Each is generational garbage collector which has been implemented to increase throughput of the application or to reduce garbage collection pause times.

1) Throughput Garbage Collector: This garbage collector in Java uses a parallel version of the young generation collector. It is used if the -XX:+UseParallelGC option is passed to the JVM via command line options . The tenured generation collector is same as the serial collector.

2) Concurrent low pause Collector: This Collector is used if the -Xingc or -XX:+UseConcMarkSweepGC is passed on the command line. This is also referred as Concurrent Mark Sweep Garbage collector. The concurrent collector is used to collect the tenured generation and does most of the collection concurrently with the execution of the application. The application is paused for short periods during the collection. A parallel version of the young generation copying collector is sued with the concurrent collector. Concurrent Mark Sweep Garbage collector is most widely used garbage collector in java and it uses algorithm to first mark object which needs to collected when garbage collection triggers.

3) The Incremental (Sometimes called train) low pause collector: This collector is used only if -XX:+UseTrainGC is passed on the command line. This garbage collector has not changed since the java 1.4.2 and is currently not under active development. It will not be supported in future releases so avoid using this and please see 1.4.2 GC Tuning document for information on this collector.
Important point to not is that -XX:+UseParallelGC should not be used with -XX:+UseConcMarkSweepGC. The argument passing in the J2SE platform starting with version 1.4.2 should only allow legal combination of command line options for garbage collector but earlier releases may not find or detect all illegal combination and the results for illegal combination are unpredictable. It’s not recommended to use this garbage collector in java.

JVM Parameters for garbage collection in Java
Garbage collection tuning is a long exercise and requires lot of profiling of application and patience to get it right. While working with High volume low latency Electronic trading system I have worked with some of the project where we need to increase the performance of Java application by profiling and finding what causing full GC and I found that Garbage collection tuning largely depends on application profile, what kind of object application has and what are there average lifetime etc. for example if an application has too many short lived object then making Eden space wide enough or larger will reduces number of minor collections. you can also control size of both young and Tenured generation using JVM parameters for example setting -XX:NewRatio=3 means that the ratio among the young and tenured generation is 1:3 , you got to be careful on sizing these generation. As making young generation larger will reduce size of tenured generation which will force Major collection to occur more frequently which pauses application thread during that duration results in degraded or reduced throughput. The parameters NewSize and MaxNewSize are used to specify the young generation size from below and above. Setting these equal to one another fixes the young generation. In my opinion before doing garbage collection tuning detailed understanding of garbage collection in java is must and I would recommend reading Garbage collection document provided by Sun Microsystems for detail knowledge of garbage collection in Java. Also to get a full list of JVM parameters for a particular Java Virtual machine please refer official documents on garbage collection in Java. I found this link quite helpful though http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html

Full GC and Concurrent Garbage Collection in Java
Concurrent garbage collector in java uses a single garbage collector thread that runs concurrently with the application threads with the goal of completing the collection of the tenured generation before it becomes full. In normal operation, the concurrent garbage collector is able to do most of its work with the application threads still running, so only brief pauses are seen by the application threads. As a fall back, if the concurrent garbage collector is unable to finish before the tenured generation fill up, the application is paused and the collection is completed with all the application threads stopped. Such Collections with the application stopped are referred as full garbage collections or full GC and are a sign that some adjustments need to be made to the concurrent collection parameters. Always try to avoid or minimize full garbage collection or Full GC because it affects performance of Java application. When you work in finance domain for electronic trading platform and with high volume low latency systems performance of java application becomes extremely critical an you definitely like to avoid full GC during trading period.


Java String Questions
 1) What is String in Java ? Is String is data type?
String in Java is not a primitive data type like int, long or double.  String is a class or in more simple term a user defined type. This is confusing for some one who comes from C background. String is defined in java.lang package and wrappers its content in a character array. String provides equals() method to compare two String and provides various other method to operate on String like toUpperCase() to convert String into upper case, replace() to replace String contents, substring() to get substring, split() to split long String into multiple String.

2) Why String is final in Java
String is final by design in Java, some of the points which makes sense why String is final is Security, optimization and to maintain pool of String in Java. for details on each of this point see Why String is final in Java.

3) What is Difference between String and StringBuffer in Java
This is probably the most common question on String I have seen in Java interviews. Though String and Stringbuffer are two different class they are used in context of concatenating two Strings, Since String is immutable in Java every operation which changes String produces new String, which can be avoided by using Stringbuffer. See String vs StringBuffer  for more details.

4) What is difference in String on C and Java
If you have mentioned C in your resume, then you are likely to face this String interview question. Well C String and Java String are completely different to each other, C String is a null terminated character array while String in Java is an Object. Also String is more feature rich in Java than C.

5) Why char array is better than String for storing password?
This String interview question is debatable and you might not agree with interviewer but this is also a chance to show that how deep and differently you can think of. One of the reason which people give Why you should store password in char array over String is related to immutability, since its not possible to remove erase contents of String but you can erase contents of char array. See Why char array preferred over String for password for complete discussion.

6) How do you compare two String in Java ?
This is another common String interview question which appears on fresher level interviews. There are multiple ways to compare two String like equals() method, equalsIgnoreCase() etc, You can also see 4 ways to compare String in Java for more examples. Main thing which interviewer checks is that whether candidate mentioned equality operator or not "==", comparing String with equality operator is common mistake which works in some case and doesn't work in other. next String interview question is follow-up up of this.

7) Can we compare String using == operator? What is risk?
As discussed in previous String question, You can compare String using equality operator but that is not suggested or advised because equality operator is used to compare primitives and equals() method should be used to compare objects. As we have seen in pitfall of autoboxing in Java that how equality operator can cause subtle issue while comparing primitive to Object, any way String is free from that issue because it doesn't have corresponding primitive type and not participate in autoboxing. Almost all the time comparing String means comparing contents of String i.e. characters and equals() method is used to perform character based comparison. equals() return true if two String points to same object or two String has same contents while == operator returns true if two String object points to same object but return false if two different String object contains same contents. That explains why sometime it works and sometime it doesn't. In short always use equals method in Java to check equality of two String object.

8) How substring method work in Java
This is one of the tricky Java question relate to String and until you are familiar with internals of String class, its difficult to answer. Substring shares same character array as original String which can create memory leak if original String is quite big and not required to retain in memory but unintentionally retained by substring which is very small in size and prevents large array from begin claimed during Garbage collection in Java. See How Substring works in Java for more details.

10)What is String pool in Java
Another tough Java question asked in  String interview. String pool is a special storage area in Java heap, mostly located on PerGen space, to store String literals like "abc". When Java program creates a new String using String literal, JVM checks for that String in pool and if String literal is already present in pool than same object is returned instead of creating a whole new object. String pool check is only performed when you create String as literal, if you create String using new() operator, a new String object will be created even if String with same content is available in pool.

9) What does intern() method do in Java
As discussed in previous String interview question, String object crated by new() operator is by default not added in String pool as opposed to String literal. intern() method allows to put an String object into pool.

11) Does String is thread-safe in Java
If you are familiar with the concept of immutability and thread-safety you can easily answer this String interview question in Java. Since String is immutable, it is thread-safe and it can be shared between multiple thread without external synchronization.

That's all on Java String interview question. In Summary there are lot of specifics about String which needs to be know for any one who has started Java programming and these String question will not just help to perform better on Java Interviews but also opens new door of learning about String. I didn't know many String related concepts until I come across these question which motivated to research and learn more about String in Java.


Why character array is better than String for storing password in Java?
1) Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used in String pool for reusability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. Since any one who has access to memory dump can find the password in clear text and that's another reason you should always used an encrypted password than plain text. Since Strings are immutable there is no way contents of Strings can be changed because any change will produce new String, while if you char[] you can still set all his element as blank or zero. So Storing password in character array clearly mitigates security risk of stealing password.

2) Java itself recommends using getPassword() method of JPasswordField which returns a char[] and deprecated getText() method which returns password in clear text stating security reason. Its good to follow advice from Java team and adhering to standard rather than going against it.

3) With String there is always a risk of printing plain text in log file or console but if use Array you won't print contents of array instead its memory location get printed. though not a real reason but still make sense.

String strPassword="Unknown";
char[] charPassword= new char[]{'U','n','k','w','o','n'};
System.out.println("String password: " + strPassword);
System.out.println("Character password: " + charPassword);

String password: Unknown
Character password: [C@110b053


That's all on why character array is better choice than String for storing passwords in Java.  Though using char[] is not just enough you need to erase content to be more secure. I also suggest working with hash'd or encrypted password instead of plaintext and clearing it from memory as soon as authentication is completed.

Why String is immutable in java?
1) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say

String A = "Test"
String B = "Test"

Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.

2)String has been widely used as parameter for many Java classes e.g. for opening network connection, you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.

In case, if String is not immutable, this would lead serious security threat , I mean some one can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access of those file. Because of immutability, you don't need to worry about those kind of threats. This reason also gel with, Why String is final in Java, by making java.lang.String final, Java designer ensured that no one overrides any behavior of String class.

3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally. Another important point to note about String is memory leak caused by SubString, which is not a thread related issues but something to be aware of.

4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java.  This one is also suggested by  Jaroslav Sedlacek in comments below. In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.

5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects. Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"


Security and String pool being primary reason of making String immutable, I believe there could be some more very convincing reasons as well, Please post those reasons as comments and I will include those on this post. By the way, above reason holds good to answer, another Java interview questions "Why String is final in Java".  Also to be immutable you have to be final, so that your subclass doesn't break immutability.  what do you guys think ?

How subString() works?
 Question starts with normal chit chat, and Interviewer ask,  "Have you used substring method in Java", and my friend proudly said Yes, lot many times, which brings a smile on interviewer's face. He says well, that’s good. Next question was Can you explain what does substring do? My friend got an opportunity to show off his talent, and how much he knows about Java API;  He said substring method is used to get parts of String in Java. It’s defined in java.lang.String class, and it's an overloaded method. One version of substring method takes just beginIndex, and returns part of String started from beginIndex till end, while other takes two parameters, beginIndex and endIndex, and returns part  of String starting from beginIndex to endIndex-1. He also stressed that every time you call  substring() method in Java,  it will return a new String because String is immutable in Java.

substring in Java , java substring method
Next question was, what will happen if beginIndex is equal to length in substring(int beginIndex), no it won't throw IndexOutOfBoundException instead it will return empty String. Same is the case when beginIndex and endIndex is equal, in case of second method. It will only throw StringIndexBoundException when beginIndex is negative, larger than endIndex or larger than length of String.

So far so good, my friend was happy and interview seems going good, until Interviewee asked him,  Do you know how substring works in Java? Most of Java developers fail here, because they don't know how exactly substring method works, until they have not seen the code of java.lang.String. If you look substring method inside String class, you will figure out that it calls String (int offset, int count, char value []) constructor to create new String object. What is interesting here is, value[], which is the same character array used to represent original string. So what's wrong with this?

In case If you have still not figured it out, If the original string is very long, and has array of size 1GB, no matter how small a substring is, it will hold 1GB array.  This will also stop original string to be garbage collected, in case if doesn't have any live reference. This is clear case of memory leak in Java, where memory is retained even if it's not required. That's how substring method creates memory leak.
How SubString in Java works
Obviously next question from interviewer would be,  how do you deal with this problem? Though you can not go, and change Java substring method, you can still make some work around, in case you are creating substring of significant longer String. Simple solution is to trim the string, and keep size of character array according to length of substring. Luckily java.lang.String has constructor to do this, as shown in below example.

// comma separated stock symbols from NYSE
String listOfStockSymbolsOnNYSE = getStockSymbolsForNYSE();

//calling String(string) constructor
String apple = new String(listOfStockSymbolsOnNYSE.substring(appleStartIndex,appleEndIndex));


If you look code on java.lang.String class, you will see that this constructor trim the array, if it’s bigger than String itself.

 public String(String original) {
        ...

        if (originalValue.length > size) {
            // The array representing the String is bigger than the new
            // String itself.  Perhaps this constructor is being called
            // in order to trim the baggage, so make a copy of the array.
            int off = original.offset;
            v = Arrays.copyOfRange(originalValue, off, off+size);

        } else {

            // The array representing the String is the same
            // size as the String, so no point in making a copy.
            v = originalValue;
        }
    ...

    }

Another way to solve this problem is to call intern() method on substring, which will than fetch an existing string from pool or add it if necessary. Since the String in the pool is a real string it only take space as much it requires. It’s also worth noting that sub-strings are not internalized, when you call intern() method on original String. Most developer successfully answers first three questions, which is related to usage of substring, but they get stuck on last two, How substring creates memory leak or How substring works. It's not completely there fault, because what you know is that every time substring() returns new String which is not exactly true, since it’s backed by same character array.

This was the only interview question, which bothers my friend little otherwise, its standard service level company  Java interview in India. By the way, he got the call a day after ,even though he struggled little bit on How SubString method works in Java, and that was the reason he shared this interview experience with me.


What is java enum?

What is Enum in Java
Enum in Java is a keyword, a feature which is used to represent fixed number of well known values in Java, For example Number of days in Week, Number of planets in Solar system etc. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing , Generics, varargs and static import. Java Enum as type is more suitable on certain cases for example representing state of Order as NEW, PARTIAL FILL, FILL or CLOSED. Enumeration(Enum) was not originally available in Java though it was available in other language like C and C++ but eventually Java realized and introduced Enum on JDK 5 (Tiger) by keyword Enum. In this Java Enum tutorial we will see different Enum example in Java and learn using Enum in Java. Focus of this Java Enum tutorial will be on different features provided by Enum in Java and how to use them. If you have used Enumeration before in C or C++ than you will not be uncomfortable with Java Enum but in my opinion Enum in Java is more rich and versatile than in any other language. One of the common use of Enum which emerges is Using Enum to write Singleton in Java, which is by far easiest way to implement Singleton and handles several issues related to thread-safety, Serialization automatically.



How to represent enumerable value without Java enum
java enum example, enum in java tutorialSince Enum in Java is only available from Java 1.5 its worth to discuss how we used to represent enumerable values in Java prior JDK 1.5 and without it. I use public static final constant to replicate enum like behavior. Let’s see an Enum example in Java to understand the concept better. In this example we will use US Currency Coin as enumerable which has values like PENNY (1) NICKLE (5), DIME (10), and QUARTER (25).

class CurrencyDenom {
            public static final int PENNY = 1;
            public static final int NICKLE = 5;
            public static final int DIME = 10;
            public static final int QUARTER = 25;

      }

class Currency {
   int currency; //CurrencyDenom.PENNY,CurrencyDenom.NICKLE,
                 // CurrencyDenom.DIME,CurrencyDenom.QUARTER
}

 Though this can server our purpose it has some serious limitations:

 1) No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to currency e.g. 99 though there is no coin to represent that value.

 2) No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print NICKLE it will print "5" instead of "NICKLE"

3) No namespace: to access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5

Java Enum is answer of all this limitation. Enum in Java is type-safe, provides meaningful String names and has there own namespace. Now let's see same example using Enum in Java:

public enum Currency {PENNY, NICKLE, DIME, QUARTER};

Here Currency is our enum and PENNY, NICKLE, DIME, QUARTER are enum constants. Notice curly braces around enum constants because Enum are type like class and interface in Java. Also we have followed similar naming convention for enum like class and interface (first letter in Caps) and since Enum constants are implicitly static final we have used all caps to specify them like Constants in Java.

What is Enum in Java
Now back to primary questions “What is Enum in java” simple answer Enum is a keyword in java and on more detail term Java Enum is type like class and interface and can be used to define a set of Enum constants. Enum constants are implicitly static and final and you can not change there value once created. Enum in Java provides type-safety and can be used inside switch statment like int variables. Since enum is a keyword you can not use as variable name and since its only introduced in JDK 1.5 all your previous code which has enum as variable name will not work and needs to be re-factored.

Benefits of Enums in Java:
1) Enum is type-safe you can not assign anything else other than predefined Enum constants to an Enum variable. It is compiler error to assign something else unlike the public static final variables used in Enum int pattern and Enum String pattern.

2) Enum has its own name-space.

3) Best feature of Enum is you can use Enum in Java inside Switch statement like int or char primitive data type.we will also see example of using java enum in switch statement in this java enum tutorial.

4) Adding new constants on Enum in Java is easy and you can add new constants without breaking existing code.


Important points about Enum in Java
1) Enums in Java are type-safe and has there own name-space. It means your enum will have a type for example "Currency" in below example and you can not assign any value other than specified in Enum Constants.

public enum Currency {PENNY, NICKLE, DIME, QUARTER};
Currency coin = Currency.PENNY;
coin = 1; //compilation error 


2) Enum in Java are reference type like class or interface and you can define constructor, methods and variables inside java Enum which makes it more powerful than Enum in C and C++ as shown in next example of Java Enum type.


3) You can specify values of enum constants at the creation time as shown in below example:
public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};
But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value , see below example.
 
public enum Currency {
        PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
        private int value;

        private Currency(int value) {
                this.value = value;
        }
}; 
Constructor of enum in java must be private any other access modifier will result in compilation error. Now to get the value associated with each coin you can define a public getValue() method inside java enum like any normal java class. Also semi colon in the first line is optional.


4) Enum constants are implicitly static and final and can not be changed once created. For example below code of java enum will result in compilation error:

Currency.PENNY = Currency.DIME;
The final field EnumExamples.Currency.PENNY cannot be re assigned.



5) Enum in java can be used as an argument on switch statment and with "case:" like int or char primitive type. This feature of java enum makes them very useful for switch operations. Let’s see an example of how to use java enum inside switch statement: 

   Currency usCoin = Currency.DIME;
    switch (usCoin) {
            case PENNY:
                    System.out.println("Penny coin");
                    break;
            case NICKLE:
                    System.out.println("Nickle coin");
                    break;
            case DIME:
                    System.out.println("Dime coin");
                    break;
            case QUARTER:
                    System.out.println("Quarter coin");
    }
 
from JDK 7 onwards you can also String in Switch case in Java code.

6) Since constants defined inside Enum in Java are final you can safely compare them using "==" equality operator as shown in following example of  Java Enum:

Currency usCoin = Currency.DIME;
if(usCoin == Currency.DIME){
  System.out.println("enum in java can be compared using ==");
}

By the way comparing objects using == operator is not recommended, Always use equals() method or compareTo() method to compare Objects.

7) Java compiler automatically generates static values() method for every enum in java. Values() method returns array of Enum constants in the same order they have listed in Enum and you can use values() to iterate over values of Enum  in Java as shown in below example:

for(Currency coin: Currency.values()){
        System.out.println("coin: " + coin);
}

And it will print:
coin: PENNY
coin: NICKLE
coin: DIME
coin: QUARTER
              
Notice the order its exactly same with defined order in enums.



8) In Java Enum can override methods also. Let’s see an example of overriding toString() method inside Enum in Java to provide meaningful description for enums constants.

public enum Currency {
  ........
     
  @Override
  public String toString() {
       switch (this) {
         case PENNY:
              System.out.println("Penny: " + value);
              break;
         case NICKLE:
              System.out.println("Nickle: " + value);
              break;
         case DIME:
              System.out.println("Dime: " + value);
              break;
         case QUARTER:
              System.out.println("Quarter: " + value);
        }
  return super.toString();
 }
};       
And here is how it looks like when displayed:
Currency usCoin = Currency.DIME;
System.out.println(usCoin);

output:
Dime: 10


    
9) Two new collection classes EnumMap and EnumSet are added into collection package to support Java Enum. These classes are high performance implementation of Map and Set interface in Java and we should use this whenever there is any opportunity.



10) You can not create instance of enums by using new operator in Java because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.


11) Instance of Enum in Java is created when any Enum constants are first called or referenced in code.


12) Enum in Java can implement the interface and override any method like normal class It’s also worth noting that Enum in java implicitly implement both Serializable and Comparable interface. Let's see and example of how to implement interface using Java Enum:

public enum Currency implements Runnable{
  PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
  private int value;
  ............
       
  @Override
  public void run() {
  System.out.println("Enum in Java implement interfaces");
               
   }
}



13) You can define abstract methods inside Enum in Java and can also provide different implementation for different instances of enum in java.  Let’s see an example of using abstract method inside enum in java

public enum Currency implements Runnable{
          PENNY(1) {
                  @Override
                  public String color() {
                          return "copper";
                  }
          }, NICKLE(5) {
                  @Override
                  public String color() {
                          return "bronze";
                  }
          }, DIME(10) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          }, QUARTER(25) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          };
          private int value;

          public abstract String color();
       
          private Currency(int value) {
                  this.value = value;
          }
          ..............
  }     
In this example since every coin will have different color we made the color() method abstract and let each instance of Enum to define   there own color. You can get color of any coin by just calling color() method as shown in below example of java enum:

System.out.println("Color: " + Currency.DIME.color());


Enum Java valueOf example
One of my reader pointed out that I have not mention about valueOf method of enum in Java, which is used to convert String to enum in java.  Here is what he has suggested, thanks @ Anonymous
“You could also include valueOf() method of enum in java which is added by compiler in any enum along with values() method. Enum valueOf() is a static method which takes a string argument and can be used to convert a String into enum. One think though you would like to keep in mind is that valueOf(String) method of enum will throw "Exception in thread "main" java.lang.IllegalArgumentException: No enum const class" if you supply any string other than enum values.

Another of my reader suggested about ordenal() and name() utility method of java enum Ordinal method of Java Enum returns position of a Enum constant as they declared in enum while name()of Enum returns the exact string which is used to create that particular Enum constant.” name() method can also be used for converting Enum to String in Java.

How to convert enum to string and string to enum in java?
Converting Enum into String and String to Enum in Java is becoming a common task with growing use of Enum. Enum is very versatile in Java and preferred choice to represent bounded data and since is almost used everywhere to carry literal value its important to know how to convert Enum to String in Java. In this article we will see both first converting Strings to Enum in Java and than Changing an Enum to String in Java with Example. I thought about this Enum tutorial when I wrote 10 Examples of Enum in Java. I missed String to Enum conversion and one of reader pointed out that. So here we have now.

Enum to String to Enum in Java
This article is in continuation of other conversion related post e.g. how to convert Date to String in Java and How to Convert String to Integer in Java. As these are common needs and having best way to do things in mind saves lot of time while coding.

Convert Enum to String in Java Example
Convert Enum to String to Enum in Java example tutorialEnum classes by default provides valueOf (String value) method which takes a String parameter and converts it into enum. String name should match with text used to declare Enum in Java file. Here is a complete code example of String to Enum in Java
Code Example String to Enum:

public class EnumTest {

    private enum LOAN {

        HOME_LOAN {
            @Override
            public String toString() {
                return "Always look for cheaper Home loan";
            }
        },
        AUTO_LOAN {
            @Override
            public String toString() {
                return "Cheaper Auto Loan is better";
            }
        },
        PEROSNAL_LOAN{
            @Override
            public String toString() {
                return "Personal loan is not cheaper any more";
            }
        }
    }

    public static void main(String[] args) {
    
        //Exmaple of String to Enum in Java
        LOAN homeLoan = LOAN.valueOf("HOME_LOAN");
        System.out.println(homeLoan);
        LOAN autoLoan = LOAN.valueOf("AUTO_LOAN");
        System.out.println(autoLoan);
        LOAN personalLoan = LOAN.valueOf("PEROSNAL_LOAN");
        System.out.println(personalLoan);
    
    }

Output:
Always look for cheaper Home loan
Cheaper Auto Loan is better
Personal loan is not cheaper any more



Convert Enum to String in Java Example
Now let's do opposite convert an Enum into String in Java, there are multiple ways to do it one way is to return exact same string used to declare ENUM from toString() method of Enum, otherwise if you are using toString() for othre purpose than you can use default static name() method to convert an Enum into String. Java by default adds name() method into every Enum and it returns exact same text which is used to declare enum in Java file.

Code Example Enum to String

public static void main(String[] args) {
    
        //Exmaple of Enum to String in Java
        String homeLoan = LOAN.HOME_LOAN.name();
        System.out.println(homeLoan);
        String autoLoan = LOAN.AUTO_LOAN.name();
        System.out.println(autoLoan);
        String personalLoan = LOAN.PERSONAL_LOAN.name();
        System.out.println(personalLoan);
     
   
    
    }

Output:
HOME_LOAN
AUTO_LOAN
PERSONAL_LOAN




Two ways to split string in java?
Java String Split Example
I don't know how many times I need to Split String in Java. Split is very common operation given various data sources e.g CSV file which contains input string in form of large String separated by comma. Splitting is necessary and Java API has great support for it. Java provides two convenience methods to split strings first within the java.lang.String class itself: split (regex) and other in java.util.StringTokenizer. Both are capable to split the string by any delimiter provided to them. Since String is final in Java every split-ed String is a new String in Java.


split string example in JavaIn this article we will see how to split string in Java both by using String’s split() method and StringTokenizer. If you have any doubt on anything related to split string please let me know and I will try to help. Since String is one of the most common Class in Java and we always need to do something with String; I have created lot of How to with String e.g.
 How to replace String in Java,  convert String to Date in Java or convert String to Integer in Java. If you feel enthusiastic about String and you can also learn some bits from those post. If you like to read interview articles about String in Java you can see :

How SubString works in Java
What is the difference between StringBuffer vs StringBuilder
Why String is popular HashMap key in Java,

These articles helps to understand String better in Java.
String Split Example Java
Let's see an example of splitting string in Java by using split() function:

//split string example

String assetClasses = "Gold:Stocks:Fixed Income:Commodity:Interest Rates";
String[] splits = asseltClasses.split(":");

System.out.println("splits.size: " + splits.length);

for(String asset: assetClasses){
System.out.println(asset);
}

OutPut
splits.size: 5
Gold
Stocks
Fixed Income
Commodity
Interest Rates



In above example we have provided delimiter or separator as “:” to split function which expects a regular expression and used to split the string.

Now let see another example of split using StringTokenizer

//string split example StringTokenizer

StringTokenizer stringtokenizer = new StringTokenizer(asseltClasses, ":");
while (stringtokenizer.hasMoreElements()) {
System.out.println(stringtokenizer.nextToken());
}

OutPut
Gold
Stocks
Fixed Income
Commodity
Interest Rates



How to Split Strings in Java – 2 Examples

My personal favorite is String.split () because it’s defined in String class itself and its capability to handle regular expression which gives you immense power to split the string on any delimiter you ever need. Though it’s worth to remember following points about split method in Java


1) Some special characters need to be escaped while using them as delimiters or separators e.g. "." and "|".







//string split on special character “|”

String assetTrading = "Gold Trading|Stocks Trading|Fixed Income Trading|Commodity Trading|FX trading";

String[] splits = assetTrading.split("\\|");  // two \\ is required because "\"     itself require escaping

for(String trading: splits){
System.out.println(trading);
}

OutPut:
Gold Trading
Stocks Trading
Fixed Income Trading
Commodity Trading
FX trading


// split string on “.”

String smartPhones = "Apple IPhone.HTC Evo3D.Nokia N9.LG Optimus.Sony Xperia.Samsung Charge”;

String[] smartPhonesSplits = smartPhones.split("\\.");

for(String smartPhone: smartPhonesSplits){
System.out.println(smartPhone);
}


OutPut:
Apple IPhone
HTC Evo3D
Nokia N9
LG Optimus
Sony Xperia
Samsung Charge


2) You can control number of split by using overloaded version split (regex, limit). If you give limit as 2 it will only creates two strings. For example in following example we could have total 4 splits but if we just want to create 2 we can use limit.

//string split example with limit

String places = "London.Switzerland.Europe.Australia";
String[] placeSplits = places.split("\\.",2);

System.out.println("placeSplits.size: " + placeSplits.length );

for(String contents: placeSplits){
System.out.println(contents);
}

Output:
placeSplits.size: 2
London
Switzerland.Europe.Australia


To conclude the topic StringTokenizer is old way of tokenizing string and with introduction of split since JDK 1.4 its usage is discouraged. No matter what kind of project you work you often need to split string in Java so better get familiar with these API.


Read more: http://javarevisited.blogspot.com/2011/09/string-split-example-in-java-tutorial.html#ixzz2Ttg7db7Q



Difference between string, string buffer, string builder
 String vs StringBuffer vs StringBuilder in Java
Difference between String, Stringbuffer and StringBuilder
String is one of the most important classes in Java and anyone who starts with Java programming uses String to print something on console by using famous System.out.println() statements. Many Java beginners not aware that String is immutable and final in Java and every modification in String result creates a new String object. So How do you manipulate String in Java without creating String garbage? StringBuilder and StringBuffer is answer of this question. StringBuffer is old class but StringBuilder is newly added in Java 5 along with major improvements like Enum, Generics, varargs methods and Autoboxing in Java. No matter which kind of application you are working you will find heavy usage of Java String class but if you do profiling of your application you will find that String is the one class which creates lots of garbage because of many temporary String created in program. In this Java tutorial we will see What is String in Java, some important properties of String in Java, What is StringBuffer in Java , When to use StringBuffer in Java , StringBuilder in Java and how it can be used in place of StringBuffer,  What are differences between String and StringBuffer and StringBuilder in Java  which is a frequently asked core Java question and mostly String vs StringBuilder vs StringBuffer. Now let's start with String.


Differences between String, StringBuffer and StringBuilder in Java
String in Java
Before looking difference between String and StringBuffer or StringBuilder let’s see some fundamental properties of String Class in Java

string and stringbuffer, string vs stringbuffer vs stringbuilder1) String is immutable in Java:  String is by design immutable in Java you can check this post for reason. Immutability offers lot of benefit to the String class e.g. his hashcode value can be cached which makes it a faster hashmap key and one of the reason why String is a popular key in HashMap. Because String is final it can be safely shared between multiple threads  without any extra synchronization.

2)when we represent string in double quotes like "abcd" they are referred as String literal and String literals are created in String pools. When you compare two String literals using equality operator "==" it returns true because they are actually same instance of String. Anyway comparing object with equality operator is bad practice in Java and you should always use equals method to check equality.

3) "+" operator is overloaded for String and used to concatenated two string. Internally "+" operation is implemented using either StringBuffer or StringBuilder.

4) Strings are backed up by character Array and represented in UTF-16 format. By the way this behavior can cause memory leak in String because same character array is shared between source String and SubString which can prevent source String from being garbage collected. See How SubString works in Java for more details.

5) String class overrides equals() and hashcode() method and two Strings are considered to be equal if they contain exactly same character in same order and in same case. If you want ignore case comparison of two strings consider using equalsIgnoreCase() method. See  how to correctly override equals method in Java  to learn more about best practices on equals method. Another worth noting point is that equals method must be consistent with compareTo() method for String because SortedSet and SortedMap e.g. TreeMap uses compareTo method to compare String in Java.

7) toString() method provides String representation of any object and its declared in Object class and its recommended for other class to implement this and provide String representation.

8) String is represented using UTF-16 format in Java.

9) In Java you can create String from char array, byte array, another string, from StringBuffer or from StringBuilder. Java String class provides constructor for all of these.


Problem with String in Java
difference between String and StringBuffer and StringBuilder, string vs stringbuffer One of its biggest strength Immutability is also biggest problem of Java String if not used correctly. many a times we create a String and then perform a lot of operation on them e.g. converting string into uppercase, lowercase , getting substring out of it , concatenating with other string etc. Since String is an immutable class every time a new String is created and older one is discarded which creates lots of temporary garbage in heap. If String are created using String literal they remain in String pool. To resolve this problem Java provides us two Classes StringBuffer and StringBuilder. String Buffer is an older class but StringBuilder is relatively new and added in JDK 5.


Differences between String and StringBuffer in Java
Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method. String vs StringBuffer or what is difference between StringBuffer and String is one of the popular Java interview questions for either phone interview or first round. Now days they also include StringBuilder and ask String vs StringBuffer vs StringBuilder. So be preparing for that. In the next section we will see difference between StringBuffer and StringBuilder in Java.

Difference between StringBuilder and StringBuffer in Java
StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than StringBuffer class. You can also use "+" for concatenating two string because "+" operation is internal implemented using either StringBuffer or StringBuilder in Java. If you see StringBuilder vs StringBuffer you will find that they are exactly similar and all API methods applicable to StringBuffer are also applicable to StringBuilder in Java. On the other hand String vs StringBuffer is completely different and there API is also completely different, same is true for StringBuilder vs String.

Read more: http://javarevisited.blogspot.com/2011/07/string-vs-stringbuffer-vs-stringbuilder.html#ixzz2TtgOeOjS


What is finalize method in java?
 10 points on finalize method in Java – Tutorial Example
finalize method in java is a special method much like main method in java. finalize() is called before Garbage collector reclaim the Object, its last chance for any object to perform cleanup activity i.e. releasing any system resources held, closing connection if open etc. Main issue with finalize method in java is its not guaranteed by JLS that it will be called by Garbage collector or exactly when it will be called, for example an object may wait indefinitely after becoming eligible for garbage collection and before its finalize() method gets called. similarly even after finalize gets called its not guaranteed it will be immediately collected. Because of above reason it make no sense to use finalize method for releasing critical resources or perform any time critical activity inside finalize. It may work in development in one JVM but may not work in other JVM. In this java tutorial we will see some important points about finalize method in Java, How to use finalize method, what to do and what not to do inside finalize in Java.

what is finalize method in Java – Tutorial Example
1) finalize() method is defined in java.lang.Object class, which means it available to all the classes for sake of overriding. finalize method is defined as protected which leads to a popular core java question "Why finalize is declared protected instead of public"? well I don't know the exact reason its falls in same category of questions like why java doesn't support multiple inheritance which can only be answer accurately by designers of Java. any way making finalize protected looks good in terms of following rule of encapsulation which starts with least restrictive access modifier like private but making finalize private prevents it from being overridden in subclass as you can not override private methods, so making it protected is next obvious choice.

2) One of the most important point of finalize method is that its not automatically chained like constructors. If you are overriding finalize method than its your responsibility to call finalize() method of super-class, if you forgot to call then finalize of super class will never be called. so it becomes critical to remember this and provide an opportunity to finalize of super class to perform cleanup. Best way to call super class finalize method is to call them in finally block as shown in below example. this will granted that finalize of parent class will be called in all condition except when JVM exits:

 @Override
    protected void finalize() throws Throwable {
        try{
            System.out.println("Finalize of Sub Class");
            //release resources, perform cleanup ;
        }catch(Throwable t){
            throw t;
        }finally{
            System.out.println("Calling finalize of Super Class");
            super.finalize();
        }
    
    }

3) finalize method is called by garbage collection thread before collecting object and if not intended to be called like normal method.

4) finalize gets called only once by GC thread, if object revive itself from finalize method than finalize will not be called again.

5) Any Exception thrown by finalize method is ignored by GC thread and it will not be propagated further, in fact I doubt if you find any trace of it.

6) There is one way you can guarantee running of finalize method by calling System.runFinalization() and
Runtime.getRuntime().runFinalization(). These methods ensures that JVM call finalize() method of all object which are eligible for garbage collection and whose finalize has not yet called.

Alternative of finalize method for cleanup.
what is finalize method in Java – Tutorial ExampleSo far its seems we are suggesting not to use finalize method because of its non guaranteed behavior but than what is alternative of releasing resource, performing cleanup because there is no destructor in Java. Having a method like close() or destroy() make much sense for releasing resources held by classes. In fact JDK library follows this. if you look at java.io package which is a great example of acquiring system resource like file descriptor for opening file, offers close() method for opening stream and close() for closing it. in fact its one of the best practice to call close  method from finally block in java. Only caveat with this approach is its not automatic, client has to do the cleanup and if client forgot to do cleanup there are chances of resources getting leaked, which again suggest us that we could probably give another chance to finalize method. You will be pleased to know that Java 7 has added automatic resource management feature which takes care of closing all resource opened inside try block automatically, leaving no chance of manual release and leakage.

When to use finalize method in Java
As last paragraph pointed out that there are certain cases where overriding finalize make sense, like an ultimate last attempt to cleanup the resource. If a Java class is made to held resource like input output devices, JDBC connection than you should override finalize and call its close() method from finalize. though there is no guarantee that it will run and release the resource timely best part is we are not relying on it. It just another last attempt to release the resource which most likely have been already released due to client calling close() method. This technique is heavily used inside Java Development library. look at below example of finalize method from FileInputStream.java

 protected void finalize() throws IOException {
        if ((fd != null) &&  (fd != FileDescriptor.in)) {

            /*
             * Finalize should not release the FileDescriptor if another
             * stream is still using it. If the user directly invokes
             * close() then the FileDescriptor is also released.
             */
            runningFinalize.set(Boolean.TRUE);
            try {
                close();
            } finally {
                runningFinalize.set(Boolean.FALSE);
            }
        }

    }

What not to do in finalize method in Java
trusting finalize method for releasing critical resource is biggest mistake java programmer can made. suppose instead of relying on close() method to release file descriptor, you rely on finalize to relapse it for you. Since there is no guaranteed when finalize method will run you could effectively lock hundreds of file-descriptor of earlier opened file or socket and there is high chance that your application will ran out of file-descriptor and not able to open any new file. Its best to use finalize as last attempt to do cleanup but never use finalize as first or only attempt.

That's all on finalize method in Java. as you have seen there are quite lot of specifics about finalize method which java programmer should remember before using finalize in java. In one liner don’t do time critical task on finalize method but use finalize with caution.

Read more: http://javarevisited.blogspot.com/2012/03/finalize-method-in-java-tutorial.html#ixzz2Tthcliaw













Saturday, May 18, 2013

SQLITE3 install - 6 steps only

1. wget http://www.sqlite.org/sqlite-autoconf-3070603.tar.gz
 2. tar xvfz sqlite-autoconf-3070603.tar.gz
 3. cd sqlite-autoconf-3070603
4. ./configure
5. make
6. make install

Reference -
http://www.thegeekstuff.com/2011/07/install-sqlite3/#more-7923

Imacro Page, Step timeout command


1.Page Timeout - 

SET !TIMEOUT_PAGE 15 
 
2. Step Timeout -
 
SET !TIMEOUT_STEP 100
TAG POS=1 TYPE=* ATTR=TXT:Transactionprocessed 

Imacro save page command --

Its really useful to store the current page as following format -

SAVEAS TYPE=(CPL|MHT|HTM|TXT|EXTRACT|BMP|PNG|JPEG) FOLDER=folder_name FILE=file_name


reference -

http://wiki.imacros.net/SAVEAS