Translate the content to your language. Select your Language below.

Wednesday, September 25, 2013

Most common mistakes we do in Java programming

Capitalisation of key words

Since you get into the habit of writing class names in capital letters you will occasionally find yourself writing keywords such as class andint with a capital beginning letter. The compiler will object to this and will issue an error message which depends on which keyword was capitalised. The compiler will issue an error message such as:
Line nn: class or interface declaration expected
when, for example, you capitalise the keyword class.

Writing a string over a new line

Sometimes you will need to write a long string. A common error is to have a new line embedded in the string. The compiler will object to this and will issue an error message such as:
Line nn: ';' expected
When this happens the solution is to split the string into two, making sure that neither string has a new line in it, and concatenate them with +. Thus you might replace:
String s = "A very long string which just happens to go over the end of a 
line and causes a problem with the compiler";
with:
String s = "A very long string which just happens to go over the end "+
"of a line and causes a problem with the compiler"

Missing brackets in a no-argument message

When you use a method which has no arguments you should place brackets after the name of the method. For example, if you have declared a method carryOut with no arguments and you want to send a message corresponding to the method to the object objSend then you should code this as:
objSend.carryOut()
rather than:
objSend.carryOut 
The compiler will usually emit an error message of the form:
Line nn: Invalid expression statement

Forgetting to import a package

This one of the most common errors that inexperienced Java programmers make. If you forget to put the required import statement at the beginning of a program, then the compiler will respond with a message such as:
Line nn: Class xxxx not found in type declaration
Don't forget, though, that java.lang is imported automatically and, hence, does not need an import statement.

Treating a static method as if it were an instance method

Static methods are associated with messages sent to classes rather than objects. A common error is to send static method messages to objects. For example, in order to calculate the absolute value of an int value and place it into the int variable you should write:
int result = Math.abs(value);
rather than:
int result = value.abs();
This gives rise to a variety of syntax errors. The most common one is of the form:
Line nn: Method yyyy not found in class xxxx.
where yyyy is the name of the method and xxxx is the name of the class within which it is called.

Case-sensitive errors with classes

This is another category of error which is very common. Java is case sensitive so, for example, it will not recognise string as a valid type in the language as you should have written String. It will generate an error message of the form:
Line nn: Class xxxx not found in type declaration.
where xxxx is the name of the class which has not been given the correct capitalisation.

Case-sensitive errors with variables

It is also quite easy to miss the fact that variables are case sensitive. For example, you may have declared the variable linkEdit as an int and then tried to refer to linkEdit within a class. This gives rise to error messages of the form
Line nn: Undefined variable: xxxx
where xxxx is the name of the variable which has been mistyped.

Missing } brackets

This is a common programming error in any programming language and can be eradicated by means of a proper indentation scheme.

Missing class brackets

A common bracketing error that you will often make is to omit the final } bracket that delimits the end of a class.

Writing the wrong format for a class method

Class methods have the form:
ClassName.MethodName(Argument(s))
A common error is to forget the class name. If you do, then you will get an error message of the form:
Line nn: '}' expected

Specifying method arguments wrongly

When you define classes you should prefix each argument with the name of a scalar type or the name of an existing class. For example:
public void tryIt(int a, int b, URL c)
A common error that programmers from other languages make is to forget to prefix every argument with its type. For example, an erroneous version of the definition above would be:
public void tryIt(int a, b URL c)
This type of error will give rise to error messages of the form:
Line nn: Identifier expected

Forgetting the fact you should send messages to objects

This is a common error committed by programmers who have only recently changed to object-oriented programming. As an example of this consider the method tryIt, which has two int arguments and which delivers anint value. Assume that this method is involved in sending a message to an object destination. This should be written as:
int newVal = destination. tryIt(arg1, arg2)
where the arguments are ints which have been declared somewhere. A common mistake is to write this as:
int newVal = tryIt(destination, arg1,arg2)
This gives rise to error messages of the form:
Line nn: ')' expected

Assuming that == stands for value equality

== is used with scalars as a means of comparing values. However, when it is applied to objects then it compares addresses. For example, the if statement:
if(newObj1 == newObj2){
...
}
will execute the code denoted by the three dots only if the first object occupies the same address as the second object. If the objects occupied different addresses, but still had the same values for their instance variables, then it would evaluate to false. Unfortunately this does not give rise to any syntax errors, but will show up when any program containing the error is executed.

Omitting void in methods

When a method returns no result, but just carries out some action, you need to use the keyword void in front of the name of the method. If you do not use this keyword, then it will give rise to error messages of the form:
Line nn: Invalid method declaration; return type required

Omitting break from case statements

This is an error which is committed in both object-oriented and procedural languages. If you want the branch of a case statement to just finish and exit to the end of the case statement, then don't forget to include thebreak statement as the last statement in the branch. If you do not do this, then execution will continue with the next branch underneath the one in which the break statement was omitted.

Omitting the return in a method

When a method returns a value, then the body of the method should include at least one return statement which returns the right type of value. Failing to do this will generate an error message of the form:
Line nn: Return required at end of xxxx
where xxxx is the method which does not contain the return.

Making an instance variable private and then referring to it by name in another class

When you tag an instance variable as private you are not allowed to access it by name outside its class. The only way that you can access such instance variables is through methods which are declared in the class in which the instance variables are defined. This gives rise to error messages of the form:
Line nn: Variable xx in class xxxx not accessible from class yyyy
where xx is the private variable, xxxx is the class in which it is defined and class yyyy is the class in which it is referred to.

Using a variable before it is given a value

Again this is a common error found in both object-oriented and procedural languages. In Java, scalars are intialised to zero or some default value so there will be no error indication and any problems that arise will be signaled by erroneous results or some side effect such as an array going over its bounds. Objects will be initalised to null and any attempt to reference an uninitialised object will be caught at run time.

Assuming the wrong type of value is generated by a message

This is a common error to make when using the Java packages. A typical example is using a method which delivers a string that contains digits and treating it like an integer. For example, the method getInteger withinjava.lang.Integer delivers an Integer and any attempt to use that value as, say, an int will give rise to an error message of the form:
Line nn: Incompatible type for declaration can't convert xxxx to yyyy

Confusing prefix operators with postfix operators

This is an error that comes with any C-like language. Postfix operators such as ++ and -- deliver the old value of the variable to which they are applied, while prefix operators deliver the new value. Thus, if x is 45 and the statement:
y = ++x 
is executed, then y and x both become 46. If the statement
y = x++
is executed, then y becomes 45, while x becomes 46. These errors will not be signalled at compile time, but will emerge during run time.

Forgetting that arguments are passed by reference to methods if they are objects

When an object is used as an argument to a method, then its address is passed over and not a value. This means that you can assign values to such arguments. If you treat them as values this will not strictly be an error, but will not be making use of the full facilities of an object-oriented programming language.

Forgetting that scalars are passed by value to methods

You cannot treat an argument which is a scalar as if it can be assigned to. This will not be signalled as a syntax error. However, it will show up as a run-time error when you write code which assumes that the scalar has been given a value by a method.

Misusing size when applied to strings and arrays

size is an instance variable associated with arrays and a method when associated with strings. If you mix them up by, for example writing:
arrayVariable.size()  
or
stringVariable.size
then the first would generate an error message of the form:
Line nn: Method size() not found in class java.lang.Object 
and the second would generate an error message of the form:
Line nn: No variable size defined in java.lang.String

Using a constructor which does not exist

You may use a constructor which has not been defined. For example, you may have a class X which has a one int constructor, a two int constructor and a threeint constructor and yet you may have used a four intconstructor. This would be picked up at compile time and an error of the form:
Line nn: No constructor matching xxxx found in class yyyy
would be generated, where xxxx is the signature of the constructor that you have tried using and yyyy is the name of the class which it should have been defined in.

Calling a constructor in a constructor with the same name

For example, you may have defined a class X with a two int constructor and a one int constructor and inside the two int constructor there is a reference to X(argument). This will be flagged as an error and will generate an error message of the form:
Line nn: Method xxxx not found in yyyy
where xxxx is the name of the constructor and its arguments and yyyy is the name of the class which it is defined in. The solution is to use the this keyword.

Assuming that two-dimensional arrays are directly implemented in Java

This gives rise to erroneous code such as:
int [,] arrayVariable = new [10,20] int
This is illegal and will give rise to an errors of the form:
Line nn: Missing term
and:
Line nn: ']' expected
You can implement many-dimensional arrays in Java, but they are treated like single-dimension arrays which contain single-dimensional arrays which contain single dimension arrays, etc.

Treating a scalar like an object

Scalars such as int and float are not objects. However, sometimes you want to treat them as such, for example when you want to deposit them in a Vector, as in the code:
Vector vec = new Vector();
vec.addElement(12);
If you write code such as that shown above then it will give rise to syntax errors of the form:
Line nn: No method matching xxxx found in yyyy
where xxxx is the name of the method which is used and yyyy is the name of the class which expects an Object. The solution is to use the object wrapper classes found in java.lang to convert them to objects.

Confusing scalars and their corresponding object types

When you have scalars such as int it is easy to write code which assumes that they can be treated as if they were objects. For example, the code:
int y = 22;
Integer x = y; 
will give rise to an error message of the form:
Line nn: Incompatible type for declaration. Can't convert xxxx to yyyy
where xxxx and yyyy are the classes involved.

Mistyping the header for the main method

When you want to execute a Java application you need to declare a method which starts with:
public static void main (String []args){
If you mistype any part of this line or miss out a keyword, then a run-time error will be generated. For example, if you miss out the keyword static then an error message of the form:
Exception in thread main.....
will be generated at run time.

Note:- Captured from http://www.open.ac.uk/

Tuesday, September 24, 2013

New Features of Java 7.0

Java 7.0 Features 

switch on String

Before JDK 7, only integral types can be used as selector for switch-case statement. In JDK 7, you can use a String object as the selector. For example,
String day = "SAT";
switch (day) {
   case "MON": System.out.println("Monday"); break;
   case "TUE": System.out.println("Tuesday"); break;
   case "WED": System.out.println("Wednesday"); break;
   case "THU": System.out.println("Thursday"); break;
   case "FRI": System.out.println("Friday"); break;
   case "SAT": System.out.println("Saturday"); break;
   case "SUN": System.out.println("Sunday"); break;
   default: System.out.println("Invalid");
}
String.equals() method is used in comparison, which is case-sensitive. Java compiler can generate more efficient code than using nested if-then-else statement.
This feature is handy in handling options specified in command-line arguments, which are Strings. For example (slightly neater code than using nested if-then-else statement),
// This program accepts three command-line options
//   -c : create
//   -v : verbose
//   -d : debug
// More than one options can be specified in any order.
public class SwitchOnString {
   public static void main(String[] args) {
      boolean create = false;
      boolean verbose = false;
      boolean debug = false;
 
      for (String arg: args) {
         switch (arg) {
            case "-c": create = true; break;
            case "-v": verbose = true; break;
            case "-d": debug = true; break;
            default:
               System.out.println("invalid option");
               System.exit(1);
         }
      }
 
      System.out.println("create: " + create);
      System.out.println("verbose: " + verbose);
      System.out.println("debug: " + debug);
   }
}

Binary Literals with prefix "0b"

In JDK 7, you can express literal values in binary with prefix '0b' (or '0B') for integral types (byteshortint and long), similar to C/C++ language. Before JDK 7, you can only use octal values (with prefix '0') or hexadecimal values (with prefix '0x' or '0X').
You are also permitted to use underscore (_) to break the digits to improve the readability but you must start and end with a digit, e.g.,
int number1 = 0b01010000101000101101000010100010;
int number2 = 0b0101_0000_1010_0010_1101_0000_1010_0010;
int number3 = 2_123_456;  // break the digits with underscore
For example,
public class BinaryLiteralTest {
   public static void main(String[] args) {
      // Some 32-bit 'int' literal values
      int anInt1 = 0b0101_0000_1010_0010_1101_0000_1010_0010;
      int anInt2 = 0b0011_1000;
 
      // An 8-bit 'byte' literal value. By default, literal values are 'int'.
      // Need to cast to 'byte'
      byte aByte = (byte)0b0110_1101;
 
      // A 16-bit 'short' literal value
      short aShort = (short)0b0111_0101_0000_0101;
 
      // A 64-bit 'long' literal value. Long literals requires suffix "L".
      long aLong = 0b1000_0101_0001_0110_1000_0101_0000_1010_0010_1101_0100_0101_1010_0001_0100_0101L;
 
      // Formatted output: "%d" for integer in decimal, "%x" in hexadecimal, "%o" in octal.
      // Take note that "%b" prints true or false (for null), NOT binary.
      System.out.printf("%d(%x)(%o)(%b)\n", anInt1, anInt1, anInt1, anInt1);
      System.out.printf("%d(%x)(%o)(%b)\n", aByte, aByte, aByte, aByte);
   }
}
1352847522(50a2d0a2)(12050550242)(true)
109(6d)(155)(true)

Underscore for Numeric Literals

In JDK 7, you could insert underscore(s) '_' in between the digits in an numeric literals (integral and floating-point literals) to improve readability. For example,
int anInt = 0b10101000_01010001_01101000_01010001;
double aDouble = 3.1415_9265;
float  aFloat = 3.14_15_92_65f;

Catching Multiple Exception Types

In JDK 7, a single catch block can handle more than one exception types.
For example, before JDK 7, you need two catch blocks to catch two exception types although both perform identical task:
try {
   ......
} catch(ClassNotFoundException ex) {
   ex.printStackTrace();
} catch(SQLException ex) {
   ex.printStackTrace();
}
In JDK 7, you could use one single catch block, with exception types separated by '|'.
try {
   ......
} catch(ClassNotFoundException|SQLException ex) {
   ex.printStackTrace();
}
[TODO] A complete example on file IO.

The try-with-resources Statement

For example, before JDK 7, we need to use a finally block, to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The code is messy!
import java.io.*;
// Copy from one file to another file character by character.
// Pre-JDK 7 requires you to close the resources using a finally block.
public class FileCopyPreJDK7 {
   public static void main(String[] args) {
      BufferedReader in = null;
      BufferedWriter out = null;
      try {
         in  = new BufferedReader(new FileReader("in.txt"));
         out = new BufferedWriter(new FileWriter("out.txt"));
         int charRead;
         while ((charRead = in.read()) != -1) {
            System.out.printf("%c ", (char)charRead);
            out.write(charRead);
         }
      } catch (IOException ex) {
         ex.printStackTrace();
      } finally {            // always close the streams
         try {
            if (in != null) in.close();
            if (out != null) out.close();
         } catch (IOException ex) {
            ex.printStackTrace();
         }
      }
 
      try {
         in.read();   // Trigger IOException: Stream closed
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}
JDK 7 introduces a try-with-resources statement, which ensures that each of the resources in try(resourses) is closed at the end of the statement. This results in cleaner codes.
import java.io.*;
// Copy from one file to another file character by character.
// JDK 7 has a try-with-resources statement, which ensures that
// each resource opened in try() is closed at the end of the statement.
public class FileCopyJDK7 {
   public static void main(String[] args) {
      try (BufferedReader in  = new BufferedReader(new FileReader("in.txt"));
           BufferedWriter out = new BufferedWriter(new FileWriter("out.txt"))) {
         int charRead;
         while ((charRead = in.read()) != -1) {
            System.out.printf("%c ", (char)charRead);
            out.write(charRead);
         }
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

Type Inference for Generic Instance Creation

import java.util.*;
public class JDK7GenericTest {
   public static void main(String[] args) {
      // Pre-JDK 7
      List lst1 = new ArrayList();
      // JDK 7 supports limited type inference for generic instance creation
      List lst2 = new ArrayList<>();
 
      lst1.add("Mon");
      lst1.add("Tue");
      lst2.add("Wed");
      lst2.add("Thu");
 
      for (String item: lst1) {
         System.out.println(item);
      }
 
      for (String item: lst2) {
         System.out.println(item);
      }
   }
}

Note:- I read this in http://www.ntu.edu.sg and posted the content for (y)our reference.


Monday, September 23, 2013

Quick Javascript Refreshner

What is JavaScript?
A1: JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself. But the language can be--and is--used with other kinds of objects in other environments. For example, Adobe Acrobat Forms uses JavaScript as its underlying scripting language to glue together objects that are unique to the forms generated by Adobe Acrobat. Therefore, it is important to distinguish JavaScript, the language, from the objects it can communicate with in any particular environment. When used for Web documents, the scripts go directly inside the HTML documents and are downloaded to the browser with the rest of the HTML tags and content. 

A2:JavaScript is a platform-independent,event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems.


How is JavaScript different from Java? 
JavaScript was developed by Brendan Eich of Netscape; Java was developed at Sun Microsystems. While the two languages share some common syntax, they were developed independently of each other and for different audiences. Java is a full-fledged programming language tailored for network computing; it includes hundreds of its own objects, including objects for creating user interfaces that appear in Java applets (in Web browsers) or standalone Java applications. In contrast, JavaScript relies on whatever environment it's operating in for the user interface, such as a Web document's form elements. 
JavaScript was initially called LiveScript at Netscape while it was under development. A licensing deal between Netscape and Sun at the last minute let Netscape plug the "Java" name into the name of its scripting language. Programmers use entirely different tools for Java and JavaScript. It is also not uncommon for a programmer of one language to be ignorant of the other. The two languages don't rely on each other and are intended for different purposes. In some ways, the "Java" name on JavaScript has confused the world's understanding of the differences between the two. On the other hand, JavaScript is much easier to learn than Java and can offer a gentle introduction for newcomers who want to graduate to Java and the kinds of applications you can develop with it.


What’s relationship between JavaScript and ECMAScript? 
ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3. 


How do you submit a form using Javascript? 
Use document.forms[0].submit();
(0 refers to the index of the form – if you have more than one form in a page, then the first one has the index 0, second has index 1 and so on).


How do we get JavaScript onto a web page? 
You can use several different methods of placing javascript in you pages. 
You can directly add a script element inside the body of page. 
1. For example, to add the "last updated line" to your pages, In your page text, add the following: 
blah, blah, blah, blah, blah.

yada, yada, yada.

(Note: the first comment, "<-- --="" browsers="" content="" don="" from="" hides="" javascript.="" of="" script="" t="" that="" the="" understand="">" finishes the comment. The "//" tells javascript that this is a comment so javascript doesn't try to interpret the "-->". If your audience has much older browsers, you should put this comments inside your javascript. If most of your audience has newer browsers, the comments can be omitted. For brevity, in most examples here the comments are not shown. ) 
The above code will look like this on Javascript enabled browsers, 
2. Javascript can be placed inside the element 
Functions and global variables typically reside inside the element. 

Default Test Page



Javascript can be referenced from a separate file 
Javascript may also a placed in a separate file on the server and referenced from an HTML page. (Don't use the shorthand ending "
How to read and write a file using javascript? 
I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be done by coding a Java applet that reads files for the script.


How to detect the operating system on the client machine? 
In order to detect the operating system on the client machine, the navigator.appVersion 
string (property) should be used.


How can JavaScript make a Web site easier to use? That is, are there certain JavaScript techniques that make it easier for people to use a Web site? 
JavaScript's greatest potential gift to a Web site is that scripts can make the page more immediately interactive, that is, interactive without having to submit every little thing to the server for a server program to re-render the page and send it back to the client. For example, consider a top-level navigation panel that has, say, six primary image map links into subsections of the Web site. With only a little bit of scripting, each map area can be instructed to pop up a more detailed list of links to the contents within a subsection whenever the user rolls the cursor atop a map area. With the help of that popup list of links, the user with a scriptable browser can bypass one intermediate menu page. The user without a scriptable browser (or who has disabled JavaScript) will have to drill down through a more traditional and time-consuming path to the desired content.


How can JavaScript be used to improve the "look and feel" of a Web site? By the same token, how can JavaScript be used to improve the user interface?
On their own, Web pages tend to be lifeless and flat unless you add animated images or more bandwidth-intensive content such as Java applets or other content requiring plug-ins to operate (ShockWave and Flash, for example). 
Embedding JavaScript into an HTML page can bring the page to life in any number of ways. Perhaps the most visible features built into pages recently with the help of JavaScript are the so-called image rollovers: roll the cursor atop a graphic image and its appearance changes to a highlighted version as a feedback mechanism to let you know precisely what you're about to click on. But there are less visible yet more powerful enhancements to pages that JavaScript offers. 
Interactive forms validation is an extremely useful application of JavaScript. While a user is entering data into form fields, scripts can examine the validity of the data--did the user type any letters into a phone number field?, for instance. Without scripting, the user has to submit the form and let a server program (CGI) check the field entry and then report back to the user. This is usually done in a batch mode (the entire form at once), and the extra transactions take a lot of time and server processing power. Interactive validation scripts can check each form field immediately after the user has entered the data, while the information is fresh in the mind. 
Another helpful example is embedding small data collections into a document that scripts can look up without having to do all the server programming for database access. For instance, a small company could put its entire employee directory on a page that has its own search facility built into the script. You can cram a lot of text data into scripts no larger than an average image file, so it's not like the user has to wait forever for the data to be downloaded. 
Other examples abound, such as interactive tree-structure tables of contents. More modern scriptable browsers can be scripted to pre-cache images during the page's initial download to make them appear lickety-split when needed for image swapping. I've even written some multi-screen interactive applications that run entirely on the client, and never talk to the server once everything is downloaded.


What are JavaScript types? 
Number, String, Boolean, Function, Object, Null, Undefined.


How do you convert numbers between different bases in JavaScript? 
Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);


How to create arrays in JavaScript? 
We can declare an array like this 
var scripts = new Array(); 
We can add elements to this array like this

scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";

Now our array scrips has 4 elements inside it and we can print or access them by using their index number. Note that index number starts from 0. To get the third element of the array we have to use the index number 2 . Here is the way to get the third element of an array. 
document.write(scripts[2]); 
We also can create an array like this 
var no_array = new Array(21, 22, 23, 24, 25);


How do you target a specific frame from a hyperlink? 
Include the name of the frame in the target attribute of the hyperlink. >My Page


What is a fixed-width table and its advantages?
Fixed width tables are rendered by the browser based on the widths of the columns in the first row, resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table. 
If the table is not specified to be of fixed width, the browser has to wait till all data is downloaded and then infer the best width for each of the columns. This process can be very slow for large tables.
Example of using Regular Expressions for syntax checking in JavaScript 


...
var re = new RegExp("^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$");
var text = myWidget.value;
var OK = re.test(text);
if( ! OK ) {
alert("The extra parameters need some work.\r\n Should be something like: \"&a=1&c=4\"");
}

Where are cookies actually stored on the hard disk? 
This depends on the user's browser and OS.
In the case of Netscape with Windows OS,all the cookies are stored in a single file called

cookies.txt 
c:\Program Files\Netscape\Users\username\cookies.txt 
In the case of IE,each cookie is stored in a separate file namely username@website.txt. 
c:\Windows\Cookies\username@Website.txt
 

How to add Buttons in JavaScript?
The most basic and ancient use of buttons are the "submit" and "clear", which appear slightly before the Pleistocene period. Notice when the "GO!" button is pressed it submits itself to itself and appends the name in the URL. 

Your Name:







Another useful approach is to set the "type" to "button" and use the "onclick" event. 



<fieldset style="margin: 1em; text-align: center;">
Select a Hero






What can javascript programs do? 
Generation of HTML pages on-the-fly without accessing the Web server. The user can be given control over the browser like User input validation Simple computations can be performed on the client's machine The user's browser, OS, screen size, etc. can be detected Date and Time Handling


How to set a HTML document's background color? 
document.bgcolor property can be set to any appropriate color.


How can JavaScript be used to personalize or tailor a Web site to fit individual users? 
JavaScript allows a Web page to perform "if-then" kinds of decisions based on browser version, operating system, user input, and, in more recent browsers, details about the screen size in which the browser is running. While a server CGI program can make some of those same kinds of decisions, not everyone has access to or the expertise to create CGI programs. For example, an experienced CGI programmer can examine information about the browser whenever a request for a page is made; thus a server so equipped might serve up one page for Navigator users and a different page for Internet Explorer users. Beyond browser and operating system version, a CGI program can't know more about the environment. But a JavaScript-enhanced page can instruct the browser to render only certain content based on the browser, operating system, and even the screen size. 
Scripting can even go further if the page author desires. For example, the author may include a preference screen that lets the user determine the desired background and text color combination. A script can save this information on the client in a well-regulated local file called a cookie. The next time the user comes to the site, scripts in its pages look to the cookie info and render the page in the color combination selected previously. The server is none the wiser, nor does it have to store any visitor-specific information.


Are you concerned that older browsers don't support JavaScript and thus exclude a set of Web users? individual users? 
Fragmentation of the installed base of browsers will only get worse. By definition, it can never improve unless absolutely everyone on the planet threw away their old browsers and upgraded to the latest gee-whiz versions. But even then, there are plenty of discrepancies between the scriptability of the latest Netscape Navigator and Microsoft Internet Explorer. 
The situation makes scripting a challenge, especially for newcomers who may not be aware of the limitations of earlier browsers. A lot of effort in my books and ancillary material goes toward helping scripters know what features work in which browsers and how to either workaround limitations in earlier browsers or raise the compatibility common denominator. 
Designing scripts for a Web site requires making some hard decisions about if, when, and how to implement the advantages scripting offers a page to your audience. For public Web sites, I recommend using scripting in an additive way: let sufficient content stand on its own, but let scriptable browser users receive an enhanced experience, preferably with the same HTML document.


What does isNaN function do? 
Return true if the argument is not a number.


What is negative infinity? 
It’s a number in JavaScript, derived by dividing negative number by zero.


In a pop-up browser window, how do you refer to the main browser window that opened it? 
Use window.opener to refer to the main window from pop-ups.


What is the data type of variables of in JavaScript? 
All variables are of object type in JavaScript.
 

Methods GET and POST in HTML forms - what's the difference?
GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET method is limited to about 2kb.
POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair.


How to write a script for "Select" lists using javascript 
1. To remove an item from a list set it to null 
mySelectObject.options[3] = null; 
2. To truncate a list set its length to the maximum size you desire 
mySelectObject.length = 2; 
3. To delete all options in a select object set the length to 0. 
mySelectObject.leng


Text From Your Clipboard? 
It is true, text you last copied for pasting (copy & paste) can be stolen when you visit web sites using a combination of JavaScript and ASP (or PHP, or CGI) to write your possible sensitive data to a database on another server.


What does the "Access is Denied" IE error mean? 
The "Access Denied" error in any browser is due to the following reason.
A javascript in one window or frame is tries to access another window or frame whose document's domain is different from the document containing the script.


Is a javascript script faster than an ASP script? 
Yes.Since javascript is a client-side script it does require the web server's help for its 
computation,so it is always faster than any server-side script like ASP,PHP,etc..


Are Java and JavaScript the Same? 
No.java and javascript are two different languages.
Java is a powerful object - oriented programming language like C++,C whereas Javascript is a client-side scripting language with some limitations.


How to embed javascript in a web page? 
javascript code can be embedded in a web page between tags


What and where are the best JavaScript resources on the Web? 
The Web has several FAQ areas on JavaScript. The best place to start is something called the meta-FAQ [14-Jan-2001 Editor's Note: I can't point to it anymore, it is broken!], which provides a high-level overview of the JavaScript help available on the Net. As for fact-filled FAQs, I recommend one maintained by Martin Webb and a mini-FAQ that I maintain. 
For interactive help with specific problems, nothing beats the primary JavaScript Usenet newsgroup, comp.lang.javascript. Depending on my work backlog, I answer questions posted there from time to time. Netscape and Microsoft also have vendor-specific developer discussion groups as well as detailed documentation for the scripting and object model implementations.


What are the problems associated with using JavaScript, and are there JavaScript techniques that you discourage? 
Browser version incompatibility is the biggest problem. It requires knowing how each scriptable browser version implements its object model. You see, the incompatibility rarely has to do with the core JavaScript language (although there have been improvements to the language over time); the bulk of incompatibility issues have to do with the object models that each browser version implements. For example, scripters who started out with Navigator 3 implemented the image rollover because it looked cool. But they were dismayed to find out that the image object wasn't scriptable in Internet Explorer 3 or Navigator 2. While there are easy workarounds to make this feature work on newer browsers without disturbing older ones, it was a painful learning experience for many. 
The second biggest can of worms is scripting connections between multiple windows. A lot of scripters like to have little windows pop up with navigation bars or some such gizmos. But the object models, especially in the older browser versions, don't make it easy to work with these windows the minute you put a user in front of them--users who can manually close windows or change their stacking order. More recently, a glitch in some uninstall routines for Windows 95 applications can disturb vital parts of the system Registry that Internet Explorer 4 requires for managing multiple windows. A scripter can't work around this problem, because it's not possible to detect the problem in a user's machine. I tend to avoid multiple windows that interact with each other. I think a lot of inexperienced Web surfers can also get confused by them.


What Boolean operators does JavaScript support? 
&&, || and !


What does "1"+2+4 evaluate to? 
Since 1 is a string, everything is a string, so the result is 124.
 

What is the difference between a web-garden and a web-farm?
Web-garden - An IIS6.0 feature where you can configure an application pool as a web-garden and also specify the number of worker processes for that pool. It can help improve performance in some cases. 
Web-farm - a general term referring to a cluster of physically separate machines, each running a web-server for scalability and performance (contrast this with web-garden which refers to multiple processes on one single physical machine).


How to get the contents of an input box using Javascript? 
Use the "value" property. 
var myValue = window.document.getElementById("MyTextBox").value;


How to determine the state of a checkbox using Javascript? 
var checkedP = window.document.getElementById("myCheckBox").checked;


How to set the focus in an element using Javascript? 


How to access an external javascript file that is stored externally and not embedded? 
This can be achieved by using the following tag between head tags or between body tags.
How to access an external javascript file that is stored externally and not embedded? where abc.js is the external javscript file to be accessed.


What is the difference between an alert box and a confirmation box? 
An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel.


What is a prompt box? 
A prompt box allows the user to enter input by providing a text box.


Can javascript code be broken in different lines? 
Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement.
that is ,
document.write("Hello \ world");
is possible but not document.write \
("hello world");


Taking a developer’s perspective, do you think that that JavaScript is easy to learn and use? 
One of the reasons JavaScript has the word "script" in it is that as a programming language, the vocabulary of the core language is compact compared to full-fledged programming languages. If you already program in Java or C, you actually have to unlearn some concepts that had been beaten into you. For example, JavaScript is a loosely typed language, which means that a variable doesn't care if it's holding a string, a number, or a reference to an object; the same variable can even change what type of data it holds while a script runs. 
The other part of JavaScript implementation in browsers that makes it easier to learn is that most of the objects you script are pre-defined for the author, and they largely represent physical things you can see on a page: a text box, an image, and so on. It's easier to say, "OK, these are the things I'm working with and I'll use scripting to make them do such and such," instead of having to dream up the user interface, conceive of and code objects, and handle the interaction between objects and users. With scripting, you tend to write a _lot_ less code.


What Web sites do you feel use JavaScript most effectively (i.e., best-in-class examples)? The worst? 
The best sites are the ones that use JavaScript so transparently, that I'm not aware that there is any scripting on the page. The worst sites are those that try to impress me with how much scripting is on the page.


How about 2+5+"8"? 
Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.


What is the difference between SessionState and ViewState? 
ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application.


What does the EnableViewStateMac setting in an aspx page do? 
Setting EnableViewStateMac=true is a security measure that allows ASP.NET to ensure that the viewstate for a page has not been tampered with. If on Postback, the ASP.NET framework detects that there has been a change in the value of viewstate that was sent to the browser, it raises an error - Validation of viewstate MAC failed. 
Use <%@ Page EnableViewStateMac="true"%> to set it to true (the default value, if this attribute is not specified is also true) in an aspx page.


How to Accessing Elements using javascript?
To do something interesting with HTML elements, we must first be able to uniquely identify which element we want. In the example 







We can use the "getElementById" method (which is generally preferred)
document.getElementById("useless").style.color = "red";
or we can use the older hierarchical navigation method,
document.forms[0].mybutton.style.color = "blue";
Notice that this uses the "name" attribute of the element to locate it.
# Example of Accessing Elements in a DOM.














onclick="showStatus()" />

What looping structures are there in JavaScript? 
for, while, do-while loops, but no foreach.


To put a "close window" link on a page ? 
Close


How to hide javascript code from old browsers that dont run it? 
Use the below specified style of comments

...

brand











What does undefined value mean in javascript? 
Undefined value means the variable used in the code doesn't exist or is not assigned any value or the property doesn't exist.


What is the difference between undefined value and null value? 
(i)Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has keyword called null
(ii)typeof undefined variable or property returns undefined whereas typeof null value returns object


What is variable typing in javascript? 
It is perfectly legal to assign a number to a variable and then assign a string to the same variable as follows 
example 
i = 10;
i = "string";
This is called variable typing


Does javascript have the concept level scope? 
No. JavaScript does not have block level scope, all the variables declared inside a function possess the same level of scope unlike c,c++,java.


What are undefined and undeclared variables? 
Undeclared variables are those that are not declared in the program (do not exist at all),trying to read their values gives runtime error.But if undeclared variables are assigned then implicit declaration is done . 
Undefined variables are those that are not assigned any value but are declared in the program.Trying to read such variables gives special value called undefined value.


What is === operator ? 
==== is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.


How to find the selected radio button immediately using the 'this' variable?


onchange="favAnimal(this)">Kangaroo

 
onchange="favAnimal(this)">Opossum


onchange="favAnimal(this)">Tasmanian Tiger


How to find radio button selection when a form is submitted? 


Kangaroo

Opossum


Tasmanian Tiger





How to disable an HTML object ?
document.getElementById("myObject").disabled = true;


To write messages to the screen without using "document.write()" ? 
Changing the contents of an element is a much better solution. When the method showStatus is invoked it will change the content of the span. 
...
function showStatus(message) {
var element = document.getElementById("mystatus");
element.textContent = message; //for Firefox
element.innerHTML = message; //for IE (why can't we all just get along?)
return true;
}
...
Test.
...


How to Add new elements dynamically ?


t1






firstP




How to have an element invoke a javascript on selection, instead of going to a new URL: ?

hit me


How to have the status line update when the mouse goes over a link (The support of the status line is sporadic)? 
 
onmouseover="window.status='Hi There!';return true" 
onmouseout="window.status='';return true">Look at the Status bar

Look at the Status bar as your cursor goes over the link.


How to create a popup warning box
alert('Warning: Please enter an integer between 0 and 100.');

How to create a confirmation box? 
confirm("Do you really want to launch the missile?"); 


How to create an input box? 
prompt("What is your temperature?");


How to setting a cookie with the contents of a textbox ? 
Values stored in cookies may not have semicolons, commas, or spaces. You should use the handy "escape()" function to encode the values, and "unescape()" to retrieve them.

//Sets cookie of current value for myTextBox
function TextBoxOnchange() {
var myBox = window.document.getElementById(myTextBox");
document.cookie = "myTextBox="+ escape(myBox.value) + getExpirationString();
}

//return a string like ";expires=Thu, 5 Jan 2006 16:07:52 UTC"
function getExpirationString() {
var exp = new Date();
var threemonths = exp.getTime()+(120*24*60*60*1000);
exp.setTime(threemonths);
return ";expires="+exp.toGMTString();
}

This is called from the event handler in the HTML.


onchange="javascript:TextBoxOnchange()" />


How to getting values from cookies to set widgets? 
function getCookieData(labelName) {
//from Danny Goodman
var labelLen = labelName.length;
// read cookie property only once for speed
var cookieData = document.cookie;
var cLen = cookieData.length;
var i = 0;
var cEnd;
while (i < cLen) {
var j = i + labelLen;
if (cookieData.substring(i,j) == labelName) {
cEnd = cookieData.indexOf(";",j);
if (cEnd == -1) {
cEnd = cookieData.length;
}
return unescape(cookieData.substring(j+1, cEnd));
}
i++;
}
return "";
}

//init() is called from the body tag onload function.
function init() {
setValueFromCookie("brand");
setValueFromCookie("market");
setValueFromCookie("measure");
}

function setValueFromCookie(widget) {
if( getCookieData(widget) != "") {
document.getElementById(widget).value = getCookieData(widget);
}
}

//if you name your cookies the widget ID, you can use the following helper function
function setCookie(widget) {
document.cookie = widget + "=" +
escape(document.getElementById(widget).value) + getExpirationString();

}


How to change style on an element? 
Between CSS and javascript is a weird symmetry. CSS style rules are layed on top of the DOM. The CSS property names like "font-weight" are transliterated into "myElement.style.fontWeight". The class of an element can be swapped out. For example: 
document.getElementById("myText").style.color = "green";
document.getElementById("myText").style.fontSize = "20";
-or-
document.getElementById("myText").className = "regular";


How to Handle Event Handlers?
You can add an event handler in the HTML definition of the element like this,



Or, interestingly enough you can just assign the event's name on the object directly with a reference to the method you want to assign.




You can also use an anonymous method like this:

document.getElementById("hitme3").onclick = function () { alert("howdy!"); }

You can also use the W3C addEvventListener() method, but it does not work in IE yet:




How to remove the event listener: ?


Key Events

"onkeydown", "onkeypress", "onkeyup" events are supported both in ie and standards-based browsers.




onkeyup="setStatus('keyup',event)" 
onkeydown="setStatus('keydown',event)" 
/>
status



How to make elements invisible ?
Change the "visibility" attribute of the style object associated with your element. Remember that a hidden element still takes up space, use "display" to make the space disappear as well.

if ( x == y) {
myElement.style.visibility = 'visible';
} else {
myElement.style.visibility = 'hidden';
}

How to set the cursor to wait ?
In theory, we should cache the current state of the cursor and then put it back to its original state. 
document.body.style.cursor = 'wait'; 
//do something interesting and time consuming
document.body.style.cursor = 'auto';


How to reload the current page ?
window.location.reload(true);


How to force a page to go to another page using JavaScript ? 


How to convert a string to a number using JavaScript?
You can use the parseInt() and parseFloat() methods. Notice that extra letters following a valid number are ignored, which is kinda wierd but convenient at times.
parseInt("100") ==> 100
parseFloat("98.6") ==> 98.6
parseFloat("98.6 is a common temperature.") ==> 98.6
parseInt("aa") ==> Nan //Not a Number
parseInt("aa",16) ==> 170 //you can supply a radix or base


How to convert numbers to strings using JavaScript? 
You can prepend the number with an empty string 
var mystring = ""+myinteger; 
or 
var mystring = myinteger.toString(); 
You can specify a base for the conversion, 
var myinteger = 14; 
var mystring = myinteger.toString(16);

mystring will be "e".


How to test for bad numbers using JavaScript? 
the global method, "isNaN()" can tell if a number has gone bad. 
var temperature = parseFloat(myTemperatureWidget.value);
if(!isNaN(temperature)) {
alert("Please enter a valid temperature.");
}

What's Math Constants and Functions using JavaScript? 
The Math object contains useful constants such as Math.PI, Math.E 
Math also has a zillion helpful functions. 
Math.abs(value); //absolute value 
Math.max(value1, value2); //find the largest 
Math.random() //generate a decimal number between 0 and 1 
Math.floor(Math.random()*101) //generate a decimal number between 0 and 100


What's the Date object using JavaScript? 
Time inside a date object is stored as milliseconds since Jan 1, 1970. 
new Date(06,01,02) // produces "Fri Feb 02 1906 00:00:00 GMT-0600 (Central Standard Time)" 
new Date(06,01,02).toLocaleString() // produces "Friday, February 02, 1906 00:00:00" 
new Date(06,01,02) - new Date(06,01,01) // produces "86400000"


What does the delete operator do? 
The delete operator is used to delete all the variables and objects used in the program ,but it does not delete variables declared with var keyword.


How tp create Arrays using JavaScript ?


This produces

first day is Sunday

A more compact way of creating an array is the literal notation: 

This produces
first day is Sunday


How to delete an entry using JavaScript? 
The "delete" operator removes an array element, but oddly does not change the size of the array.

This produces
Number of days:7
Number of days:7
 

How to use strings as array indexes using JavaScript?
Javascript does not have a true hashtable object, but through its wierdness, you can use the array as a hashtable.


This produces
days["Monday"]:Monday


How to use "join()" to create a string from an array using JavaScript? 
"join" concatenates the array elements with a specified seperator between them.


This produces
days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday


How to make a array as a stack using JavaScript? 
The pop() and push() functions turn a harmless array into a stack


This produces
sixfivefour


How to shift and unshift using JavaScript? 

This produces
zero one two
shift, unshift, push, and pop may be used on the same array. Queues are easily implemented using combinations.


How to create an object using JavaScript? 
Objects can be created in many ways. One way is to create the object and add the fields directly.


This produces
aliens:[object Object]

You can also use an abbreviated format for creating fields using a ":" to separate the name of the field from its value. This is equivalent to the above code using "this.".

This produces
aliens:[object Object]
 

How to associate functions with objects using JavaScript?
Let's now create a custom "toString()" method for our movie object. We can embed the function directly in the object like this.


This produces
title: Narni director: Andrew Adamson

Or we can use a previously defined function and assign it to a variable. Note that the name of the function is not followed by parenthesis, otherwise it would just execute the function and stuff the returned value into the variable.


This produces
title: Aliens director: Cameron

eval()? 
The eval() method is incredibly powerful allowing you to execute snippets of code during execution.

This produces
Population is 521,289


What does break and continue statements do? 
Continue statement continues the current loop (if label not specified) in a new iteration whereas break statement exits the current loop.


How to create a function using function constructor? 
The following example illustrates this
It creates a function called square with argument x and returns x multiplied by itself.
var square = new Function ("x","return x*x");


What's Prototypes for JavaScript? 
Objects have "prototypes" from which they may inherit fields and functions.

unescape(), escape() 
These are similar to the decodeURI() and encodeURI(), but escape() is used for only portions of a URI.



If you use escape() for the whole URI... well bad things happen.