Jun 20, 2012

SCJP 1.5 - Chapter 1(Part 2) - Declaration and Access Control - Notes

Click here for Part 1 - SCJP 1.5 - Chapter 1(Part 1) - Declaration and Access Control - Notes

The final keyword:
- final methods cannot be over-ridden
- the value of final variables cannot be changed
- the value in final arguments cannot be changed inside the method
- if a reference variable is marked final, it cannot be re-assigned to another object(the data in the object can be modified, buth the reference variable cannot be made to refer to another object).
eg. public Contact getContact(int fileName, final int phoneNumber)
The value of the phoneNumber cannot be changed inside the method.

Abstract method:
- Methods are declared, but not implemented. The first concrete sub-class must implemet all the abstract methods of an abstract class
- If atleast one method is abstract, then the class should be declared as an abstract class. An abstract class need not have any abstract methods.
eg.
public abstract class PhoneBook {
      public abstract void viewContacts();
}
- An abstract class cannot be private, static or final

Native methods:
- Methods implemented in a platform-dependant code, like C.
- native keyword applies only to methods.

Var-args(Methods with variable arguments, a JDK1.5 feature):
- Arguments : passed, during the method invocation
- Parameters : recevied by methods(in the method signature)
- eg. void doStuff(int... x); // expects one to many int parameters
- only the last parameter can have var-args:
    eg.  void doStuffs(int... x, int... y); //illegal
     void doStuffs(int x, int... y); //legal

Constructor Declarations:
- In Java, objects are constructed
- If we dont create a constructor explicity, the compiler will construct one for us
- A constructor will not have any return type
eg.
public class Tester {
      protected Tester(){} // a constructor
      protected void Tester(){} //not a constructor, but a method, since it has a return type     
}
Variable Declarations:
2 types of variables in Java
- Primitives : char, byte, short, int, long, float, double, boolean
- Reference Variables: to refer an object, can refer the declared type or its sub-type.

Local (Automatic/Stack/Method) Variables:
- before the local variable can be used, it has to be initialized with a value (else gives compilation error)
- unlike instance varaibles, local varaibles do not get default values.

Shadowing:
Declaring a local variable with the same name as an instance variable

Stack & Heap:
Local variables & Reference to object variables are stored in Stack & Objects are stored in the heap.

The this keyword refers to the object currently running.

Array Declarations:
The size of an array should never be included in its declaration.
eg.
int[5] scores; //illegal
Transient Variables:
Transient Variable cannot be serialized. They are skipped while Serializing.

Volatile Variables:
Volatile variables can be modified concurrently by multiple threads. The volatile modifier tells the JVM that a thread accessing the variable must always reconcile its own private copy of the variable with the master copy in memory.

Transient and Volatile keyword can be applied only to instance variables.

Enums:
- cannot be defined within a method
- should be public (or) default
  

Jun 19, 2012

SCJP 1.5 - Chapter 1(Part 1) - Declaration and Access Control - Notes

Inheritence:
Allows code in one class to be used in another class. Allows us to define a general(more abstract) superclass, and extend it with more specific sub-classes.

A subclass that inherits from the superclass is automatically given accessible instance variables and methods defined by the superclass, but is also free to override superclass methods to define more specific behavior.

Cohesive:
Cohesion indicates the degree to which a class has a single, well-focused urpose.
Every class should have a focused set of responsibilities. Cohesiveness defines the extent to which a class has a focussed set of responsibilities.

Coupling:
Coupling is the degree to which one class knows about another class.
How a class is tied to another-classes.
High cohesiveness and Loose coupling is desired.

Legal Identifiers:
- Identifiers must start with a letter, $ or _, cannot start with a number or special characters
- After the first character, Identifier can have any combination of letters, currency symbol, connecting characters or numbers
- No limit on the size of a legal identifier.

Class:
A class is a template that defines the state and behavior objects of its type support.
Naming a class - It should be a noun, with the first letter capitalized, and if it has more than one word, it should follow the "camelCase" notation. eg. Dog, Account, PrintWriter.

Interfaces:
Interface is like a 100% abstract superclass that defines the methods a subclass must support, but not how they must be supported.
- methods are public abstract(whether mentioned or not)
- variables are public static final(whether mentioned or not)
- An interface cannot be static, final, strictfp or native
- An interface can extend only another interface
- An interface cannot implement another interface or class
- An interface is always public abstract(whether mentioned or not)
 eg. public abstract interface Rollable{}
Naming an interface - Should be an adjective. Other rules remain the same as that for a class. eg. Runnable.

Object:
Instance of a class, created by the JVM whenever it encounters the new keyword.

Naming Conventions (variables, constants & methods):
variable - Should have meaningful names (camelCase for long names)
constant(static final) - Should have meaningful names + CAPS
method - verb-noun combination, telling what it does. eg. getBalance, doCalculation, setCustomerName

Source File Naming Rules:
- There can be only one public class in a source file, Its name should be the name of the Java file
- There can be more than one non-public classes in a source file
- Source files with no public classes can have a name that does not match with any of the classes in the file.

Modifiers in Java (2 types):Access Modifiers: public(any class can acess), private(only class and its members can access), protected-(class & its sub-classes can access)  & default - (package level access)
Non-access Modifiers: strictfp(floating point arithmatic corresponds to IEEE 754 standard rules), final & abstract

Abstract & Final Classes:
- A class cannot be both final & abstract(since final means the class cannot be sub-classed and abstract means the methods of the class needs to be implemented by the extending class)
- Abstract class cannot be instantiated
- An abstract class can have both abstract and non-abstract methods.

Class Access:
When we say Class A has access to Class B, it means Class A can:
- Create an instance of Class B
- Extend class B(ie. become a subclass of Class A)
- Access certain methods and variables of class B, depending on the access control of those methods & varables.

Access modifiers for local methods:
- Local varaibles cannot have access modifiers.

Click here for Part 2 - SCJP 1.5 - Chapter 1(Part 2) - Declaration and Access Control - Notes

Jun 18, 2012

Spring DAO


Objective:
Lets create an example for Spring DAO using jnidiTemplate.

1) Start the Hypersonic SQL DB & Create the "contacts" table in Hypersonic SQL
Refer to the following for creating the table in Hypersonic SQL -
                 a) For configuring & starting the HSQL Server
                 b) For creating the "contacts" table in HSQL Server


3) Create the Java Components:
                a)Create the Model: Contact.java

package com.dct.phonebook.model;
public class Contact {
      private String name;
      private int phone;
     
      public Contact(String name, int phone){
            this.name = name;
            this.phone = phone;
      }    
      public String getName() {
            return name;
      }    
      public void setName(String name) {
            this.name = name;
      }    
      public int getPhone() {
            return phone;
      }    
      public void setPhone(int phone) {
            this.phone = phone;
      }
}

              b)Create the DAO contract(interface): ContactsDAO.java


package com.dct.phonebook.dao;
import com.dct.phonebook.model.Contact;

public interface ContactsDAO {
      public void addContact(final Contact contact) throws Exception;  
}

            c)Create the implementation for the contract: ContactsDAOImpl.java

package com.dct.phonebook.dao.impl;
import java.sql.Connection;
import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import com.dct.phonebook.dao.ContactsDAO;
import com.dct.phonebook.model.Contact;

public class ContactsDAOImpl implements ContactsDAO {
     
      private DataSource dataSource;
      private JdbcTemplate jdbcTemplate;
     
      public DataSource getDataSource() {
            return dataSource;
      }

      public void setDataSource(DataSource dataSource) {
            this.dataSource = dataSource;
      }

      public void addContact(final Contact contact) throws Exception {       
            Connection conn = null;      
            try{
                
                String sql = "insert into contacts(name,phone) values(?,?)";
                jdbcTemplate = new JdbcTemplate(dataSource);         

                jdbcTemplate.update(sql, new Object[]{contact.getName(),     contact.getPhone()});          
           
            } catch(Exception e){              
                  throw e;
            } finally {
                  if(conn!=null){
                        try{
                              conn.close();
                        } catch(Exception e){
                              throw e;
                        }
                  }
            }
      }    
}
           d)Create the Spring configuration files:
                   - Configure the dataSource : spring-datasource.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

      <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="org.hsqldb.jdbcDriver" />      
            <property name="url" value="jdbc:hsqldb:http://localhost/phonebook"/>
            <property name="username" value="SA" />
            <property name="password" value="" />
      </bean>

</beans>
 
                - Configure the Model: spring-model.xml
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

      <bean id="contactsDAO" class="com.dct.phonebook.dao.impl.ContactsDAOImpl">
            <property name="dataSource" ref="dataSource" />
      </bean>

</beans>

               - Create the Application Context file: spring-phonebook.xml
 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

      <import resource="datasource/spring-datasource.xml" />
      <import resource="model/spring-model.xml" />

</beans>

                e) Create the test class for testing this application: Phonebook.java

package com.dct.phonebook;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.dct.phonebook.dao.ContactsDAO;
import com.dct.phonebook.model.Contact;


public class Phonebook {
     
    public static void main(String[] args) throws Exception {
      ApplicationContext context =
            new ClassPathXmlApplicationContext("resources/spring-Phonebook.xml");

        ContactsDAO contactsDAO = (ContactsDAO) context.getBean("contactsDAO");
        Contact contact = new Contact("renganath", 97890);
        contactsDAO.addContact(contact);                                                                                                                                                                                                                                             
   }   
}

The folder structure of the final application is: