Latest Entries »

I am developing websites for over past nine months and I have found some really good stuff that could help in decreasing the load time of a web page. Below are few things related to JavaScript and CSS that could help in speed up the load time of a web page.


Minimize the HTTP Request.

Most of the end-user time is spent on loading the front end. If somehow we could reduce this time user gets more time to look at the content. This happens mainly due to the loading of various components used in page such as images, stylesheets, scripts, flash, etc. Each component requires a HTTP request. Reducing the number of this request can help in faster page loading.
Combined files are a way to reduce the number of HTTP requests by combining all scripts into a single script, and similarly combining all CSS into a single stylesheet.
CSS Sprites are the preferred method for reducing the number of image requests. Combine your background images into a single image and use the CSS background-image and background-position properties to display the desired image segment.


Putting CSS Stylesheets at the Top

Putting stylesheet in the HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively. Loading progressively means that the browser displays whatever content it has as soon as possible. This helps a lot when the page is loaded heavily with lots for content. It also helps when the user internet connection is slow (Dial up). When the browser loads the page progressively the header, the navigation bar, the logo at the top, etc. all serve as visual feedback for the user who is waiting for the page. This improves the overall user experience.
The problem with putting stylesheets near the bottom of the document is that it prohibits progressive rendering in many browsers, including Internet Explorer. These browsers block rendering to avoid having to redraw elements of the page if their styles change. The user is stuck viewing a blank white page.


Put Scripts at Bottom

As described above how stylesheets near the bottom of the page prohibit progressive rendering, and how moving them to the document HEAD eliminates the problem. Scripts (external JavaScript files) pose a similar problem, but the solution is just the opposite: it’s better to move scripts from the top to as low in the page as possible. One reason is to enable progressive rendering, but another is to achieve greater download parallelization.
With scripts, progressive rendering is blocked for all content below the script. Moving scripts as low in the page as possible means there’s more content above the script that is rendered sooner.
The second problem caused by scripts is blocking parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won’t start any other downloads, even on different hostnames.


Make JavaScript and CSS External

Using external files in the real world generally produces faster pages because the JavaScript and CSS files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the size of the HTML document is reduced without increasing the number of HTTP requests.


Minify JavaScript and CSS.

Minification means removing unnecessary characters from code to reduce its size thereby improving load times. When code is minified all comments are removed, as well as unneeded white space characters (space, newline, and tab). In the case of JavaScript, this improves response time performance because the size of the downloaded file is reduced.

What Java 5 has got for us?

The last major release of the Java platform was 1.2. It was so major, in fact, that the language came to be known as Java 2. Later Java releases added a number of new features and fixes, but nothing to get overly excited about. Java 5 (JDK 1.5), however, is another biggie!

Autoboxing


Autoboxing is a language feature that makes the programmer’s life much easier when it comes to working with the primitive wrapper types. Consider this code fragment:

int num = 23;
Integer numObject = new Integer(num);

Primitive wrapper objects, such as the Integer class used here, were Java’s way of allowing you to treat primitive types as though they were objects. Consequently, you were expected to ‘wrap’ your primitive type with the corresponding primitive wrapper object, as shown above.

Forget all that! Java 5 allows you to do the following:

int num = 23;
Integer numObject = num;

This seems a little odd at first: we’ve created an object of type Integer and assigned it a primitive type! How can that be? A primitive is a primitive and an object is an object, and never the twain shall meet, right? Regardless, the extra step of wrapping the primitive is no longer required. It has been ‘automatically boxed up’ on your behalf.

Unboxing uses the same process in reverse. Study the following snippet for a moment:

Boolean canMove = new Boolean(true);
if(canMove){
System.out.println(“This code is legal in Java 5!”);
}

So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference types and primitives, for example, when you have to put numerical values into a collection. It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.

Var-args


In Java, method specifications are pretty much set in stone. For example, a method that declares two parameters of a particular type must be called with those parameters. If you supply too many, too few, or incorrectly typed parameters, you will get a compile time error. Of course, we use method overloading to deal with the cases in which we need to declare a varying number or type of parameters.

However, every now and then it makes sense, or is more convenient, to have the one method handle any number of arguments that are thrown its way, just as you’re allowed to do in languages like JavaScript and ColdFusion. The way many programmers previously simulated such behavior in Java was to create an array of parameters, then pass that array along as an argument to the desired method.

In Java 5, this rather messy approach is no longer necessary. Consider this method specification:

public void myMethod(Object … args)

Notice the three periods next to the parameter type? This is how we tell the method that it is allowed to accept a varying number of arguments. The type must be Object, and it must be the last or only argument in the method specification. With that in mind, the following method calls are all perfectly legal:

myMethod(23, 34, 78);
myMethod(“Hello”, “Goodbye”);
myMethod(123);

This makes sense, except for one thing. I said that the arguments must be of type Object, yet I clearly pass along primitives in two of these calls! That’s autoboxing in action — the arguments are passed along as Object types; the compiler takes care of the primitive wrapping on our behalf.

As you would expect, inside the method body, the parameters are handled as an array of type Object. The following code sample shows how much code we may have needed to achieve the same thing prior to Java 5.

int num1 = 23;
int num2 = 28;
int num3 = 98;

Integer objNum1 = new Integer(num1);
Integer objNum2 = new Integer(num2);
Integer objNum3 = new Integer(num3);

Integer[] params = {objNum1, objNum1, objNum3}
myMethod(params);

Here, we do all the primitive wrapping ourselves. Then, we create the array-based parameter. Finally, we do the method call. Now that’s a lot more work!

The printf Method

Here’s a handy addition to the java.io.PrintStream and java.io.PrintWriter classes — the C like printf() method. The first argument to printf() is a String, known as a format string. The remaining arguments are called ‘format specifiers’. Thanks to the var-args feature, you can have as many of these format specifiers as you like. This is easier to explain by way of a simple example:

Calendar c = Calendar.getInstance();
System.out.printf(“Hi %2s, the current month is:  %1tB”, cal, “Andy”);

Let’s break it down, as there are quite a few things going on here. Let us consider the first format specifier in the format string — that’s the bit that reads, %2s.

The % symbol signifies that we’re using a format specifier. The digit that follows is the argument index. In this case it is 2, and therefore refers to the second argument, which is the string “Andy”.

The next format specifier is %1tB. From the above explanation, you’ll know that it’s another format specifier, this time referring to the first argument (the %1 portion tells us that much). On this occasion, we use a t to indicate a date conversion. The B following the t indicates that the month should be output. The resulting string would be, “Hi Andy, the current month is October”.

As you can probably see, without the var-args feature, printf() would hardly be possible. This is a rare example of var-args being used in the proper manner.

Static Imports


The new ‘import static’ statement is another great addition to the language. As Java programmers, you may well have written code like the following on more than one occasion:

PrintStream o = System.out;
o.print(“stuff”);
o.print(“more stuff”);

The reference variable o is no more than a handy shortcut to System.out. In Java 5, you can import a class’s static members and refer to them without the usual class name prefix. Thus, you can now do something like this:

import static java.lang.System.out;
// other code here.
out.print(“stuff”);
out.print(“more stuff”);

Once the static member is imported, you can use it in your code without the System class prefix. Here’s an even better example from the GUI world of Swing.

// without static import.
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

// with static import.
import static javax.swing.WindowConstants.*;
// other code
setDefaultCloseOperation(EXIT_ON_CLOSE);

In the second example, the addition of the static import greatly enhances the readability of the code and cuts down on the amount of code required. I used the * to import all of WindowConstants static members in this case.

The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.

So when should you use static import? Very sparingly! Only use it when you’d otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.

Enumerated Types


Let’s kick this one off with a quick look at the way we used to simulate enumerated types:

class FizzyDrink {
static final int PEPSI = 1;
static final int COKE = 2;
static final int SCHWEPPES = 3
}

This pattern has many problems, such as:

  • Not typesafe – Since it is just an int you can pass in any other int value where combonation is required, or add two FizzyDrink together (which makes no sense).
  • No namespace – You must prefix constants of an int enum with a string  to avoid collisions with other int enum types.
  • Brittleness – Because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
  • Printed values are uninformative – Because they are just ints, if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is.

Here’s the new way:

enum FizzyDrink{ pepsi, coke, schweppes }

Notice the use of the enum keyword in place of the class keyword? An enum is really just a special kind of class. Here’s an example of this enum in use:

FizzyDrink todaysFizzyDrink = FizzyDrink.pepsi;

Now, we really do have a FizzyDrink type. In fact, if we printed the value of todaysFizzyDrink, we’d get the string pepsi and not some meaningless integer value. Here’s the really cool part: no dependant class recompilation is required, and Java will even warn you when you change an enumerated type but still have code elsewhere that uses the old enumerated values!

Note : enum constants cannot be used in switch statements.

So when should you use enums? Any time you need a fixed set of constants. That includes natural enumerated types (like the planets, days of the week, and suits in a card deck) as well as other sets where you know all possible values at compile time, such as choices on a menu, rounding modes, command line flags, and the like. It is not necessary that the set of constants in an enum type stay fixed for all time. The feature was specifically designed to allow for binary compatible evolution of enum types.

Generics


Type genericity is by far the most radical enhancement to the core Java language. In a nutshell, generics allows java programmers to pass types as arguments to classes just as values are passed to methods.

Generics are largely intended for use with the collection framework, so I’ll keep this very brief discussion of them focused in that area. Take a look at the following before-and-after example of the way elements in a LinkedList are accessed:

String custName = (String) myList.getFirst();  // without generics
String custName = myList.getFirst();    // with generics

In the first example, we had to perform the usual cast, because the current collection classes work with Objects. It’s up to the programmer to figure out the type and do the appropriate conversion.

In the second example, there is no cast. So how did the getFirst() method know to return a String object? The simple answer is that when the LinkedList was instantiated, it was specifically told to work with Strings. Let’s have a look at how this was done:

LinkedList<String> myList = new LinkedList<String>();

You’ll see that the two sets of angle brackets contain the ‘type’ we pass to the class as we instantiate it. This list will now work only with Strings — it simply will not compile if any attempts are made to add objects of the wrong type. Let’s look at an example LinkedList implementation to get an idea of what’s going on:

public class LinkedList <Element>{
boolean add(Element o) {
// code omitted
}
Element getFirst(){
// code omitted
}
}

The key to all this is the <Element> declaration. This rather odd looking syntax really just serves the same purpose parentheses serve for method parameters, except, of course, that we’re passing types along, not values. By the way, the real LinkedList class uses <E> as the type parameter — there’s nothing special about <Element>, just as there’s nothing special about any method parameter names you choose.

At first, it’s easy to think that generics simply save us having to perform casts — this is indeed a nice feature, but it’s not the point. Before generics, it was possible for some errant code to add, say, an Integer to a collection that was supposed to hold Strings. Unfortunately, this would go unnoticed by the compiler and, instead, would surface many months or years later in the form of a near-impossible-to-find bug!

Collection classes now know exactly the types they’re meant to deal with, so error detection is moved to an earlier point in the development lifecycle: compile time.

Generics are implemented by type erasure: generic type information is present only at compile time, after which it is erased by the compiler. The main advantage of this approach is that it provides total interoperability between generic code and legacy code that uses non-parameterized types (which are technically known as raw types). The main disadvantages are that parameter type information is not available at run time, and that automatically generated casts may fail when interoperating with ill-behaved legacy code. There is, however, a way to achieve guaranteed run-time type safety for generic collections even when interoperating with ill-behaved legacy code.

The java.util.Collections class has been outfitted with wrapper classes that provide guaranteed run-time type safety. They are similar in structure to the synchronized and unmodifiable wrappers. These “checked collection wrappers” are very useful for debugging. Suppose you have a set of strings, s, into which some legacy code is mysteriously inserting an integer. Without the wrapper, you will not find out about the problem until you read the problem element from the set, and an automatically generated cast to String fails. At this point, it is too late to determine the source of the problem. If, however, you replace the declaration:

Set<String> s = new HashSet<String>();

with this declaration:

Set<String> s = Collections.checkedSet(new HashSet<String>(), String.class);

the collection will throw a ClassCastException at the point where the legacy code attempts to insert the integer. The resulting stack trace will allow you to diagnose and repair the problem.

You should use generics everywhere you can. The extra effort in generifying code is well worth the gains in clarity and type safety. It is straightforward to use a generic library, but it requires some expertise to write a generic library, or to generify an existing library. There is one caveat: You may not use generics (or any other Tiger features) if you intend to deploy the compiled code on a pre-5.0 virtual machine.

For-Each Loop


Iterating over a collection is uglier than it needs to be. Consider the following method, which takes a collection of timer tasks and cancels them:

void cancelAll(Collection<TimerTask> c) {

for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); )

i.next().cancel();

}

The iterator is just clutter. Furthermore, it is an opportunity for error. The iterator variable occurs three times in each loop: that is two chances to get it wrong. The for-each construct gets rid of the clutter and the opportunity for error. Here is how the example looks with the for-each construct:

void cancelAll(Collection<TimerTask> c) {

for (TimerTask t : c)

t.cancel();

}

When you see the colon (:) read it as “in.” The loop above reads as “for each TimerTask t in c.” As you can see, the for-each construct combines beautifully with generics. It preserves all of the type safety, while removing the remaining clutter. Because you don’t have to declare the iterator, you don’t have to provide a generic declaration for it. (The compiler does this for you behind your back, but you need not concern yourself with it.)

So when should you use the for-each loop? Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.

Source


http://articles.sitepoint.com/article/introducing-java-5

http://download.oracle.com/javase/1.5.0/docs/guide/language/index.html

Section 1: Declarations, Initialization and Scoping


 

  1. Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).
  2. Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.
  3. Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.
  4. Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.
  5. Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class.

Section 2: Flow Control


 

  1. Develop code that implements an if or switch statement; and identify legal argument types for these statements.
  2. Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.
  3. Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.
  4. Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.
  5. Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.
  6. Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.

 

Section 3: API Contents


 

  1. Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.
  2. Given a scenario involving navigating file systems, reading from files, writing to files, or interacting with the user, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader, BufferedWriter, File, FileReader, FileWriter, PrintWriter, and Console.
  3. Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.
  4. Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.

Section 4: Concurrency


 

  1. Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.
  2. Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.
  3. Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.

Section 5: OO Concepts


 

  1. Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.
  2. Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.
  3. Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.
  4. Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, or overloaded constructors.
  5. Develop code that implements “is-a” and/or “has-a” relationships.

Section 6: Collections / Generics


 

  1. Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.
  2. Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.
  3. Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions. Write code that uses the NavigableSet and NavigableMap interfaces.
  4. Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.
  5. Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the “natural ordering” of primitive wrapper classes and java.lang.String on sorting.

Section 7: Fundamentals


 

  1. Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.
  2. Given an example of a class and a command-line, determine the expected runtime behavior.
  3. Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.
  4. Given a code example, recognize the point at which an object becomes eligible for garbage collection, determine what is and is not guaranteed by the garbage collection system, and recognize the behaviors of the Object.finalize() method.
  5. Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.
  6. Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, –), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.

Hi all,

I am preparing for SCJP 310-065 exam.I am a fresher to the IT industry and want to build my career in JAVA Technologies so i thought it would be a very help full to kick-off  with SCJP. I am writing this blog so that i can gather all my study material here and get some useful tips from those who have cleared the exam.

Follow

Get every new post delivered to your Inbox.