Friday, January 28, 2011

Thursday, January 13, 2011

SCJP part-2 by Madhu Reddy

                                             Chapter 2: Operators and Assignments.



2.1. Increment and Decrement operation:
Increment operation:
1. Pre increment………….. ++x
2. Post increment……………x++
Decrement operation:
1. Pre decrement………………--x
2. Post decrement………………x- -


Expression        initial value of x        Final value of y      Final value of x
Y = ++X;                          5                                       6                             6
  Y = X++;                          5                                       5                             6
Y = --X;                            5                                       4                             4
Y = X--;                            5                                       5                             4


Increment and decrement operators we can not apply for constants. 
We should be apply  only for variables.
Ex: Y = X++; ………..Wright
Y = 5++ …Compile time exception
Final values can not be incremented and decremented violation leads to compile time
exception.


Floating point values can be incremented or decremented.
Q) byte a = 4;
     byte b = 6;
     byte c = a + b;
Compile time exception
Q) final byte a = 4;
      final byte b = 6;
      byte c = a + b;
No compile time exception, Output is 10
Q) byte a = 4;
     byte b = 6;
     byte c = (byte) (a + b);
No compile time exception, Output is 10


If we can apply arithmetic operator between two operands ‘a’ and ‘b’ the result is max
(int. type of a, type of b)
19
Example:
byte + byte = int
byte + short = int
short + byte = int
float + int = float
float + double = double
char + int = int


2.2. Shift operator:


The shift operator is very helpful in J2ME technology for getting
compression date and high resolution.
1) Left shift operator (<<).
2) Right shift operator (>>).
3) Unsigned right shift operator (>>>).


1) Left shift operator:
a<<n: Shift all the bits of ‘a’ n cells to the left hand side by filling right hand side
places with zero.
Hence a<<n = a*2^n …… (0 to 31)
= (n = n%32) if n>32
= (n = n+32) if n<0
Ex:
Q1) 4<<2 = 4*2^2 = 4*4 = 16
Q2) 8<<-3 = -3 + 32 = 29….. 8*2^29
Q3) 3<<33 = 33 % 32 = 1 …..3*2^1 = 6
Note: If ‘a’ and ‘b’ are compile time constants the compiler will performs the calculation
automatically. There is no type checking.
If these are not compiling time constants then compiler never calculates its value. It
should find its type by using MAX (int, type of ‘a’).
2) Right shift operator:
a>>n: Shift all the bits of ‘a’ n cells to right hand side by filling left hand side
places with sign bit.
Hence a>>n = a/2^n …… (0 to 31)
= (n = n%32) if n>=32
= (n = n+32) if n<0
20
3) Unsigned right shift operator:
Unsigned right shift operator (a>>>n): Shift all the bits of ‘a’ n cells to the right
side by filling left hand side cells with zero always.
If ‘a’ is positive there is no difference between unsigned right shift operator and right
shift operator.
If ‘a’ is +ve
a>>>n is a/2^n... the result of unsigned right shift operator is +ve.


Q) Which of the following is not a valid operator in java?
1. <<
2. >>
3. <<< no such operator in java (Ans)
4. >>>


Note: The shift operators we can not apply for floating point data types (float and
double). Violation leads to compile time exception.



2.3. Arithmetic operators:

       The float and double classes contain some constants for representing +ve and –ve
infinities. Hence 10/0.0 is not a runtime exception. We will get +ve infinity.
% and / these operators results arithmetic exception only for integral types.
System.out.println (0/0); gives run time exception.

For non integral type System.out.println (0/0.0); gives NaN (not a number).
If the result of arithmetic operation is not defined we will get arithmetic exception only
in integral data types.

But in the case of float and double classes for representing undefined values constants 
are defined which are NaN (not a number).




2.4. String concatenation operator:


       Almost all binary operators are left associative.
       Almost all unary operators are right associative.
int a = 10;
int b = 20;
string c = “abc”;
int d = 40;

a + b + c + d = 30 + c + d = 30abc + 40 = 30abc40
b + c + a + d = 20abc + a + d = 20abc10 + d = 20abc1040
c + a + b + d = abc10 + b + d = abc1020 + d = abc102040

At least one operand is the string type then only ‘+ ‘operator acts as concatenation
operator.


If both are number the ‘+ ‘operator acts as arithmetic operator.
System.out.println (" "+10+20+30+" ") gives 102030
System.out.println (10+20+30) gives 60.



2.5. Equality operators: 


        The return type of Equality operator is Boolean.
We can use Equality operator for comparing two numbers, two characters and two
object references also.

Equality operators for object references:


If s1 and s2 pointing to same object on the heap then s1==s2 returns true.
StringBuffer s3 = s2;
StringBuffer s1 = new StringBuffer (“abc”);
StringBuffer s2 = new StringBuffer (“bcd”);
S1--------------abc
S2--------------bcd--------------S3
S2==S3 gives true.
Sting s = “surya”
StringBuffer s1 = new StringBuffer (“surya”);
System.out.println(s==s1); give Compile time exception.

If we can apply == (or) ! = operator between two objects of different types then we
will get compile time exception saying incomparable objects.


2.6. Relational operators:


Return type of these operators is always Boolean.
We should apply these operators only for primitives.
10<20 give true
10<10.05f gives true
10<30<40 gives compile time exception.
For this type of expressions
First it will evaluate (10<30)<40 = true<40 this gives compile time exception like
operator can not be applied for Boolean and int.





2.7. Bitwise operator:


                                       & -----------AND
                                       | ------------ OR
                                      ^ ------------XOR


A ---------B--------- A&B--------- A|B--------- A^B
T--------- T--------- T ----------------T---------------F
T--------- F--------- F ----------------T --------------T
F--------- T--------- F ----------------T --------------T
---------F--------- F ---------------- --------------F
We can apply these operators not only for Boolean, for the integral types also.
4 & 5 ----- 4
4-- 100
&
5--101
-----------
100 --- 4
------------



~ Bitwise compliment operator: 


  We can apply these operators for integral types.
         We never use these operators for Boolean types.
Ex: ~4
4 = 000----------0100
Write opposite
111----------1011
Apply and operator for both then result is 1’s complement.
---------------------------
000----------0101 = 5
~4 is -5
Why it is in negative means the MSB (most significant bit is 1 that means
negative).
! Boolean complement operator:
! true = false
This operator can be applied only for Boolean types not for integral types.


2.8 Short circuit operators:


&&-------Short circuit AND operator
||----------Short circuit OR operator
These two operators applicable only for Boolean types.




Example:
class Temporary
{
public static void main (String args[])
{
int i = 10;
int j = 10;
if(++i<10 && ++j>15)
{
i++;
System.out.println(i);
System.out.println(j);
}
else{
j++;
System.out.println(i);
System.out.println(j);
}
}
}




O/p is :














Wednesday, January 12, 2011

SCJP Sun Certified Programmer for the Java Platform, Standard Edition 6 Exam Objectives

Section 1: Declarations, Initialization and Scoping 



  • Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).
  • Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.
  • Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.
  • Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.
  • Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class.


Section 2: Flow Control 


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


Section 3: API Contents 


  • Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.
  • Given a scenario involving navigating file systems, reading from files, writing to files, or interacting with the user, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader, BufferedWriter, File, FileReader, FileWriter, PrintWriter, and Console.
  • Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.
  • Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.


Section 4: Concurrency 


  • Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.
  • Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.
  • Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.


Section 5: OO Concepts 


  • Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.
  • Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.
  • Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.
  • Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, or overloaded constructors.
  • Develop code that implements "is-a" and/or "has-a" relationships.


Section 6: Collections / Generics 


  • Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.
  • Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.
  • Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions. Write code that uses the NavigableSet and NavigableMap interfaces.
  • Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.
  • Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting.


Section 7: Fundamentals 


  • Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.
  • Given an example of a class and a command-line, determine the expected runtime behavior.
  • Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.
  • Given a code example, recognize the point at which an object becomes eligible for garbage collection, determine what is and is not guaranteed by the garbage collection system, and recognize the behaviors of the Object.finalize() method.
  • Given the fully-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.

SCJP part-1 by Madhu Reddy

                                                           Objective


This information is useful to the person who has prior knowledge on JAVA and also who
is preparing for scjp exam.
The purpose of this document is to provide you with  important concepts with
examples. I have tried my best to cover as many points as I could in this document. So I
recommend you to go through this document at least once.



                                           Chapter 1: Language fundamentals
1. Identifiers
2. Keywords
3. Data types
4. Literals
5. Arrays
6. Un initialized variables


1.1. Identifiers
Rules of identifiers
Combination a-z ,0-9 and Symbols only _ , $.
First character should never be a digit.
There is no length limit but up to 15 digits is recommended.
Identifiers are case sensitive (Number=Number=number).
Some identifiers are reserved in java those are called Keywords.
No Keyword is allowed as identifier in java.
All predefined JAVA class names are allowed to use as identifiers.
1.2. Keywords
Some identifiers are reserved in java which is called reserved words.


1) 53 Reserved words
      1.1) 50 Keywords
           1.1.1) 48 Key words
           1.1.2) 2 Unused key words (Constant, go to)
      1.2) 3 Reserved literals  (True/false/null)



Keywords for primitive data type (8)
    byte float
    short double
    int char
    long boolean

Key words for flow control (11)
    if do
    else while
    switch return
    case break
    default continue


Keywords for Exception handling (6)

    try throw
    catch throws
    finally assert
Keywords for modifiers (11)
    public synchronized (not synchronize)
    protected volatile
    private transient
    static native
    abstract strictfp (strict floating point)
    final
Keywords related to class (6)
    class implements (not implement or implemented)
    import import (not imports)
    package extends (not extend)
    Keywords related to objects (4)
    new
    instance of (not instance Of)
    super
    this
Other keywords
    void: indicate no return type for a method
    Unused key words: goto, const
    The new keyword introduced in j2se1.5 is enum.
                      Enum: in order to define a list of name constants
                       Ex: enum month
                                 {JAN, FEB…}
All the java reserved words contain only alphabet symbols and all the symbols are in
lowercase.

1.3. Data types


                                                              Data types

                   Numeric types                               Char               Boolean(True/False)


Integral                            Floating Point


  byte                                      float
  short                                     double
  int
  long



Because of this non objects (primitive data types) java is not considered as a purely
object oriented programming language.
Primitive type                                           Wrapper class
  byte                                                                   Byte
  short                                                                 Short
  int                                                                     Integer
  long                                                                   Long
  float                                                                   Float
 double                                                               Double
 char                                                                 Character
 boolean                                                              Boolean


except boolean and char all the remaining data types are called signed data types. We
can represent both +ve and –ve numbers
byte:
Smallest integral data types
Size = 8 bits = 1 byte
If MSB is 0 = +ve
If MSB is 1 = -ve
Range is -128 to +127
Default value = 0
short:
Size = 2 bytes = 16 bits
Range -2pow (16-1) to 2pow (16-1)-1 formula [-2pow (n-1) to 2pow (n-1)-1]
This data type is very rarely used data type in java. It is best suitable for 16-bit
processor like 8086.
Default value = 0


int:
Size = 4 bytes = 32 bits
Range -2pow (32-1) to 2pow (32-1)-1
The size of the int is irrespective of the platform.
This is the most commonly used data type in java.
Default value = 0

Long:
This date type is preferable if int is not enough to hold big values like the amount of
distance travelled by light in 1000 days.
Size = 8 bytes = 64 bits
Range = -2pow (64-1) to 2pow (64-1)-1
Default value = 0


float:

Single precision = 6-7 decimal places

Size = 4 bytes = 32 bits
Range = -1.7e38 to 1.7e38
Default value = 0.0

double:
Double precision = 14-15 decimal places
Size = 8 bytes = 64 bits
Range = -3.4e308 to 3.4e308
Default value = 0.0


boolean:
Size: not applicable (virtual machine dependent)
Range: not applicable
Values true/false (not True/False)
Default value = false (not False)


char:
Size = 2 bytes = 16 bits
Range 0 to 65535
Default value = 0 (blank space)
In Unicode 0 = blank space character
12

1.4. Literals


The constant value which can be assigned for a variable is called Literal.
Integral----- [byte, short, int, long]
Integral literals------ 3 types
decimal literals---- int x = 3
octal literals 066
hexadecimal literals 0x66 [alphabets are either capital or small ]
All integral literals are by default int type.
There is no direct way to specify byte literals and short literals externally.
Floating point literals
All floating point literals are by default double values.
Byte---short—int---long----float---double
Char------------int---long----float---double
Floating point literals can not be assigning for the integral data types.
Integral literal can be assigned to the floating point literal.
Boolean literals
For the Boolean variables only the possible literals are true/false. [Not True/False].
Char literals
A char literal can be specified as a single character with in simple code.
A char literal can also be specified as an integer from 0 to 65535.
Char literal can also specify as Unicode representation. It is \u followed by 4 digit hexa
decimal number with in single codes.
Escape sequences
Escape sequences Unicode values character
\b \u0008 Back space
\t \u0009 Horizontal tab
\n \u000a new line
\r \u000d carriage return
\f \u000c form feed
\’ \u0027 single code
\” \u0022 double codes
\\ \u00jc back slash
Easy to remember big forms need red tractors.
int x = 5
Data type/keyword
Name/identifier
Value/literal
13
Instead of \n and \r we never allow using the corresponding uni codes \u000a and
\u000d even in comments also.
There is a separate meaning for that in compiler so violation leads to compile time
exception.

1.5. Arrays


1) Declare an array [ create a reference variable ]
2) How to construct an array [ creation of array object ]
3) Initialization of array [ populating array with elements ]
4) Declaration, construction and initialization in a single line
5) length Vs length()
6) Anonymous arrays
7) Array element assignments
8) Array reference assignments

1) Declare an array
An array is a data structure that defines an indexed collection of fixed number of
homogeneous date elements.
The main limitation of array is the size is fixed. I.e. once we are creating an array with
some size there is no chance of increasing or decreasing the size.
The performance of arrays is very high when compared with collections.
Ways of declaring array
int [ ] a;
int a [ ];
2-dimentional array:
int [ ] [ ] a [ ];
int [ ] a[ ],b; ----- a= two dimension, b= one dimension.
We can declare size after the type or after the name but not before the name.
int [ ] a[ ], [ ]b; ------------ wrong, this gives compile time exception.
int [ ] [ ]a, b[ ], [ ]c; ---------------- wrong
Int [ ] a;
type
dimension
Name of array
14
It is illegal to specify the size of the array at the time of declaration.
Ex: int [ ] a; is correct.
int [16] a; is wrong.
2) Constructing an array:
If we are not specifying the size of the array at the time of construction it is a
compile time exception.
Some examples:
1. int[ ] a;
a = new int[6]; ------ correct
2. int[ ] a = new int[ ];
This is wrong; it gives compile time exception because size is not specified.
3. int[ ] a = new int[-6];
Runtime exception like negative array size exception.
4. It is legal to have an array with size zero in java.
long l = 10;
int[ ] a = new int[l];
it gives compile time exception like
Found: long
Required: int
If we want to specify the size of the array with some variables
byte, short, char and int are allowed
long, float, double and Boolean are not allowed.
Assignment of arrays or populating an array with elements
Ex: int[ ][ ] a = new int[3][ ];
a[0] = new int[2];
Structure is
O/P a[0][0] = 0.
a[1] = null.
a[1][0] = null pointer exception.
null 0 null null
0 0
15
4) Declaration construction and initialization in a single line
If we are accessing an element with out of range index or negative index we will
get a runtime exception saying array index out of bounds exception.
Declaration, construction and initialization we should perform in a single line. If
we split it will give runtime exception.
int[ ] a;
a = {10, 20, 30}; it will give compile time exception.
length Vs length()
length is a final variable for an array object and length() is final method for string
objects.
length returns the size of an array and length() returns the number of characters in the
string.
Examples:
1. Every array object has final field length
int[ ] a = new int[6];
System.out.println(a.length);
O/P = 6
2. Every object has a final method called length()
String s = “Surya”
System.out.println(s.length());
O/P = 5
3. int[ ] a = new int[10]
System.out.println(a.length());
O/P = Compile time exception like unresolved symbol exception
4. int[ ] a = new int[6];
a.length; O/P = 6
a.length(); O/P = Compile time exception like unresolved symbol.
5. int[ ][ ] a = new int[3][2];
a.length; O/P = 3;
a[0].length; O/P = 2;
6) Anonymous arrays
Anonymous arrays are called name less arrays.
The purpose of these arrays is, if just in time use.
While creating anonymous arrays we are not allowed to specify the size, violation leads
to compile time exception.
Ex: new int[3] = {0, 3, 5}; O/P is Compile time exception.
16
7) Array Element assignment:
An array can access any element which can be implicitly promoted declared type.
In object arrays we can give any object as array element which is an instance of
declared class type (or) its change class instances.
8) Array reference assignments:
1. int [ ] a = new int[6];
char [ ] ch = {‘a’ , ‘c’ };
a=ch;----------------------------------Compile time exception like incompatible types.
2. int [ ]a = new int[6];
Char ch = new char[6];
int []b = a;………………correct
int [ ]b = ch;………….compile time exception.
Object array assignments:
In the case of object arrays the child array we can assign to the parent array variable.


1.6. UN initialized variables


1) Instance variables (Attributes/Member variables)
2) Static variables (Fields/class variable )
3) Local variables (Temporary/automatic/stack variable)
1) Instance variables:
The value of these variables varies from instance to instance. For every instance a
separate copy of these variables are created. These variables present as long as the
object present on the heap. These variables have to be declaring with in a class but
outside of nay method or constructor.
2) Static variables:
There is only one global copy of this variable present and shared by all instances
of that class. Hence these variables are considered as class level variables. (When ever
the class loaded into the memory static variables are created. As long as the class file is
in the JVMs memory the static variables will exist we can access a static variable by
using either object reference or class name).
3) Local variables:
The variables which are declared inside the method or inside a block are called as local
variables. The scope of this local variable is with in the method or block where the
variable declared.

Note:
In the case of instance variable and static variable if we are not performing any
initialization by default, default values will get.
The local variables never get a default values. We should perform initialization before
using a local variable.