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
| Operators | Precedence |
| postfix | expr++ 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.
- Only "one" top-level public class is allowed per java source file.
- The name of the java source file and the name of the top-level public class MUST be the same.
- If no public class is there in a file, after compiling separate class files will be created for all classes in the file.
- Package statement, import statements and class definition MUST appear in the order given.
Keywords and Identifiers
- Keywords are always in a lower case.
- Some keywords: const, goto, strictfp, and volatile
- Identifiers must start with either letter, $ or _ (underscore) and can have letter, $, _ or digits in it.
- no keyword is allowed as 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
- Each primitive data type has a default value
specified. Variable of primitive data type may be
initialized
- Only class member variables are automatically
initialized. Method variables need explicit
initialization
- Local variables (also known as automatic
variables) are declared in methods and in code
blocks
- Automatic variables are not automatically initialized
- local variables should be explicitly initialized before first use. These are automatically destroyed when they go out of scope
Arrays
- Fixed-sized ordered collection of homogeneous data elements
int[] ints; // array declaration
ints = new ints[25]; // array construction at runtime.
- Array declared, constructed and initialized at the same time.
int[] ints = {1,2,3,4,5}; // array declaration,
- An array of primitive data type created using the new keyword is automatically initialized. Each array element is initialized to its default value.
For example,
char[] arrayOfChars = new char[10];
- Array of object references: An array of object references created using the new keyword is also initialized. Each array element is initialized to its default value, i.e. null.
String[] names = new String[10];
- length is a property of array (and not a method)
- java.lang.Object is the superclass of an array
Argument passing during method calls
- Always a copy of argument value is passed to calling method
- Arguments of primitive data types: first, a copy of the passing variable is made and then it is passed. The original copy remains unaffected
- Object reference as an argument: A copy of object reference is passed for method calls. It still points to the same object. The original copy is affected.
SCJP: Garbage Collection
Garbage Collection
- Java itself does memory management. You do not need to allocate memory at the time of object creation; also you do not need to free memory explicitly
- Object is created either on the heap or on a stack
- Memory heap: Objects created with new keyword are placed in heaps. This memory remains allocated throughout the life cycle of the object. When the object is no more referred, the memory becomes eligible for garbage collection
- Stack: During method calls, objects are created for method arguments and method variables. These objects are created on stack. Such objects are eligible for garbage-collection when they go out of scope.
- Garbage Collection is a low-priority thread in java
- Garbage Collection cannot be forced explicitly. JVM may do garbage collection if it is running short of memory.
- The call System.gc() does NOT force the garbage collection but only suggests that the JVM may make an effort to do garbage collection.
- Garbage Collection is hardwired in Java runtime system. Java runtime system keeps the track of memory allocated. Therefore, it is able to determine if memory is still usable by any live thread. If not, then garbage collection thread will eventually release the memory back to the heap.
- Garbage Collection usually adopts an algorithm, which gives a fair balance between responsiveness (how quickly garbage-collection thread yields?) and speed of memory recovery (important for memory-intensive operations). Responsiveness is especially important in real time systems.
- An object is eligible for garbage collection when no object refers to it.
- An object also becomes eligible when its reference is set to null. (Actually all references to the object should be null for it to be eligible.)
- The objects referred by method variables or local variables are eligible for garbage collection when the method or their container block exits
SCJP: Flow controls and exception
Flow Control and Exceptions
Flow control statements
- Conditional: if, if-else and switch-case
- Looping: for, while, do-while
- Exception handling: try-catch-finally, throw
- Ad hoc flow control: break, continue with or without labels
switch statement
switch(expression){
case ConstantExpression: statement(s);
case ConstantExpression: statement(s);
.
.
.
default: statement(s);
}
- expression: must be char, byte, short, or int, or a compile-time error occurs
- long primitive can be used if type casted to int
- Object reference cannot be used as expression
- Every case expression must be unique
- break statement may be used at the end of a case statement, to discontinue execution.
- There can be at most only one default statement.
- The order of case statements and default can be anything.
break and continue
- A break statement transfers the control out of an enclosing statement. break used within a loop breaks the execution of the current loop. In case of nested loops, the break statement passes the control to the immediate outer loop.
- A continue statement breaks the current iteration and moves to next iteration.
- break and continue with labels.
- Labels specify the target (statement) for continue and break
- continue with label does not jump to the labeled statement but instead jumps to the end of the labeled loop.
- Same label identifiers can be reused multiple times as long as they are not nested.
- Label names do not conflict with the same named identifier(variable, method or class name).
Checked and Unchecked Exceptions
Checked Exceptions
- Checked Exceptions are checked by the compiler to see if these exceptions are properly caught or specified. If not, the code will fail to compile
- Checked exception forces client program to deal with the scenario in which an exception may be thrown
- Checked exceptions must be either declared or caught at compile time
Unchecked Exceptions
- Unchecked exceptions are RuntimeException and all of its subclasses.
- Class java.lang.Error and its subclasses also are unchecked.
- Unchecked Exceptions are not checked by the compiler.
- Runtime exceptions do not need to be caught or declared.
Code Conventions for the Java Programming Language
Why Have Code Conventions?
- 80% of software life cycle is spent on software
maintenance.
- Hardly the original author maintains a software
- Code Conventions improve the readability of the
software
- If you require to ship your source code as a product,
code conventions make your product well packaged
Java Code Conventions
- Avoid assigning several variables to the same value
in a single statement
- Avoid using an object to access a class (static)
variable or method. Use a class name instead
- Don't make any instance or class variable public
without good reason. When the class is essentially
a data structure, you can use public instance
variables
- Two blank lines: Between sections of a source file,
between class and interface definitions
- One blank line: Between methods, between the local
variables in a method and its first statement,
before a block or single-line, between logical
sections inside a method
- Blank spaces: Between a keyword and parenthesis,
after commas in argument lists, after Casts
- Each line should contain at most one statement
- One declaration per line is recommended
- Initialize local variables where they're declared
- Put declarations only at the beginning of blocks
- No space between a method name and the parenthesis
- Methods are separated by a blank line
- Four styles of implementation comments: block,
single-line, trailing, and end-of-line
- Documentation comments describe Java classes,
interfaces, constructors, methods, and fields. Use
/**...*/ for doc comments
- Doc comments: One comment per class, interface, or
member
- Doc comments: Should appear just before the
declaration
- Avoid lines longer than 80 characters
- Break longer lines: after a comma, before an
operator, Prefer higher-level breaks to lower-level
breaks, align new lines with the previous line, or
indent the new line with 8 spaces
- You can get a detailed code conventions at Java Code Conventions
SCJP: Class Declarations
class declarations
- Start with modifiers such as public, private followed
by class keyword
- The class name, with the initial letter capitalized
- The name of the class's parent (superclass),
preceded by the keyword extends (if any). A class can
only extend (subclass) one parent.
- list of interfaces implemented by the class,
preceded by the keyword implements (if any). A class
can implement more than one interface
- The class body, surrounded by braces, {}.
- Class member variable declarations
- Requires three components, in order:
- Zero or more modifiers, such as public or
private
- The field's type
- The field's name.
Abstract Classes
- A class declared with abstract keyword is an abstract
class. It may or may not include abstract methods
- Abstract classes cannot be instantiated
- Abstract classes can be subclassed
- Class containing abstract methods, must be declared to
be abstract
- Abstract methods are methods declared without
implementation (braces)
- The subclass of an abstract class must provide
implementations of all the abstract methods otherwise
the subclass itself needs to be declared as abstract.
- An abstract class may have static and final fields and
methods. Interfaces can not
- If an abstract class contains only abstract method
declarations with no implementations, it should better
be declared as an interface
- It's a good design to declare a common abstract class with common methods with implementations for several very related classes (will extend the abstract class)
- An abstract class can implement an interface but are
not bound to implement all interface methods
Nested Classes
- Classes declared under another class are called nested
classes
- Two types: Static Nested: declared with static keyword, Inner Nested: declared with no static keyword
- inner classes have access to other members of the
outer class including private members
- Static nested classes do not have access to other
members of the outer class
- Static nested classes are accessed using the outer
class name such as: OuterClass.StaticNestedClass
- To use inner classes, the outer class must be instantiated first. Then, inner object can be created as follows:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
- Local inner classes: Declared within the body of a
method
- Anonymous inner classes: Declared within the body of
a method without naming it
- Inner classes may have similar access modifiers like
other outer class members
- Why use nested classes:
- For logically grouping classes that are only
used in one place
- It increases encapsulation.
- May lead to more readable and maintainable
code
SCJP: Interfaces
Interface
- An interface is a reference type, similar to a class
- Interfaces can contain only constants, method
signatures, and nested types
- No method is implemented
- Interfaces cannot be instantiated
- They can only be implemented by classes or extended
by other interfaces
- Interfaces are not part of the class hierarchy
- A class can implement multiple interfaces
SCJP: Random Stuffs
- An enum may NOT be declared in a method
- An enum can be imported
- If the JVM has a choice, it will select a method
without varargs before selecting a method with
varargs
- When enums are equal, both .equals and == always
return true
- The headMap() method returns the portion of the map
whose keys are less than the key sent to it
- The asList() method of Arrays creates a fixed-size
list that is backed by the array, so no additions are
possible.
- A static initialization block is a normal block of
code enclosed in braces, { }, and preceded by the
static keyword. Used to initialize class variables
- All enums implicitly extend java.lang.Enum.
- A class can extend only one other class, an
interface can extend any number of interfaces
- An interface might also contain constant
definitions.
- An abstract class that implements an interface may
not implement all interface methods
Java : SCJP: Important Resources
- How to use generics to avoid runtime errors.
- More Generics
- Class casting in Java: How to avoid runtime exception - ClassCastException: overloading, overriding, variable and method hiding
- Java HotSpot virtual machine
- What Java Technology can do?
- Offers from Java Technology
- Java:Common Problems (and Their Solutions)
- Benefits of OOP: Modularity, Information-hiding, Code re-use, Pluggability and debugging ease
- Object oriented concepts in Java
- Variable Naming Conventions in Java
- Java Primitive Data Types
- Java : Arrays: System.arraycopy method
- Java Operators: Carefully look about precedence
- continue and break statements in Java
- Annotations in Java
- Passing Parameters, System.out.printf, Shadowing Variables
- The Garbage Collector
- You can use interface names as return types. The object returned must implement the specified interface.
- when a class name is used as a return type, the returned object must be either a subclass of, or the exact class of, the return type
- Controlling Access to Members of a Class
- Java initializing variables: initialize at declarations, Static Initialization Blocks, private static method to initialize, Initializer blocks for instance variables, A final method for initialization
- Nested Classes
- enum in Java: enums implicitly extend java.lang.Enum. An enum cannot extend anything else. Enums can have methods like classes
- if a variable is declared to be the type of an interface, its value can reference any object that is instantiated from any class that implements the interface
- Interfaces provide an alternative to multiple inheritance
- Java Interfaces
- Rewriting Interfaces
- Covariant return type: An overriding method can return a subtype of the type returned by the overridden method
- The access modifier for an overriding method can allow more, but not less, access than the overridden method
- Hiding fields makes code difficult to read
- java.lang.Object as a super class
- final methods can not be overridden, final classes can not be sub-classed, methods called from constructors should generally be declared final (otherwise, a different implementation of the method in subclasses may create unwanted results)
- Interfaces can not have static or final methods
- System.out.format(.....) and String.format() can be used as alternatives to System.out.println()
- Using Number class vs. primitive data types
- String, StringBuilder, StringBuffer: StringBuilder has capacity(), reverse() methods that String does not have. StringBuffer = StringBuilder but StringBuffer is thread-safe i.e. synchronized. String, and StringBuilder can be converted to each other
- Three kinds of exceptions
- Chained Exceptions: Stack Trace: Logging
SCJP: Basic Java I/O
- ByteStream is the basic I/O stream. Handles data as
a stream of bytes. Does operation with byte unit and
uses 8 bit. FileInputStream, FileOutputStream - can
be used to copy files as byte by byte.
- Character Streams: FileReader and FileWriter are
character streams. They treat file data as 16 bit
unicode charater streams.
- InputStreamReader, OutputStreamWriter are also
character streams. May be used in socket data
reading.
- Line-Oriented I/O: BufferedReader and PrintWriter
- Buffered Streams: BufferedInputStream and
BufferedOutputStream create buffered byte streams,
while BufferedReader and BufferedWriter create
buffered character streams
- You can set autoflush() of buffered streams or
call manually flush() method.
- The scanner API breaks input into individual
tokens. The formatting API assembles data into
nicely formatted, human-readable form.
- Scanner:
Scanner scanner = new Scanner(new BufferedReader(new FileReader("test.txt")));
while (s.hasNext()) {
System.out.println(s.next());
}
- To create formatted output streams, instantiate
PrintWriter not PrintStream
- Check: System.out.format("The square root of %d is %f.%n", i, r);
- System.out and System.err are
PrintStream objects. PrintStream is really a byte
stream but uses some mechanism to emulate
character stream.
- InputStreamReader cin = new
InputStreamReader(System.in); System.in is a byte stream. InputStreamReader is used to emulate a character stream.
- System.console provides character streams to handle
console read/write operations. Provides readPassword method to read password from the console
- Data Streams: Support I/O operations of primitive
data types. DataInputStream and DataOutputStream.
- Check:
out = new DataOutputStream(new
BufferedOutputStream(new FileOutputStream(dataFile)));
out.writeDouble(prices);
out.writeInt(units);
out.writeUTF(descs);
- DataStreams detects an end-of-file condition by catching EOFException
- Correct type to represent currency values: java.math.BigDecimal - an object type
- Object Streams: ObjectInputStream and ObjectOutputStream. Use writeObject and readObject to write and read objects respectively.
- A stream can contain only one copy of an object but many references to it when required.
- File Objects: File I/O
- Random access file:
new RandomAccessFile("test.txt", "r");
new RandomAccessFile("test.txt", "rw");
RandomAccessFile methods:
* int skipBytes(int)
* void seek(long)
* long getFilePointer()
- The new java.nio.* package provides supports to handle
file i/o for high performance applications.
SCJP: Java Concurrency
Java: Collections Frameworks
- Core collection interfaces: Collection (Set(SortedSet), List, Queue), Map(SortedMap)
- A Map is not a true Collection.
-
public interface Collection extends Iterable {
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element); //optional
boolean remove(Object element); //optional
Iterator iterator();
// Bulk operations
boolean containsAll(Collection> c);
boolean addAll(Collection extends E> c); //optional
boolean removeAll(Collection> c); //optional
boolean retainAll(Collection> c); //optional
void clear(); //optional
// Array operations
Object[] toArray();
T[] toArray(T[] a);
}
- Traverse collections:
for (Object o : collection)
System.out.println(o);
- You can also use Iterator to traverse through collections. like: for (Iterator> it = c.iterator(); it.hasNext(); )
- Use iterator over for construct to remove an item from the collection or to iterate parallelly two or more collections.
- Collection to array: String[] a = c.toArray(new String[0]);
- Each Queue method exists in two forms: (1) one throws an exception if the operation fails, and (2) the other returns a special value if the operation fails
- Collections represent data items that form a natural group
- All general-purpose collection implementations have a constructor that takes a Collection argument. This constructor (conversion constructor), initializes the new collection to contain all of the elements in the specified collection
- List list = new ArrayList(c) - where c is a Collection
- Remove all of the null elements from a Collection c:
c.removeAll(Collections.singleton(null));
- Set can not contain duplicate elements. Hence, converting any collection to a set can remove duplicate elements from the collection. Example: Collection noDups = new HashSet(c);
- The Set interface contains only methods inherited from Collection
- Set overrides equals method of the Object class. Two Set instances are equal if they contain the same elements.
- Set implementations: HashSet, TreeSet, and LinkedHashSet. HashSet: uses hash table to store data, the best-performing implementation, not ordered. TreeSet: uses red-black tree as storage, ordered, substantially slower than HashSet. LinkedHashSet: uses hash table as storage with a linked list running through it, ordered according to the insertion order
- HashSet fastest, LinkedHashSet average, TreeSet slowest among sets
- s1.addAll(s2) - s1 union s2 : s1, s2 are sets
- s1.retainAll(s2) - s1 intersection s2
- s1.removeAll(s2) - s1 subtract s2
- Java List Interface
public interface List extends Collection {
// Positional access
E get(int index);
E set(int index, E element); //optional
boolean add(E element); //optional
void add(int index, E element); //optional
E remove(int index); //optional
boolean addAll(int index,
Collection extends E> c); //optional
// Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator listIterator();
ListIterator listIterator(int index);
// Range-view
List subList(int from, int to);
}
- List: types of operations: Positional access, Search, Iteration , Range-view
- List types: ArrayList, LinkedList, Vector (retrofitted to implement List)
- Concatenate two lists: List list3 = new ArrayList(list1);
list3.addAll(list2);
- List has its own Iterator called ListIterator that can move in both directions
- List algorithms: # sort ,
shuffle ,reverse ,rotate , swap ,replaceAll ,fill , copy ,binarySearch ,indexOfSubList ,lastIndexOfSubList
- To generate sublist use subList(fromIndex,toIndex)
- Queue methods add, remove, and element throw exception (illegalStateException, NoSuchElementException) in case of errors while offer, poll, peek return null or false in case of errors.
- Null is not a recommended value for queue as they return null in case of errors. Queue doesn't support null values where LinkedList version of Queue supports.
- Like Set Maps are of three kinds HashMap, TreeMap, LinkedHashMap and HashTable is retrofitted to Map.
- Performance order: HashMap, HashMap, TreeMap, LinkedHashMap, TreeMap
- Sorting collections: If you try to sort a list, the elements should implement Comparable otherwise Collections.sort(list) will throw a ClassCastException.
- You can also create Comparator object for sorting and use Collections.sort(list, comparator). but the list elements should be comparable to one another using the comparator
- SortedSet is a set whose values are sorted according to the natural order or the provided comparator object at creation.
- it's okay to use range-views on sorted sets for long periods of time, unlike range-views on lists.
- Two range-view methods of SortedSet:
SortedSet volume1 = dictionary.headSet("n"); From first but does not include "n", until "n"
SortedSet volume2 = dictionary.tailSet("n");: from "n" to the end of the set.
- SortedMap has similar methods like SortedSet
- From this point implementations of the interfaces (collection related) will be discussed
- HashSet, ArrayList, and HashMap are the most used collections
- TreeSet and TreeMap implementations came from SortedSet and SortedMap interfaces respectively
- Queue implementations: LinkedList: FIFO, PriorityQueue: Ordered according to values
- General-purpose implementations: None are synchronized (thread-safe). All have fail-fast iterators, are Serializable, and support a public clone method.
- Thread-safe collections: the synchronization wrappers, allow any collection to be transformed into a synchronized collection
- The java.util.concurrent package: Implements BlockingQueue interface, which extends Queue, and ConcurrentMap interface, which extends Map. Much higher concurrency than mere synchronized implementations
SCJP: Rules
- A class's superclasses don't have to implement
Serializable in order to be serialized
- if a superclass doesn't implement Serializable then
it's constructor will run during deserialization
- A transient variable's state is lost during
serialization, but a volatile variable's state is
not lost
- Java:Volatile variable
- Transient Variable
- NumberFormat, Calendar, DateFormat are abstract
classes. Use the getInstance method to get
NumberFormat instances.
- The + quantifier in a regular expression indicates
1 or more occurrences, * indicates 0 or more, []
just one character in the group, () indicates a
whole group match.
- The default separator in Scanner class is a blank
NOT a comma
- Multiple threads can be created using the same
Runnable object, but a given thread can be started
only once.
- Thread.yield(): Causes the currently executing
thread object to temporarily pause and allow other
threads to execute.
- Thread.join(): Waits for this thread to die.
- Wait(), Notify(), NotifyAll() methods
- Low coupling: classes know the least possible
about each other, is preferable over tight
coupling.
- High cohesion: Each class has well focused
responsibilities. Is preferable over low
cohesion.
- Polymorphism does NOT apply to static methods.
- Instance variable cannot be referenced from
static method
Sun certifications: Topics
SCJP: Short Notes
- For the package
package com.sun2;
public enum Seasons {SUMMER, FALL, WINTER, SPRING}
Valid import statements are:
import com.sun2.Seasons; // the class
import static com.sun2.Seasons.*; //all enum values
import static com.sun2.Seasons.FALL; //only one enum value
- An interface can extend many interfaces
- Interfaces can have variables, overrides and overloads
- An enum can have methods and can override those methods for a specific enum constant
- var-args can be used to pass arrays, var args can be of 0 or more lengths
- A var-args argument must be a method's last argument
- An override cannot change the return type. Override can use covariant as a return type
- Overloading does not depend on the return type
- From J2se 5.0, a method in a subclass may return an object whose type is a subclass of the type returned by the method with the same signature in the superclass
- When a subclass constructor does not explicitly invoke a superclass constructor, the no-argument constructor of the superclass is automatically called from the subclass constructor. If the super class does not have a no-argument constructor, a compile-time error is displayed
- When subclasses override superclass methods, these superclass methods can be accesses using the super keyword (from subclass methods)
- From java 1.5, enums can be used in a switch
- To enable asserts in java program use -ea switch.
- assert has two forms: assert Expression1 ;, assert Expression1 : Expression2 ;. In the first form only AssertionErorr is displayed, in the second form you can add additional message(Expression2) to the AssertionError. Assert when finds its arguments to be false, it throws AssertionError
- Good places to use assertions: Internal Invariants, Control-Flow Invariants, Preconditions, Postconditions, and Class Invariants
- bad use of assertions: argument checking in public methods, to do any work that your application requires for correct operation
- Assertions should be free of side effects: evaluating the expression should not affect any state that is visible after the evaluation is complete
- An overriding method does not need to throw the overridden method's exception
- Nesting try/catches are ok and normal flow rules apply in case of nesting.
- Accessing uninitialized instance/class wrapper variables (Integer, Short) will cause NullPointerException
- NumberFormatException extends IllegalArgumentException
- JVM when calling a method, to make data types compatible, will widen the parameters before boxing.
- java.io.Console class: Only a single instance exists for a given JVM, All of the methods that read user input are synchronized
- Among File, FileReader, BufferedReader only BufferedReader has a readLine method
- A class's superclasses don't have to implement Serializable in order to be serialized
- if a superclass doesn't implement Serializable then it's constructor will run during deserialization.
- A transient variable's state is lost during serialization
- A volatile variable's state is not lost during serialization
- If Dog has-a Collar, then Collar must implement java.io.Serializable in order to serialize an instance of Dog.
- If Dog extends Animal and Animal implements java.io.Serializable but Dog does NOT implement java.io.Serializable, you can serialize an instance of Dog.
- Serialization rules: # Rule #1: The object to be persisted must implement the Serializable interface or inherit that implementation from its object hierarchy,
# Rule #2: The object to be persisted must mark all nonserializable fields transient
- To make thread instance unserializable: transient private Thread animator;
- java.lang.Object does not implement Serializable. AWT and Swing GUI components, strings, and arrays -- are serializable
- Serialization Details
- NumberFormat, Calendar, and DateFormat are abstract. Use the getInstance method to get instances.
- For java.util.Scanner, the default separator is a blank NOT a comma
- Multiple threads can be created using the same Runnable object, but a given thread can be started only once
- Two invocations of synchronized methods on the same object to interleave - is not possible. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. When a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
- In object oriented design, low coupling is more desirable than high coupling. High cohesion is more desirable than low cohesion. Coupling: class interdependence. Cohesion: Class activities should be well focused.
- Polymorphism does NOT apply to static methods
- Polymorphic calls and co-variant returns can be mixed
- no modifier (package private) is weaker than protected. The order is: public, protected, package private, private
- Kind of' translates to extends, 'contract' translates to implements, and 'composed' translates to a has-a implementation.
- TreeMap: headMap() method returns keys that are less than the argument, and tailMap() returns keys that are greater than(>=) the argument.
SCJP: More Rules
- java -classpath gFolder/Game.jar civilization.java:
In such command, -classpath will override (replace)
CLASSPATH environment variable.
- java -classpath gFolder/Game.jar civilization.java:
if both gFolder and current directory contain
Game.jar then the jar file under gFolder will be
used.
- If you want java compiler to recognize your jar file,
either you have to mention the location of the jar
file in javac command using -classpath switch or you
have to add the jar file in the CLASSPATH environment
variable. Mentionable - you need to add the file,
adding upto the directory will not work.
- Garbage collection: can Java program run out of
memory? yes.
- Can objects be garbage collected even if it has a
valid reference? yes. when no live thread
has access to the object.
- Can Objects created within inner classes be eligible
for garbage collection.? yes.
- Do garbage collector deletes objects from the stack?
No. As objects reside in heaps not in the stack.
- If an object's finalize method runs to completion
will it always be garbage collected? No. The
finalize method may create some other references.
- Arrays.equals(Object[] a1, Object[] a2) : Returns true if
the two specified arrays of Objects are equal to one
another
- The results of Binary search on an unsorted array
are undefined
- <A extends Alpha> Alpha go(int i) is a valid method
declaration with a generic return type. class
Alpha{}
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
- int x=5; String y="3"; System.out.print(x + 1 + y);
Output: 63
- When there is no live reference to an object, the
object becomes eligible for garbage collection.
- The concrete interface method implementation must be
public.
- When a class implements Comparator, it must implement
a compare method.
- When a class implements Comparable, it must implement
a compareTo method.
- The Arrays.asList() method creates a fixed-size list
- A method like void go(Set a) can be called
with objects created as: TreeSet t = new TreeSet();
TreeSet t = new TreeSet();. Remember,
TreeSet t = new TreeSet();
TreeSet t = new TreeSet(); will not work
where Dog is a sub-class of Animal.
- When two enums are equal, both .equals and == always
return true.
- TreeSet is ordered in their natural order or
according to the Comparator provided at creation.
- SortedMaps are abstract
- Is-a relationships can use inheritance
- Tightly encapsulated classes can have a has-a
relationship
- is-a or has-a relationships does not apply to methods
- java command in details:
Usage: java [-options] class [args...]
(to execute a class)
or java [-options] -jar jarfile [args...]
(to execute a jar file)
where options include:
-client to select the "client" VM
-server to select the "server" VM
-hotspot is a synonym for the "client" VM [deprecated]
The default VM is client.
-cp
-classpath
A ; separated list of directories, JAR archives,
and ZIP archives to search for class files.
-D=
set a system property
-verbose[:class|gc|jni]
enable verbose output
-version print product version and exit
-version:
require the specified version to run
-showversion print product version and continue
-jre-restrict-search | -jre-no-restrict-search
include/exclude user private JREs in the version search
-? -help print this help message
-X print help on non-standard options
-ea[:...|:]
-enableassertions[:...|:]
enable assertions
-da[:...|:]
-disableassertions[:...|:]
disable assertions
-esa | -enablesystemassertions
enable system assertions
-dsa | -disablesystemassertions
disable system assertions
-agentlib:[=]
load native agent library , e.g. -agentlib:hprof
see also, -agentlib:jdwp=help and -agentlib:hprof=help
-agentpath:[=]
load native agent library by full pathname
-javaagent:[=]
load Java programming language agent, see java.lang.instrument
Regular Expressions
- java.util.regex provides APIs for pattern matching
with regular expressions
- java.util.regex API is most similar to that found in
Perl
- java.util.regex: Three important classes: Pattern,
Matcher, and PatternSyntaxException
- Pattern : no public constructors : must call one of
the public static compile methods to get a Pattern
object
- Matcher: To get a Matcher object call matcher method
on a Pattern object. No public constructor.
- PatternSyntaxException: regular expression pattern
syntax error. unchecked exception.
- Notice: matcher.find(),matcher.group(),
matcher.start(), matcher.end()
- Regular expression metacharacter: a character with
special meaning in a regular expression.
- Java meta characters: ([{\^-$|]})?*+.
- ! @ and # never carry a special meaning
- enforce a metacharacter to be treated as an ordinary character: precede the metacharacter with a backslash, enclose it within \Q (which starts the quote) and \E (which ends it)
- Character classes:
|
Character Classes
|
[abc]
|
a, b, or c (simple class)
|
[^abc]
|
Any character except a, b, or c (negation)
|
[a-zA-Z]
|
a through z, or A through Z, inclusive (range)
|
[a-d[m-p]]
|
a through d, or m through p: [a-dm-p] (union)
|
[a-z&&[def]]
|
d, e, or f (intersection)
|
[a-z&&[^bc]]
|
a through z, except for b and c: [ad-z] (subtraction)
|
[a-z&&[^m-p]]
|
a through z, and not m through p: [a-lq-z] (subtraction)
|
- Simple Classes: [bcr]at, Negation: [^bcr]at, ranges:[a-c], union:[0-4[6-8]], Intersections:[0-9&&[345]], subtraction:[0-9&&[^345]]
- Quantifiers:
|
Quantifiers |
Meaning |
|
Greedy |
Reluctant |
Possessive |
X? |
X?? |
X?+ |
X, once or not at all |
X* |
X*? |
X*+ |
X, zero or more times |
X+ |
X+? |
X++ |
X, one or more times |
X{n} |
X{n}? |
X{n}+ |
X, exactly n times |
X{n,} |
X{n,}? |
X{n,}+ |
X, at least n times |
X{n,m} |
X{n,m}? |
X{n,m}+ |
X, at least n but not
more than m times |
- Zero-length matches always start and end at the same index position
- [abc]+ (a or b or c, one or more times) or (abc)+ (the group "abc", one or more times)
- Greedy quantifiers: the matcher reads in, or eat, the entire input string prior to attempting the first match. If it fails, the matcher backs off the input string by one character and tries again, repeating the process until a match is found or there are no more characters left to back off from.
Reluctant quantifiers: start at the beginning of the input string, then reluctantly eat one character at a time looking for a match.
possessive quantifiers: always eat the entire input string, trying once (and only once) for a match.
- Backreferences: To match any 2 digits, followed by the exact same two digits, you would use (\d\d)\1 as the regular expression: here \1 is the back reference to indicate to call the group(\d\d) one more time.
-
|
Boundary Matchers |
^ |
The beginning of a line |
$ |
The end of a line |
\b |
A word boundary |
\B |
A non-word boundary |
\A |
The beginning of the input |
\G |
The end of the previous match |
\Z |
The end of the input but for the final terminator, if any |
\z |
The end of the input |
- pattern = Pattern.compile("[az]$", Pattern.MULTILINE | Pattern.UNIX_LINES);
- The quote(String s) method of the Pattern class, returns a literal pattern String for the specified String. Metacharacters or escape sequences in the input sequence will be given no special meaning.
- Matcher class methods: matches() requires the entire input sequence to be matched, while lookingAt does not
- Matcher class methods
Generics in Java
- Generics can prevent many run time errors.
- A generic class:
public class Box<T> {
private T t; // T stands for "Type"
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
}
Object creation:
Box<Integer> integerBox = new
Box<Integer>();
- Generic method syntax: public <U> void
inspect(U u){}
- Type Erasure:Check this code:
public class MyClass<E> {
public static void myMethod(Object item) {
if (item instanceof E) { //Compiler error
...
}
E item2 = new E(); //Compiler error
E[] iArray = new E[10]; //Compiler error
E obj = (E)new Object(); //Unchecked cast
warning
}
}
Basic Java But Essential Knowledge for exams like SCJA, or to the project managers new to Java technologies
- By definition an enumerated type is a finite set of
symbolic literals
- In Java an enumerated type is represented as
first-class object.
- Enumerated type literals are allowed in case
statements.
- The literals of an enumerated type may be of any
valid Java identifier
- An interface may NOT contain any concrete method
implementations
- An interface is NOT a class of any style.
- An interface defines a set of abstract methods that
may have many implementations.
- An interface is NOT a member of a class.
- Both class associations and class compositions
relationship may be of any multiplicity.
- 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 bject.
- Dependency:one object uses another object during
computations.
- the portability of a Java application is NOT
dependent
- upon whether information hiding was used.
the class cannot protect bad assignments. For
example, setting a negative value for an account
balance.
- classes that do NOT support information hiding
are NOT treated specially in Java
- Disadvantages of 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.
- It is time consuming to use methods to access
object attributes rather than direct access.
- Information hiding does NOT restrict the
reusability of a superclass.
- Interfaces are only contracts (declarations of
public methods) and a program needs classes for
actual behavior.
- NOT every class will have behavior that
requires an explicit contract (interface).
- It is the reference variables to objects that
need to be as generic as possible. This is the
essence of the "program to an interface"
principle.
- An interface cannot be instantiated using the
new operator
- The minus symbol in a uml class diagram
signifies private visibility
- the + symbol in a uml class diagram signifies
public visibility
- encapsulation: all of its attributes be
private and it provides appropriate public
accessor and mutator methods.
- UML: attribute representation: - attr : int
- UML
- ? is NOT a valid multiplicity indicator.
- 0..* indicates zero or more multiplicity.
- 0..1 indicates zero or one multiplicity, which is how
you can represent an optional association.
- ?..1 is NOT a valid multiplicity indicator.
- ? 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.
- M is NOT a valid multiplicity indicator.
- Enums and arrays make use of object references
- A source file can have zero package statements or one
package statement.
- A source file automatically imports all classes of its
package.
- java -version com.example.MyProgram: The Java
interpreter prints the version information and exits.
- The Collections APIs contain interfaces for lists and
sets.
- The Collections APIs are in the java.util package.
- the classes for TCP and UDP communication are contained
in the java.net package.
- cell phone side of an application requires the micro
edition and the server side with EJB requires the
enterprise edition
- the J2SE platform has rich GUI capabilities, as well as
IP communication capabilities allowing multiple,
Internet-wide applications to exchange data.
- TCP/IP sockets are the basis of RMI.
- RMI may create new threads for each request.
- JMS is used to communicate with messaging services
asynchronously.
- HTML does NOT provide interactive capabilities.
- HTML does NOT provide a rich set of UI components.
- HTML does provide navigation capabilities, such as
hyperlinks.
- HTML does provide rich text formatting capabilities,
such as tables and cascading style sheets.
- J2me include APIs for playing audio media.
- J2ME provides limited user interface components.
- J2ME applications usually execute on small devices with
small screen resolution, which cannot support rich UI
components.
- an Applet executes within a security sandbox that, by
default, prohibits access to the user's filesystem.
- an Applet might fail to execute correctly (or at all)
if the web browser does NOT have the appropriate JRE
installed.
- an Applet does NOT have access to the web browser's
cookie information.
- the default security sandbox does permit communication
with the originating enterprise server.
- Applets execute in a security sandbox that does NOT
permit access to files on the client system.
- Applets can be used to create animated games. However,
Applets do NOT have access to gaming-specific APIs like
J2ME applications do.
- Applets cannot connect to arbitrary Internet servers.
- Applets may connect to the server that delivered the
Applet to access media files on that server.
- Applets can access other Applets on the same web page.
- Applets can access other Applets on the page through
the AppletContext object supplied by the web browser.
- Swing (Richest GUI components in j2SE) has a broader
GUI component set than AWT.
- MIDP is a J2ME (not J2SE) profile.
- JSF is a J2EE web-based UI component framework with
only a limited component set.
- AWT has a more limited GUI component set than Swing
- SWT is NOT a standard J2SE technology.
- JSP is used to create dynamic HTML content. It does NOT
handle business logic.
- JMS is the technology that handles asynchronous
requests and performs the business logic of these
requests.
- JDBC is a database communication technology and does
NOT handle business logic.
- JNDI is a naming and directory service interface. It
does NOT handle business logic.
- JNDI and JDBC support completely independent purposes
in an application. JNDI is an interface to directory
servers and JDBC is an interface to database servers.
- servlets and SQL support completely independent
purposes in an application. Servlets respond to HTTP
requests and SQL is used to communicate with relational
databases.
- JavaMail uses SMTP (simple mail transfer protocol),
which is used to send email from an application to
users.
- JavaScript and EJB support completely independent
purposes in an application. JavaScript provides
interactivity to web pages and Enterprise JavaBeans
provide business logic.
- JSP technology simplifies the creation of dynamic web
pages.
- JSP technology is a server-side technology.
- JSP technology is NOT intended to be used to create
business components.
- JSP technology is ideal for web designers who are NOT
familiar with Java programming.
- JSP technology is NOT an integration technology.
- JSP is NOT an EJB technology
- servlets are NOT an EJB technology
- MDBs do NOT record client conversational state
- stateful session beans are used to record client
conversational state
- stateless session beans do NOT record client
conversational state
- entity beans are used to represent persistent data.
- message-driven beans handle asynchronous events.
- Session beans only handle synchronous events.
- session beans represent business processes and
- stateless session beans are client-independent. That
is, they do NOT store conversational state.
- session beans do NOT exist in the web container
- stateless session beans are used to represent
client-independent business processes.
- J2EE provides a rich and flexible programming model,
but it is NOT simple
- J2EE infrastructure provides rich concurrency support
in both the web and EJB tiers, which supports highly
scalable application development.
- clustering is NOT directly supported by the J2EE
specification. However, most vendor implementations of
J2EE do support clustering.
- J2EE provides declarative transaction management.
- declarative transaction management is a required
feature of the EJB container
- declarative user interface construction - is NOT part
of the J2EE specification.
Java Rules
- Do not synchronize an instance variable or a code block without an object - it is illegal in Java
- a synchronized context: wait(), notifyAll() - may be required to be called
- Do not add a checked exception to an overridden
method
- A superclass does not have to be serializable, but its constructor will run when a serializable subclass instance is deserialized.
-
Loose coupling: you can change the implementation of a class without affecting the other classes. For example, if two classes say A and B - do not use each other at all (no instantiation of the other or no method calling ), they are not coupled. If A uses B but B does not use A, then they are loosely coupled. If both A and B use each other, then they are tightly coupled.
Loose coupling expects that a class should keep its members private and that the other class should access them
through getters and setters
Java Fundamentals
- An abstract class may have constructors
- 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
- A well-encapsulated class must have all of its attributes marked private
- A well-encapsulated class must hide all internal methods.
- NOT all attributes require accessor or mutator methods
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