Showing posts with label sun certified java programmer exam. Show all posts
Showing posts with label sun certified java programmer exam. Show all posts

Sunday, July 13, 2008

SCJP Exam - Objective 1.3 Part II

Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.

Arrays are objects in Java that store multiple variables of the same type. Arrays can hold either primitives or object references, but the array itself will always be an object on the heap, even if the array is declared to hold primitive elements. In other words, there is no such thing as a primitive array, but you can make an array of primitives.

There are three things, what you should know about array:
  1. declaring array
  2. constructing array
  3. initializing array

Declaring arrays
Arrays are declared by stating the type of element the array will hold, which can be an object or a primitive, followed by square brackets to the left or right of the identifier.

Declaring array of primitives
Declaration of an array of primitives looks like this:
<primitive type>[] <identifier>;

for example:
int[] integer_array;

There is another way to declare arrays (like in language C):
<primitive type> <identifier>[];

for example:
int anotherArray[];
Declaring array of objects
Declaration of array of objects:
<classname>[] <identifier>;

for example:
String[] stringArray;
Array of object can be declared as in language C too.

Declaring multidimensional arrays
Java let you to declare multidimensional arrays. Multidimensional arrays are arrays of arrays.
A two dimensional array declaration:
String[][] twoDimensionalArray;

The
String[][] threeDimensionalArray[];

declaration is interesting, but legal.

Constructing arrays
Constructing an array means creating the array object on the heap. To create an array object, Java must know how much space to allocate on the heap, so user must specify the size of the array at creation time. The size of the array is the number of elements the array will hold.

Examples
int[] intArray; //Declare an one-dimensional array
intArray = new int[3]; //Construct an int array to hold 3 int value
long longArray = new long[1]; //Declare and construct a long array with one element


Constructing multidimensional array
Remember, multidimensional arrays are simply arrays of arrays. It means, elements of multidimensional arrays are arrays.
The
int[][] array = new int[2][];

means we declare and construct a two-dimensional integer array and the size of the first dimension will be 2. When we initialize the array then we can put int array as elements with different size into the array.
The
int otherArray = new int[3][2];

means we declare and construct a two-dimensional integer array and the size of the first dimension will be 3 and declare and construct three one-dimension array with length 2 and put them into the array.

Initializing arrays
Initializing an array means putting things (primitives, object references) into it:
int[] a = new int[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
int b[] = new int[2];
b[0] = 8;
b[1] = 9;
int[][] c;
c = new int[2][];
c[0] = a;
c[1] =b;
String[] s = new String[3];
s[0] = "hello";
s[1] = null; //null can be use as string element
s[2] = new String("World");

Notice, array indexes begin with 0 and go to size-1. If we try refer to an index that not exist (for example a negative number, or a number greater then size-1) then ArrayIndexOutOfBoundsException trowed.

Declaring, constructing and initializing arrays
It's possible to declare, construct and initialize array in the same time:
int[] a = { 5, 6, 7 };
String lenovo = new String("Lenovo");
String[] computerProducers = { "Dell", lenovo, "HP", "Apple" };

Anonymous array creation
Anonymous array creation can be used to construct and initialize an array, and then assign the array to a previously declared array reference variable:
String[] operatingSystems;
operatingSystems = new String[] { "Windows XP", "Windows Vista", "OpenSuSE 10.3" };

Multidimensional array creation
Multidimensional array creation looks like this:
int[][] array = { { 1, 2, 3 }, { 10, 11 }, { 0 } };

Declare, initialize and uses arrays, enums, objects as static, instance and local variables
Example code:

You can download source code here.

Friday, July 4, 2008

SCJP Exam - Objective 1.3 Part I

Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.

Legal identifiers
Technically, legal identifiers must be composed of only Unicode characters, numbers, currency symbols, and connecting characters (like underscores).
  • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ).
  • Identifiers cannot start with a number!
  • After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
  • There is no limit to the number of characters an identifier can contain.
  • Java keywords can't be used as identifier.
  • Identifiers in Java are case-sensitive.

Java keywords

abstractassertbooleanbreak
bytecasecatchchar
classconstcontinuedefault
dodoubleelseenum
extendsfinalfinallyfloat
forgotoifimplements
importinstanceofintinterface
longnativenewpackage
privateprotectedpublicreturn
shortstaticstrictfpsuper
switchsynchronizedthisthrow
throwstransienttryvoid
volatilewhile


Static variables
  • static variables belong to the class, not the instance
  • static variables can be public, protected, default and private
  • static variables can accessed through class reference
  • access static variables through instance variables is legal, but not a good idea
  • static variables get their default value at declaration
  • static variables declared when the class loader load their class
  • static variables live as long as their class lives
  • static variables can declared and initialized at the same time, except when the initialization can throw exception, in this case use static initialization block:
//Required imports here
...
class ThisClassUseStream {
//Compilation fails, because FileInputStream constructor can throw exception.
static InputStream stream = new FileInputStream("filename");

//Works well, otherStream declared and initialized as null.
static InputStream otherStream;

//static initialization block
static {
try {
otherStream = new FileInputStream("filename");
} catch( Exception ex } { ... }
}
}
  • static initialization block execute top-down
  • static variables are not inherited
  • static variables cannot be serialized

Instance variables
  • instance variables belong to an object instance
  • instance variables can be accessed only through an instance
  • instance variables can be accessed from somewhere in their instance
  • instance variables can be public, protected, default and private
  • instance variable can be inherited
  • private variables are not inherited
  • variables with default visibility are not inherited
  • instance variables are created when the constructor is called
  • instance variable get their default values at declaration

Local variables
  • local variables are created inside a method body
  • local variables live as long as their method is running
  • local variables can be accessed only the method where they was declared
  • local variables don't have default values
  • local variables can be marked only as final

Variables - default values
  • boolean variables: false
  • byte variables: 0
  • char variables: '\u0000'
  • double variables: 0.0D
  • float variables: 0.0F
  • int variables: 0
  • long variables: 0L
  • object references: null
  • short variables: 0
Do not forget, only static and instance variables have default values!

Declare, initialize, use primitives as static, instance and local variable
The Java programming language is strongly-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen:
int a = 5;
Primitive types
There are 8 primitive type in java:
  • boolean data type has only two possible values: true and false.
  • byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
  • char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
  • double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values isn't important.
  • float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values isn't important.
  • int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
  • long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).
  • short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).
Default values of data types are showed above.

Primitive and string literals

Integer literals

There are three ways to represent integer numbers in the Java language:
  • decimal (base 10)
  • octal (base 8)
  • hexadecimal (base 16)

Decimal literals
Decimal representation is the most common in Java, for example:
int a = 1;
long l = 5L;
byte b = 0;
short s = 8;

Octal literals
  • octal literals use only the digits 0 to 7
  • octal literals always begin with 0
  • octal literals can up to 21 digits in an octal number, not including the leading zero
So don't forget,
o77 != 77

because 077 is the octal representation of number 63.
  • some octal literals:
int a = 07 //equals decimal 7
int b = 08 //compilation fails, 8 digit not allowed
int c= 01234 equals decimal 668


Hexadecimal literals
  • hexadecimal numbers are constructed using 16 distinct symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A (or a), B (or b), C (or c), D (or d), E (or e) , F (or f)
  • hexadecimal literals always begin with 0x or 0X
  • hexadecimal numbers can be up to 16, not including the prefix Ox
Floating-point literals
  • floating point literals include the decimal point (.)
  • the left side of decimal point is the integer part
  • the right side of decimal point is the fraction part
  • one of the integer or the fraction part must be declared
  • legal declaration and initialization:
double d1 = .1;
double d2 = 1.;
double d3 = 1.d;
double d4 = .3D;
double _____________ = -.66d;
float f1 = 9.66f;

  • not legal declaration and initialization:
double d3 = .;
float f1 = 0.0;
Boolean literals
  • there are two boolean literals: true and false
Character literals
  • character literals can declared between two single quotes
  • character literals can declared as number
  • legal character literals:
char c1 = 'a';
char c2 = '\u00ff';
char c3 = 32;
char c4 = 04;
char c5 = 0xf;
String literals
  • string literals are declared between two double quote
  • string literal declaration:
String s = "Hello World";
Declaration Example

You can download source code here.

Casting primitives
Casts can be implicit or explicit. An implicit cast means you don't have to write code for the cast; the conversion happens automatically. Typically, an implicit cast happens when you're doing a widening conversion.

Implicit cast
byte b = 5;
int i = b;

Int type is bigger the byte, implicit cast work.

Explicit cast
We need use explicit cast, if we want to assign a bigger value to a smaller type. It can cause loss of procession so explicit cast is required.
Explicit cast look like this:
int a = (int) 5.5; //5.5 is a double, it must be cast to int
byte b = (byte) 128; //128 is too big to store in a byte
byte c = 100;

Tuesday, July 1, 2008

SCJP Exam - Objective 1.2

Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.

Interface declaration
This is discussed in Objective 1.1 - Interface declaration.

Do not forget, what is in the Objective 1.1 written about interface declarations.

Extend an interface
  • an interface can extend one or more other interfaces

  • an interface cannot extend anything but another interface


Abstract class declaration
abstract class <ClassName> {
//...
}

You can read more about abstract classes in Objective 1.1 - Non-access modifier: abstract.

Extend an abstract class
  • a class can extend only one class (no multiple inheritance)
  • abstract class can extend concrete and abstract classes


Example for interface declaration, interface implementation, abstract class declaration, abstract class extension:

You can download source code here.

Sunday, June 29, 2008

SCJP Exam - Objective 1.1

Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).

Java Source File
Sample Java source file:



You can download source code here.
  1. If the class is part of a package, the package statement must be the first in the source code file.
  2. The import statements must be after the package statement (if there is one) and must be before the class declaration.
  3. There can be only one public class per source code file.
  4. If there is a public class in a file, the name of the file must match the name of the public class.
  5. A source file can have more than one nonpublic class.
  6. Files with no public classes can have a name that does not match any of the classes in the file.
Static import

The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually:

import static java.lang.Math.PI;
or:
import static java.lang.Math.*;
Once the static members have been imported, they may be used without qualification:
double r = cos(PI * theta);
The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.

Class declaration
Class declaration looks like this:
<Class modifier> class <ClassName> {
//...
}
Modifiers
Access modifiers
  1. A class can be declared as public and default access.
  2. A class never can be declared as private or protected, except the inner classes.
Non-access modifiers
  1. abstract
  2. final
  3. strictfp

Non-access modifier: abstract
An abstract class can never be instantiated. If you try it, you get Compilation fails. The abstract classes are to extend them.

If we have some classes with the same methods, but some method implementation are different then abstract class is a perfect choice:
Make an abstract class, write the methods, that will be same in the subclasses.
Mark the methods, that will have different implementations as abstract. Abstract methods end in a semicolon rather than curly braces.

Example for abstract class and its concrete classes:

You can download source code here.


Non-access modifier: final
When used in a class declaration, the final keyword means the class can't be subclassed. In other words, no other class can ever extend a final class, and any attempts to do so will give you a compiler error.

Many classes in the Java core libraries are final. For example, the string class. So notice, you never ever can extend the String class.

Example for final class and the Compilation fails when try to extend the class, marked final:

You can download source code here.


Non-access modifier: strictfp
Marking a class as strictfp means that any method code in the class will conform to the IEEE 754 standard rules for floating points. Without that modifier, floating points used in the methods might behave in a platform-dependent way.

Notice,
  • an abstract class never ever can be instantiated
  • abstract class can have constructor and it can be called from subclasses constructors trough super()
  • a final class never ever can be extended
  • a class never ever can be marked as both abstract and final
Declaring nested classes
The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here:
class OuterClass {
//...
class NestedClass {
//...
}
}
Type of nested classes:
  1. static nested class
  2. inner (non-static) class
  3. local class
  4. anonymous class
Static nested class
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
Inner class
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {
//...
class InnerClass {
//...
}
}

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Local inner class
You can declare an inner class within the body of a method. Such a class is known as a local inner class:
class OuterClass {
public void someMethod() {
class InnerClass {
//..
}
}
}
Notice,
  1. a local inner class can be instantiated only within the method where the inner class is defined
  2. a local inner class can not access to the method's local variables
  3. a local inner class can access to the method's local variables, marked as final

Anonymous class
Anonymous classes extends an exists class or implements an interface, with creating a new class without name:
class Tree {
public void grow() {
//Some tree specific code
}
}

interface Door {
void closeDoor();
}

public class MyClass {
public void doStuff() {
Tree oak = new Tree {
public void grow() {
//Some oakvspecific code
}
}

Door door = new Door {
public void closeDoor() {
//Close door method
}
}
}
}



Interface declaration

Interface declaration looks like this:
<Class modifier> interface <InterfaceName> {
//...
}
Notice,
  • all interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract
  • all variables defined in an interface must be public, static, and final—in other words, interfaces can declare only constants, not instance variables

  • interface methods must not be static

  • because interface methods are abstract, they cannot be marked final, strictfp, or native

  • an interface can extend one or more other interfaces

  • an interface cannot extend anything but another interface

  • an interface cannot implement another interface or class

  • an interface must be declared with the keyword interface

  • interface types can be used polymorphically

Puzzle 1
Given the following code:
interface Tree {
void grow();
}

public class Oak implements Tree {
void grow() {
//Some oak specific code here...
}
}
What is the result?
The result is: the code does not compile, it causes Compilation fails, because methods in interface declaration are implicitly public and the accession of grow() method in Oak class is default.

Puzzle 2
Given the following code:
interface MyInterface {
int x = 67;
}

class MyClass implements MyInterface {
public void setter() {
x = 100;
}
}
What is the result?
The result is: the code does not compile, it causes Compilation fails, because variables, declared in interfaces are implicitly final and static, and you can not assign a new value to a final variable.

Declaring Enums
Using enums can help reduce the bugs in your code.

Example for declaring enumerations:

You can download source code here.

Friday, June 27, 2008

SCJP Exam - Introduction

Sun Certified Programmer for the Java Platform, Standard Edition 6 (CX-310-065)
As I promised, I begin my series about the Sun Certified Java Programmer Exam. In my first post I write about the exam and the objectives. The next SCJP posts review the interesting and the dodgy part of the required knowledge to exam.



Exam objectives - What should I know?
Source: http://www.sun.com/training/catalog/courses/CX-310-065.xml

Sun divides the objectives to seven sections:

Section 1: Declarations, Initialization and Scoping

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

Section 3: API Contents
  • Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.
  • Given a scenario involving navigating file systems, reading from files, writing to files, or interacting with the user, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader, BufferedWriter, File, FileReader, FileWriter, PrintWriter, and Console.
  • Develop code that serializes and/or de-serializes objects using the following APIs from java.io: DataInputStream, DataOutputStream, FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream and Serializable.
  • Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.
  • Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.
Section 4: Concurrency
  • Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.
  • Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.
  • Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.
  • Given a scenario, write code that makes appropriate use of wait, notify, or notifyAll.
Section 5: OO Concepts
  • Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.
  • Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.
  • Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.
  • Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, or overloaded constructors.
  • Develop code that implements "is-a" and/or "has-a" relationships.
Section 6: Collections / Generics
  • Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.
  • Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.
  • Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions. Write code that uses the NavigableSet and NavigableMap interfaces.
  • Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.
  • Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting.
Section 7: Fundamentals
  • Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.
  • Given an example of a class and a command-line, determine the expected runtime behavior.
  • Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.
  • Given a code example, recognize the point at which an object becomes eligible for garbage collection, determine what is and is not guaranteed by the garbage collection system, and recognize the behaviors of the Object.finalize() method.
  • Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.
  • Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.
About the exam
Other exams/assignments required for this certification: None
Exam type: Multiple choice and drag and drop
Number of questions: 72
Pass score: 65% (47 of 72 questions)
Time limit: 210 minutes