Sun Certified Java Programmer - Preparation Guide

by JustEtc Publications Ltd




Distributed by justEtc

Opening and reading files with Java JDK 1.0.x



   1. Open the file with the File class;
   2. Create a FileInputStream object using the File object;
   3. Convert the FileInputStream to a BufferedInputStream to greatly increase file reading speed;
   4. Convert the BufferedInputStream to a DataInputStream; the methods of DataInputStream give me a fair amount of flexibility in reading the data.
   5. Read the file until the end


File f = new File("mydata.txt"); 
FileInputStream fis = new FileInputStream(f); 
BufferedInputStream bis = new BufferedInputStream(fis); 
DataInputStream dis = new DataInputStream(bis);  
String record = null; 

try { 

   while ( (record=dis.readLine()) != null ) { 
      // 
      // put your logic here to work with "record" 
      // 
   } 

} catch (IOException e) { 
   // 
   // put your error-handling code here 
   // 
} 



Linked List and Iterator in Java



/*
 * LinkedList.java
 *
 * Created on January 10, 2008, 8:51 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package linkedlist;

import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collections;
import java.util.Random;

/**
 *
 * @author Sayed
 */
public class LinkedListTest {
    
    /** Creates a new instance of LinkedList */
    public LinkedListTest() {
    }
    
    /**
     *Example operations using linked lists
     */
    
    public void linkedListOperation(){
        
        final int MAX = 10;
        int counter = 0;

        //create two linked lists
        List listA = new LinkedList();
        List listB = new LinkedList();

        //store data in the linked list A
        for (int i = 0; i < MAX; i++) {
            System.out.println("  - Storing Integer(" + i + ")");
            listA.add(new Integer(i));
        }
       
        //print data from the linked list using iterator 
        Iterator it = listA.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }

        //print data from the linked list using listIterator. 
        counter = 0;
        ListIterator liIt = listA.listIterator();
        while (liIt.hasNext()) {
            System.out.println("Element [" + counter + "] = " + liIt.next());
            System.out.println("  - hasPrevious    = " + liIt.hasPrevious());
            System.out.println("  - hasNext        = " + liIt.hasNext());
            System.out.println("  - previousIndex  = " + liIt.previousIndex());
            System.out.println("  - nextIndex      = " + liIt.nextIndex());
            System.out.println();
            counter++;
        }


        //retrieve data from the linked list using index
        for (int j=0; j < listA.size(); j++) {
            System.out.println("[" + j + "] - " + listA.get(j));
        }

        //find the location of an element
        int locationIndex = listA.indexOf("5");
        System.out.println("Index location of the String \"5\" is: " + locationIndex);  

        //find the first and the last location of an element
        System.out.println("First occurance search for String \"5\".  Index =  " + listA.indexOf("5"));
        System.out.println("Last Index search for String \"5\".       Index =  " + listA.lastIndexOf("5"));

        //create a sublist from the list 
        List listSub = listA.subList(10, listA.size());
        System.out.println("New Sub-List from index 10 to " + listA.size() + ": " + listSub);

        //sort the sub-list
        System.out.println("Original List   : " + listSub);
        Collections.sort(listSub);
        System.out.println("New Sorted List : " + listSub);
        System.out.println();

        //reverse the new sub-list
        System.out.println("Original List     : " + listSub);
        Collections.reverse(listSub);
        System.out.println("New Reversed List : " + listSub);
        System.out.println();

        //check to see if the lists are empty
        System.out.println("Is List A empty?   " + listA.isEmpty());
        System.out.println("Is List B empty?   " + listB.isEmpty());
        System.out.println("Is Sub-List empty? " + listSub.isEmpty());
        
        //compare two lists
        System.out.println("A=B? " + listA.equals(listB));        
        System.out.println();

        //Shuffle the elements around in some Random order for List A
        Collections.shuffle(listA, new Random());

        //convert a list into an array
        Object[] objArray = listA.toArray();
        for (int j=0; j < objArray.length; j++) {
            System.out.println("Array Element [" + j + "] = " + objArray[j]);
        }

        //clear listA
        System.out.println("List A   (before) : " + listA);        
        System.out.println();
        listA.clear();
        System.out.println("List A   (after)  : " + listA);        
        System.out.println();
        
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        LinkedListTest listExample = new LinkedListTest();
        listExample.linkedListOperation();
    }
    
}



Set, TreeSet, Iterator in Java



/*
 * TreeSetExample.java
 *
 *Illustrates mathematical set operations
 *
 * Created on January 10, 2008, 9:28 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package treesetexample;
import java.util.Set;
import java.util.TreeSet;
import java.util.Iterator;

/**
 *
 * @author Sayed
 */

public class TreeSetExample {
    
    /** Creates a new instance of TreeSetExample */
    public TreeSetExample() {
    }
    
    //example set operations 
     public static void treeSetOperations() {

        final int MAXIMUM = 20;

        //create a TreeSet
        Set ss = new TreeSet();

        //store data in the set, set can contain only one type of data
        for (int i = 0; i < MAXIMUM; i++) {
            System.out.println("  - Storing Data(" + i + ")");
            ss.add(new Integer(i));
        }

        //display set data using an iterator
        Iterator it = ss.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }

        
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        TreeSetExample treeSet = new TreeSetExample();
        treeSet.treeSetOperations();
    }
    
}



Java Collections Framework



Some URLs
http://www.javaworld.com/javaworld/jw-11-1998/jw-11-collections.html?page=2
http://www.informit.com/articles/article.aspx?p=781700
http://java.sun.com/docs/books/tutorial/collections/index.html
Vector Vs. ArrayList
Vector vs. Hashtable
ArrayList vs. LinkedList



SCJA: Java Really Basic Stuffs - But you may need to know them for exams like SCJA



SCJA: Syllabus

http://www.sun.com/training/catalog/courses/CX-310-019.xml

Floating point types: http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html
Enumerated types in Java: http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
is a finite set of symbolic literals
is represented as first-class object
are allowed in case statements
the literals may be any valid Java identifier

Java Interface
an interface may NOT contain any concrete method implementations
an interface is NOT a class of any style
an interface is NOT a member of a class
An interface defines a set of abstract methods that may have many implementations.

Class Association, Class Composition, dependency:
Compositions may also have navigation methods, but these methods must NOT pass references to the owned objects. This is usually achieved by passing back a copy of the object rather than the owned object itself.
Composition implies that the owning object controls the life cycle of the owned object
Dependency merely imply that one object uses another object during computations.

disadvantages of proper information hiding?
Access to object attributes incur a runtime penalty.However, the Sun hotspot JVM usually can eliminate the added overhead by "inlining" the methods where they are called.
a mutator method is longer than an assignment operation
it is time consuming to use methods to access object attributes rather than direct access.

program to an interface
References to objects should be declared as interfaces rather than concrete classes
the reference variables to objects that need to be as generic as possible. This is the "program to an interface" principle.

correct representation of an attribute in UML

- attr : int uml

0..1 indicates zero or one multiplicity, which is how you can represent an optional association.

? is NOT a valid multiplicity indicator.
* is an abbreviation for 0..*.
M is NOT a valid multiplicity indicator.
? is NOT a valid multiplicity indicator.
0..* is exactly how to indicate zero or more.

Statement types



Java: Some basic important stuffs



Data types to represent telephone numbers:

a string of ten digits can represent all ten-digit telephone numbers.
an object can hold data (integers or strings) of the elements of a telephone number
an integer data type can represent all ten-digit numbers
-- a boolean can only represent two values
an enumerated type can only represent a fixed number of constant



Abstract Class:

An abstract class may have constructors, but it is illegal to invoke the new operator on an abstract class
An abstract class is allowed to have method implementations
There is no restriction about the placement of abstract classes in a class hierarchy
It is legal for an abstract class to implement an interface and implement one or more interface methods



Design a role player game:

creating an abstract superclass for a generic player will simplify the design.
This is because the maintenance of the common methods will be simplified.
An abstract class is the perfect container, as a superclass, for the common methods



Model

A sports team with fixed number of players in which players may participate in other teams
a many-to-many association from players to team Will work

Java Bean convention for setter methods

void setFirstName(String value)



Data Hiding

A well-encapsulated class must have all of its attributes marked private.
A well-encapsulated class must hide all internal methods. This is because this is NOT part of the class's public interface.
NOT all attributes require accessor or mutator methods.

The principle of "programming to an interface"?

Generalize the return type of a method. The return type of a method should be as abstract as possible, such that any object of that type could be returned. If a concrete class is used as the return type, then only an object of that type (or its subclasses) can be returned.

A class hierarchy is a static part of the code structure. Polymorphism and program to an interface are principles that apply to the dynamic aspects of the code, such as the objects that are stored in variables and passed through methods.

The parameter type of a method should be as abstract as possible, such that any object of that type could be passed in to the method. If a concrete class is used as the parameter type, then only an object of that type (or its subclasses) can be used as a parameter.

The type of an instance variable should be as abstract as possible, such that any object of that type could be held by the owning object. If a concrete class is used as an instance variable type, then only an object of that type (or its subclasses) can be held in that variable.

The relationship between classes and interfaces form only a static part of the code structure. Polymorphism and program to an interface are principles that apply to the dynamic aspects of the code



JAVA: Some links: useful for exams like scjp/scja



Assertions in Java: http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html
Enum in Java:http://www.java2s.com/Code/Java/Language-Basics/Enum.htm
StringBuffer and StringBuilder Classes have similar methods where StringBuffer is synchronized: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html
Serialize and Deserialize: http://java.sun.com/j2se/1.4.2/docs/api/java/io/Serializable.html
java.util package is very important: http://java.sun.com/j2se/1.4.2/docs/api/java/util/package-summary.html



SCJP: Java Operators



Exams like SCJP test your understanding of Java operators and how to use them like:
assignment operators: =, +=, -=
arithmetic operators: +, -, *, /, %, ++, --
relational operators: <, <=, >, >=, ==, !=
logical operators: &, |, ^, !, &&, ||
conditional operators: ? :
Also operators to check the equality of two objects or two primitives

In the following table operators and their precedences are shown. Upper rows operators have higher precedence. Same row operators have equal precedence. For equal precedence operators, All binary operators except the assignment operators work from left to right while assignment operators work from right to left.

Operator Precedence
OperatorsPrecedence
postfixexpr++ expr--
unary++expr --expr +expr -expr ~ !
multiplicative* / %
additive+ -
shift<< >> >>>
relational< > <= >= instanceof
equality== !=
bitwise AND&
bitwise exclusive OR^
bitwise inclusive OR|
logical AND&&
logical OR||
ternary? :
assignment= += -= *= /= %= &= ^= |= <<= >>= >>>=
The following quick reference summarizes the operators supported by the Java programming language.

Simple Assignment Operator

=	Simple assignment operator

Arithmetic Operators

+ 	Additive operator (also used for String concatenation)
- 	Subtraction operator
*	Multiplication operator
/ 	Division operator
%	Remainder operator

Unary Operators

+ 	Unary plus operator; indicates positive value (numbers are positive without this, however)
- 	Unary minus operator; negates an expression
++  	Increment operator; increments a value by 1
--    	Decrement operator; decrements a value by 1
!     	Logical compliment operator; inverts the value of a boolean

Equality and Relational Operators

==	Equal to
!=	Not equal to
>	Greater than
>=	Greater than or equal to
<	Less than
<=	Less than or equal to

Conditional Operators

&& 	Conditional-AND
|| 	Conditional-OR
?:      Ternary (shorthand for if-then-else statement)

Type Comparison Operator

instanceof	Compares an object to a specified type 

Bitwise and Bit Shift Operators

~	Unary bitwise complement
<<	Signed left shift
>>	Signed right shift
>>>	Unsigned right shift
&	Bitwise AND
^	Bitwise exclusive OR
|	Bitwise inclusive OR



Details about java operators



SCJP: Classpath and Jar



Java certification exams like SCJP test your knowledge about java classpath. Check here for an excellent resource on the topic .

System classpath

We can specify classpath in the command line or make use of a `system' class path. The IDEs have their own way of maintaining class paths. System class paths will be used by both the Java compiler and the JVM in the absence of specific instructions.

Set Linux System Classpath:
CLASSPATH=/myclasses/myclasses.jar;export CLASSPATH

Windows:
set CLASSPATH=c:\myclasses\myclasses.jar

For permanent result, in Linux, put the commands in the file .bashrc in your home directory. On Windows 2000/NT, set it from `Control Panel', System, Environment Variables.

You can also specify .jar files full of your required classes in your classpath.

CLASSPATH=/usr/j2ee/j2ee.jar:.;export CLASSPATH

where the `.' indicates `current directory'.

From command line, if you want to add more paths to the classpath use:

Linux:javac -classpath $CLASSPATH:dir1:dir2 ...

Windows:javac -classpath %CLASSPATH%;dir1:dir2 ...

if you have spaces in your path use double quote to concatenate words.

Also check this resource



SCJP: Topics and Resources : will be continued



SCJP topics and related resources are provided. I have skimed through the resources at least one time.

Garbage Collection

Parameter Passing Command Line Parameter
Access Modifiers, Package Declaration, Import
Concurrency:java.lang.Thread and java.lang.Runnable Java Thread:wait/notify/notifyall-lock OOP Concept 1



Java Collection Framework



Array
Benefits Constraints
  • Data access is fast.
  • Good for ordered data, which is not changed or searched frequently.
  • Inefficient if number of elements grow.
  • Inefficient if an element to be inserted in middle of collection.
  • Provides no special search mechanism.


Linked List
Benefits Constraints
  • Allows efficient inserts/delete at any location
  • Allows arbitrary growth of collection.
  • Applying order to the elements is easy.
  • Slower while accessing elements by index.
  • No special search mechanism is provided.



Tree
Benefits Constraints
  • Easy addition/deletion in middle.
  • Allows arbitrary growth.
  • A better and efficient search mechanism.
  • Ordering is peculiar and some comparison mechanism is required.
  • Searching is not efficient for unevenly distributed data.



Hashtable
Benefits Constraints
  • Efficient searching.
  • Good access mechanism.
  • Allows arbitrary growth of collection.
  • Not good for small data set because of overheads.
  • Overhead for storing keys for the values in collection.
  • Overhead of hashing scheme.



SCJP: Language Fundamentals



Class declaration and java source file.

Keywords and Identifiers

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

Default Values, Local Variables

Arrays

Argument passing during method calls



SCJP: Garbage Collection



Garbage Collection



SCJP: Flow controls and exception



Flow Control and Exceptions Flow control statements

switch statement

switch(expression){
case ConstantExpression: statement(s);
case ConstantExpression: statement(s);
.
.
.
default: statement(s);
}

break and continue

Checked and Unchecked Exceptions

Checked Exceptions Unchecked Exceptions



Code Conventions for the Java Programming Language



Why Have Code Conventions?

Java Code Conventions



SCJP: Class Declarations



class declarations

Abstract Classes

Nested Classes



SCJP: Interfaces



Interface



SCJP: Random Stuffs





Java : SCJP: Important Resources





SCJP: Basic Java I/O





SCJP: Java Concurrency





Java: Collections Frameworks





SCJP: Rules





Sun certifications: Topics





SCJP: Short Notes





SCJP: More Rules





SCJP Practice Exams



Check these practice exams. Be careful that many java rules may have changed over the time. Check that which jdk version or the exam these practice exams support



SCJP Essential Knowledge





Regular Expressions





Generics in Java





Basic Java But Essential Knowledge for exams like SCJA, or to the project managers new to Java technologies





Java Rules





Java Fundamentals





Java File Operation Example



Code that helped me to create http://add.justEtc.net - the Bangladesh section based on the the web-site http://winnipeg.justEtc.net

package hello;

import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: Sayed Ahmed
 * Date: May 30, 2008
 * Time: 9:45:08 PM
 * To change this template use File | Settings | File Templates.
 */

/**
Class containing major methods - operation methods
*/
class Process{
    private FileReader src = null; //source folder
    private FileWriter dest = null; //destination folder
    private ArrayList cityList = new ArrayList(); //arraylist to contain the names of all cities

    private String cityFileName; //reference to the file containing all city names
    private String folderToCopy; //path to the folder to be copied
    private String destination; // path  to the folder where the copy will be kept

    /**
     * Constructor
     */
    Process(){
//JOptionPane.showInputDialog(null,"City File Name");
        cityFileName = "C:\\test_development\\java\\resources\\cityList.txt";  
//JOptionPane.showInputDialog(null,"Folder to Copy");
        folderToCopy = "C:\\test_development\\java\\hello\\src\\resources\\source\\Winnipeg";  
//JOptionPane.showInputDialog(null,"Destination Path"); 
        destination = "C:\\test_development\\java\\hello\\src\\resources\\destination";         

        //load city list from the file to an arraylist
        copyCityList(cityFileName);

        //to create a file with links to all the cities of Bangladesh
        createFile();

        //copy a folder (winnipeg) and rename it to all the city names of Bangladesh -- one by one
        Iterator it = cityList.iterator();
        while(it.hasNext()){
            copyDirectory((String) it.next());
        }

    }

    /**
     * load city list into an ArrayList
     */
    private void copyCityList(String cityFileName){
        String city = "";
        try {
            BufferedReader bfCity = new BufferedReader(new FileReader(cityFileName));
            while(null != (city = bfCity.readLine())){
                cityList.add(city);
            }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
        }
    }

    /**
     * copy a folder , name the folder as the city name
     */
    private void copyDirectory(String city){
        try {
            copyDirectory(new File(folderToCopy), new File(destination+"/"+city), city);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    /**
     * Copies all files under srcDir to dstDir.
     * If dstDir does not exist, it will be created.
     * @param srcDir - folder to copy
     * @param dstDir - where to keep
     * @param city  - new folder name
     * @throws IOException
     */
    public void copyDirectory(File srcDir, File dstDir, String city) throws IOException {
        //if srcDirectory is a directory , create the directory
        if (srcDir.isDirectory()) {
            if (!dstDir.exists()) {
                dstDir.mkdir();
            }
            //if srcDir has child directories , create child directories - Recursively
            String[] children = srcDir.list();
            for (int i=0; i