Saturday, 6 April 2013

Rules associated with declaring classes, import statements, and package statements in a source file

  • There can be only one public class per source code file.
  • Comments can appear at the beginning or end of any line in the source code file; they are independent of any of the positioning rules discussed here.
  • If there is public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Dog { } must be in a source code file named Dog.java
  • If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present.
  • If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn't a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements, the class declaration must be the first line in the source code file.importand package statements apply to all classes within a source code file. In other words, there's no way to declare multiple classes in a file and have them in different packages, or use different imports.
  • A file can have more than one nonpublic class.
  • Files with no public classes can have a name that does not match any of the classes in the file.

JavaBeans Standards

JavaBean Property Naming Rules

  • If the property is not a boolean, the getter method's prefix must be get. For example, getSize()is a valid JavaBeans getter name for a property named "size." Keep in mind that you do not need to have a variable named size (although some IDEs expect it).
The name of the property is inferred from the getters and setters, not through any variables in your class. What you return from getSize() is up to you.
  • If the property is a boolean, the getter method's prefix is either get or is. For example, getStopped() or isStopped() are both valid JavaBeans names for a boolean property.
  • The setter method's prefix must be set. For example, setSize() is the valid JavaBean name for a property named size.
  • To complete the name of a getter or setter method, change the first letter of the property name to uppercase, and then append it to the appropriate prefix (
    get, is, or set).
  • Setter method signatures must be marked
    public, with a void return type and an argument that represents the property type.
  • Getter method signatures must be marked
    public, take no arguments, and have a return type that matches the argument type of the setter method for that property.
  • JavaBean Listener Naming Rules

    • Listener method names used to "register" a listener with an event source must use the prefix
      add, followed by the listener type. For example, addActionListener() is a valid name for a method that an event source will have to allow others to register for Action events.
  • Listener method names used to remove ("unregister") a listener must use the prefix
    remove, followed by the listener type (using the same rules as the registration add method).
  • The type of listener to be added or removed must be passed as the argument to the method.
  • Listener method names must end with the word "Listener".
  • Examples of valid JavaBean method signatures are
    public void setMyValue(int v)
    public int getMyValue()
    public boolean isMyStatus()
    public void addMyListener(MyListener m)
    public void removeMyListener(MyListener m)

    Examples of invalid JavaBean method signatures are
    void setCustomerName(String s) // must be public
    public void modifyMyValue(int v) // can't use 'modify'
    public void addXListener(MyListener m) // listener type mismatch


    Java Code Conventions


    Sun estimated that over the lifetime of a standard piece of code, 20 percent of the effort will go into the original creation and testing of the code, and 80 percent of the effort will go into the subsequent maintenance and enhancement of the code. Agreeing on, and coding to, a set of code standards helps to reduce the effort involved in testing, maintaining, and enhancing any piece of code. Sun had created a set of coding standards for Java, and published those standards in a document cleverly titled "Java Code Conventions," which you can find at
    http://www.oracle.com/technetwork/java/codeconv-138413.html. It's a great document, short and easy to read and we recommend it highly.  Here are the naming standardsthat Sun recommends, and that we use in the exam and in most of the book:

    Classes and interfaces

    The first letter should be capitalized, and if several words are linked together to form the name, the first letter of the inner words should be uppercase (a format that's sometimes called "camelCase"). For classes, the names should typically be nouns. For example:
    Dog
    Account
    PrintWriter

    For interfaces, the names should typically be adjectives like

    Runnable
    Serializable
    Methods

    The first letter should be lowercase, and then normal camelCase rules should be used. In addition, the names should typically be verb-noun pairs. For example:
    getBalance
    doCalculation
    setCustomerName
    Variables

    Like methods, the camelCase format should be used, starting with a lowercase letter. Sun recommends short, meaningful names, which sounds good to us. Some examples:
    buttonWidth
    accountBalance
    myString
    Constants

    Java constants are created by marking variables static and final. They should be named using uppercase letters with underscore characters as separators:
    MIN_HEIGHT

    Legal Identifiers

    Technically, legal identifiers must be composed of only Unicode characters, numbers, currency symbols, and connecting characters (like underscores). The exam doesn't dive into the details of which ranges of the Unicode character set are considered to qualify as letters and digits. So, for example, you won't need to know that Tibetan digits range from \u0420 to \u0f29.

    Here are the rules you do need to know:
    • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number!
    • After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
    • In practice, there is no limit to the number of characters an identifier can contain.
    • You can't use a Java keyword as an identifier.
    • Identifiers in Java are case-sensitive; foo and FOO are two different identifiers.
    Examples of legal and illegal identifiers follow, first some legal identifiers:
    int _a;
    int $c;
    int ______2_w;
    int _$;
    int this_is_a_very_detailed_name_for_an_identifier;
    The following are illegal (it's your job to recognize why):
    int :b;
    int -d;
    int e#;
    int .f;
    int 7g;
    Legal Identifi ers (Exam Objectives 1.3 and 1.4) 5

    Sunday, 24 March 2013

    Keywords in java



    Java - Keywords 


    abstract
    continue
    goto
    package
    synchronized
    assert
    default
    if
    private
    this
    boolean
    do
    implements
    protected
    throw
    break
    double
    import
    public
    throws
    byte
    else
    instanceof
    return
    transient
    case
    extends
    int
    short
    try
    catch
    final
    interface
    static
    void
    char
    finally
    long
    strictfp
    volatile
    class
    float
    native
    super
    while
    const
    for
    new
    switch

    Wednesday, 20 March 2013

    Objective 1.1.1: Declare Class,Interface...

    Interface

    Interface is a an abstract type that can be used only after implementation by the class that implements the interface. It is important to know that interface does not define any methods, it just tell the outside world that a class that implements this interface will have all the methods defined in the interface. Interface may contain only method signature as as I said before and constant declaration which means the variables declared are both static and final. The mehods defined in the interace are public and abstract in nature. There cannot be a method of type final. 

     Example

    interface Car{
    
        void changeGear(int newValue);
    
        void accelerate(int accelerateValue);
    
        void decelerate(int decelerateValue);
    }
    

    Class

    To implement this interface, the name of your class would change (to a particular brand of car , for example, such as MarutiCar), and you'd use the implements keyword in the class declaration.

    Example

    class MarutiCar implements Car{
        //class variables
        // remainder of this class 
        // implementation of the interface methods
    }
    

    Comprehensive Example 

    class MarutiCar implements Car{

        String ACModel;

        public void changeGear(int newValue){
             // change gear operation
        }

        public void accelerate(int accelerateValue){
           // accelerate operation
       }
        void decelerate(int decelerateValue)
           // decelerate operation
       }
       public static void main(String args[]) {
           // Object creation
           MarutiCar myCar = new MarutiCar();

          // Call a method
           myCar.ChangeGear(2);

        }

    }
    Unlike interface the class variables need not be final and static. Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

    Interface also helps in multiple inheritance which cannot be done with normal classes. A class can implement two interfaces but cannot inherit two classes in java.


    Sunday, 17 March 2013

    OOPs Basics

    Objects

    Objects are used to map our programming elements to the real world. For example, In real world we find different objects, like a car which has its own state(Property) and behaviour(Function). Similarly, in programming we try to map these state and behaviour to programming entities.

    Example

    Lets assume we have to calculate the area of a circle object. The circle will have its state radius. And it will have a behaviour area. If you map it to a car you will find it even better. Lets assume we have a car object that is going to be controlled automatically. It will have states like speed, mileage and so on. It will have behaviours like acceleration, deceleration, stop and so on.

    Classes

    To put it simple Class is a template for objects. We have same sort of objects and hence we can create a class from which multiple objects can be created. Again from the car example, we know that all cars have same set of components at least for same brand of a car. This is how classes came into existence for re using the same kind of object behaviour.

    Inheritance

    Lets assume that we have a basic car. Now we want to add AC to that car, So the new AC car is actually the same car but have AC in additional. In such case we will create a new class that inherits from the car class thereby reusing code.

    Interface

    Interfaces are use to expose the required information of the class without exposing the actual implementation of the class. It will have just the instance variables and public methods associated to the class.

    Packages

    Packages are namespaces that organizes the set of classes and interfaces. It is used to ensure easy access to thousands of classes. It done by grouping the classes into subgroups. For example util is one of the sub group. Its package consists of classes like linked list, vector and so on. It is accessed by java.util.Vector and so on.

    Exam Topics

    Section 1: Declarations, Initialization and Scoping 

    • 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).
    • 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.
    • 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.
    • 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.
    • 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

    •  Develop code that implements an if or switch statement; and identify legal argument types for these statements.
    • 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.
    • Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.
    • Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.
    • 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.
    • 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

    •  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.
    • 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.
    • 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.
    • 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

    • Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.
    • Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.
    • 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

    •  Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.
    • 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.
    • Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.
    • 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.
    • Develop code that implements "is-a" and/or "has-a" relationships.

    Section 6: Collections / Generics

    • 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.
    • Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.
    • 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.
    • 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.
    • 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

    • 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.
    • Given an example of a class and a command-line, determine the expected runtime behavior.
    • 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.
    • 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.
    • Given the fully-quali fied 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.
    • 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.

    Oracle Java certification

    Which Oracle Java certification?

     Java certifications were previously given by Sun Micro Systems when it owned Java. Once it was bought by Oracle the certification program was als taken over by Oracle and the Sun Certified Java Programmer (SCJP) was renamed to Oracle Certified Professional, Java SE 6 Programmer(OCP).

    List of Basic Java certifications available

  • Oracle Certified Associate, Java SE 5/SE 6
  • Oracle Certified Associate, Java SE 7 Programmer 
  • Oracle Certified Professional, Java SE 5 Programmer
  • Oracle Certified Professional, Java SE 7 Programmer
  • Oracle Certified Professional, Java SE 6 Programmer
  • Oracle Certified Java Programmer, Bronze SE 7 (Available only in Japan)

  • Which One to Choose?

    If you plan to study Oracle Certified Professional(OCP), Java SE 7 Programmer, you need to first complete Oracle Certified Associate, Java SE 7 Programmer. So if you want OCP certification and dont want to waste time and money then take Oracle Certified Professional, Java SE 6 Programmer which does not need  Oracle Certified Associate, Java SE 6 certification.

    My Suggestions  

    Know basics and want to save money - Oracle Certified Professional, Java SE 6 Programmer, You can upgrade to Oracle Certified Professional(OCP), Java SE 7 Programmer later if at all required.
    New to java - Oracle Certified Associate, Java SE 7 Programmer and then Oracle Certified Professional(OCP), Java SE 7 Programmer.

    Certification Cost

    To take the test a candidate must buy a voucher from Oracle (approximately US$300 in the US, £150 (excluding VAT) in the UK, AUD 316 plus tax in Australia, Rs. 8000 plus taxes in India) and book the test at least a week in advance. The test consists of multiple choice questions. In June 2011, Oracle moved from Prometric to Pearson VUE as their test provider.

    List of Advanced Java certifications available

  • Oracle Certified Master, Java SE 6 Developer
  • Oracle Certified Master, Java EE 5 Enterprise Architect
  • Oracle Certified Professional, Java EE 5 Business Component Developer
  • Oracle Certified Professional, Java EE 5 Web Component Developer
  • Oracle Certified Master, Java EE 6 Enterprise Architect
  • Oracle Certified Expert, Java EE 6 Web Services Developer
  • Oracle Certified Expert, Java Platform, EE 6 Web Component Developer
  • Oracle Certified Professional, Java EE 5 Web Services Developer
  • Oracle Certified Expert, Java EE 6 Java Persistence API Developer
  • Oracle Certified Expert, Java EE 6 Enterprise JavaBeans Developer
  • Oracle Certified Professional, Java ME 1 Mobile Application Developer
  • Oracle Certified Expert, Java EE 6 Web Services Developer
  • Oracle Certified Professional, Java EE 5 Web Services Developer
  • Oracle Certified Expert, NetBeans Integrated Development Environment 6.1 Programmer