Showing posts with label Important Notes SCJP. Show all posts
Showing posts with label Important Notes SCJP. Show all posts

Sunday, August 9, 2009

Imortant Revision Notes for Classes and Constructors in Java

Class Declaration--> Syntax of class declaration is as follows:

(class modifiers) class (class name)
               (extends clause) (implements clause)  // Class header

{ // Class body
    -- field declarations
     --method declarations
     --nested class declarations
     --nested interface declarations
     --constructor declarations
     --initializer blocks
}

Methods of a Class--> They are the class members and are also called operations. They define behaviour of the class. 

Syntax of their declaration is as follows:

(method modifiers) (return type) (method name) ((formal parameter list))
         (throws clause) // Method prototype


{ // Method body
    --local variable declarations
    --nested local class declarations
    --statements
}

Method Overloading--> This means several methods share same name but have different argument list.

Constructor--> It is a special method which is used to initialize state of an object when it is created using new operator. 

It has following syntax:

(accessibility modifier) (class name) ((formal parameter list))
            (throws clause) // Constructor header
  { // Constructor body
    --local variable declarations
    --nested local class declarations
    --statements
  }

However there are few constraints for a method to be constructor:
a) Their modifiers can be only accessibility modifiers.
b) They cannot have a return type
c) Their should be same as the class name.

Default Constructor--> It is the constructor with no argument. Its syntax is: classname()

Implicit Default Constructor-->If no constructor is defined in the class, then implicit default constructor is provided by java.

Its syntax is:

classname(){super();}

Tuesday, June 16, 2009

Java More Definations and Concepts

Types of variables



1) Instance variables--> They are non static members of a class. Every object of a class has its own copy of these variables. Their values exist as long as object containing them exists. Initialized to default valued by default.

2)Static Variables-->They belong to the class and are created when class is loaded first time at runtime.They exists as long as class exists. Initialized to default value by default.

3)Local variables-->Created in method or block and executed for method or block. After the execution of method or block, they are no more accessible. They should be explicitly initialized in a non conditional statement, before being used.


************************************


Main method--> This is the method where from execution of a program can start. It must be public, static and void. It should be public so that it can be accessed by Java Interpreter. It should be static so that It can be accessed without object of a class being created. public and static keywords can appear in any order.


************************************


Typecasting and converstions:


1) Narrowing--->Conversion of broader datatype to narrower datatype is called narrowing. It results in loss of magnitued information. This means bits from the left of the binary respresentation are truncated to fit in the destination variable. Like conversion from float to int. In this explicit cast is required.


2)Widening--->Conversion from narrower type to the broader one is called widening. In this no explicit cast is required.


*******************************************


Unary Numeric Promotion--> In a unary operator if type of operand is narrower than int, it is converted to int. It is applicable to +,-,>>,<<,>>>,~ and expressions in array initialization and array indexes. Note: not applicable to ++, -- operators.


*******************************************


Binary Numeric Promotion--> In binary numeric promotion type of the expression is promoted to the type of broadest operand which is atleast an int.


******************************************

String Concatenation-->When an operand is added to a string object using '+' sign, then any of the following cases take place:


a) If other operand is primitive datatype(int, long etc) its value is converted to the string object with string representation of its value.


b) Values like true, false and null are also converted to String objects their corresponding string respresentation. A reference variable with null value is also converted to String with string representation as "null"


c) For all other references, String is constructed by calling toString method of the referred object.


******************************************


Conditional Operators:

They are used to check the condition of an expression.


&& --> Shortcircuit AND


& --> Bitwise AND

|| --> Shortcircuit OR

| --> Bitwise OR

Difference between && and & is as given below:


In case of && if first expression is false then next condition is not checked. However in case of & if first condition is false, still next condition is checked.
! --> NOT

It  is used to invert the value of a boolean expression. true is changed to false and vice versa.

***************************************


Integer Bitwise operators:


~ Bitwise Compliment--> Inverts all bits of an operand


& Bitwise AND--> Returns 1 if both corresponding bits of two operands are 1, else returns 0.


! Bitwise OR--> Returns 0 if both corresponding bits of two operands are 0, else returns 1.


^ Bitwise Exclusivley OR--> Returns 1 if one bit of the two operands is 0 and another one is 1, else returns 0.


*******************************************


Shift Operators


a>>n--> Right shift carry sign bit


a<--> Left shift zero fill.


a>>>n--> Right shift zero fill.


*********************************************

Saturday, August 9, 2008

Serialization and Deserialization Important Tips


**For an object to be serialized, it has to implement either the java.io.Serializable or java.io.Externalizable interfaces, the latter being a subtype of Serializable.

---------------------------------------------------------------------

**Serializable is a marker interface: it specifies no methods and merely indicates an object that has serializable state.

-------------------------------------------------------------

**All subclasses of a Serializable class are also serializable.

--------------------------------------------------------------

**If a supertype of a Serializable object is not itself serializable, then the object can assume the responsibility for saving and reconstructing the supertype's state (public, protected, and package fields if they share a package).For this to work, the superclass must have a public no-arg constructor.

--------------------------------------------------------------

**Further, if an object at runtime refers to a nonserializable object, the serialization system will throw a NotSerializableException, since it cannot write the complete object graph to the serialized stream.

--------------------------------------------------------------

**If an object holds multiple references to another object, this second object is serialized only once, and subsequent references to it will include a handle as a reference instead.

---------------------------------------------------------------

**Along with instance data, the object serialization system writes a special object to the stream to represent the serializable object's class.

---------------------------------------------------------------

**This object is of the type java.io.ObjectStreamClass, and is essentially a descriptor for the Class object associated with the serializable object. It contains the class's name, its unique version number (serialVersionUID), and the class fields.

---------------------------------------------------------------

**In addition, it also has methods to obtain the actual class represented by this object, if, and only if, this class is already present in the local VM:

Class forClass() : If there is no class identified in the local VM that corresponds to this ObjectStreamClass, then a null value is returned.

------------------------------------------------------------------

**Not all objects are suitable for serialization:

1.Threads, for instance, do not have state that can later be recreated. (Actually, it is possible, but very difficult, to do so.)

2.There can also be objects that should not be serialized for semantic reasons. Even if an object is serializable, you may not need to write all object fields to the stream during serialization. For instance, a variable that loses its meaning in a different execution context (such as something indicating the current time) should be marked transient, and will instead be initialized to its default value when reading it from the stream.

----------------------------------------------------------------

**If instances of a class need a special way to serialize their state, that class can implement the Externalizable interface, which mandates two methods:
void readExternal(ObjectInput inputStream);

void writeExternal(ObjectOutput outputStream);

-------------------------------------------------------------

**The main difference between Externalizable and Serializable is that the latter serializes, by default, the entire object graph, including states of an object's superclass. While in the former Only the identity of the class of an Externalizable instance is written in the serialization stream and it is the responsibility of the class to save and restore the contents of its instances.

Externalizable gives you complete control over the serialization process.

Serialization allows you to create a JVM-independent binary representation of an in-memory Java object. This external representation may be used to transfer or store the object and to recreate it in another JVM.

--------------------------------------------------------------------

**Two streams in java.io--

1. ObjectInputStream

2. ObjectOutputStream

-- are run-of-the-mill byte streams and work like the other input and output streams. However, they are special in that they can read and write objects.

----------------------------------------------------------------

**Serializable has no methods but Externalizable has 2 methods: readExternal() and writeExternal()

----------------------------------------------------------------

You can use object serialization in the following ways:
· Remote Method Invocation (RMI) --communication between objects via sockets
· Lightweight persistence--the archival of an object for use in a later invocation of the same program.

---------------------------------------------------------------------

**Technique to protect sensitive data in classes :

Mark fields that contain sensitive data as private transient. transient and static fields are not serialized or deserialized.

Marking the field will prevent the state from appearing in the stream and from being restored during deserialization.

Since writing and reading (of private fields) cannot be superseded outside of the class, the class's transient fields are safe.

-------------------------------------------------------------

Sunday, July 6, 2008

Inner Classes

In Object Oriented programming, for reuse and flexibility/extensibility you need to keep your classes specialized.

In other words, a class should have code only for the things an object of that particular type needs to do; any other behavior should be part of another class better suited for that job.

Sometimes, though, you find yourself designing a class where you discover you need behavior that belongs in a separate, specialized class, but also needs to be intimately tied to the class you're designing.

One of the key benefits of an inner class is the "special relationship" an inner class instance shares with an instance of the outer class.

That "special relationship" gives code in the inner class access to members of the enclosing (outer) class, as if the inner class were part of the outer class.

In fact, that's exactly what it means: the inner class is a part of the outer class. Let's look at each of them.

Regular Inner Classes

A normal "regular" inner class is declared inside the curly braces of another class, but outside any method or other code block.

class MyOuter {
class MyInner { }
}

An inner class is a full-fledged member of the enclosing (outer) class, so it can be marked with an access modifier as well as the abstract or final modifiers. (Never both abstract and final together— remember that abstract must be subclassed, whereas final cannot be subclassed).

An inner class instance shares a special relationship with an instance of the enclosing class. This relationship gives the inner class access to all of the outer class's members, including those marked private.

class MyOuter {
private int x = 7;
// inner class definition
class MyInner
{ public void seeOuter()
{ // Yes you can access the private variables of enclosing class
System.out.println("Outer x is " + x);
}
} // close inner class definition
} // close outer class

To instantiate an inner class, you must have a reference to an instance of the outer class to tie to the inner class.

An inner class instance can never stand alone without a direct relationship to an instance of the outer class.

From code within the enclosing class, you can instantiate the inner class using only the name of the inner class, as follows:

MyInner mi = new MyInner();

From code outside the enclosing class's instance methods, you can instantiate the inner class only by using both the inner and outer class names, and a reference to the outer class as follows:

MyOuter mo = new Myouter();
MyOuter.MyInner inner = mo.new MyInner();

or

MyOuter.MyInner inner = new MyOuter().new MyInner();

From code within the inner class, the keyword this holds a reference to the inner class instance.

To reference the outer this (in other words, the instance of the outer class that this inner instance is tied to) precede the keyword this with the outer class name as follows:

MyOuter.this;

Method Local Inner Classes

A method-local inner class is defined within a method of the enclosing class.

class MyOuter2 {
private String x = "Outer2";
void doStuff() {
class MyInner {
public void seeOuter()
{ System.out.println("Outer x is " + x);
} // close inner class method
} // close inner class definition }
// close outer class method doStuff()
} // close outer class

For the inner class(Method - Local Inner Class) to be used, you must instantiate it, and that instantiation must happen within the same method, but after the class definition code.

class MyOuter2 {
private String x = "Outer2";
void doStuff() {
class MyInner {
public void seeOuter() {
System.out.println("Outer x is " + x);
} // close inner class method
} // close inner class definition
MyInner mi = new MyInner(); // This line must come
// after the class
mi.seeOuter();
} // close outer class method doStuff()
} // close outer class

In other words, no other code running in any other method—inside or outside the outer class—can ever instantiate the method-local inner class.

Like regular inner class objects, the method-local inner class object shares a special relationship with the enclosing (outer) class object, and can access its private (or any other) members.

However, the inner class object cannot use the local variables of the method the inner class is in unless those variables are marked final.This is bcoz the local variables of the method live on the stack, and exist only for the lifetime of the method.

You already know that the scope of a local variable is limited to the method the variable is declared in. When the method ends, the stack frame is blown away and the variable is history. But even after the method completes, the inner class object created within it might still be alive on the heap if, for example, a reference to it was passed into some other code and then stored in an instance variable.

Because the local variables aren't guaranteed to be alive as long as the method-local inner class object, the inner class object can't use them. Unless the local variables are marked final! The only modifiers you can apply to a method-local inner class are abstract and final. (Never both at the same time, though.)

A local class declared in a static method has access to only static members of the enclosing class, since there is no associated instance of the enclosing class. If you're in a static method there is no this, so an inner class in a static method is subject to the same restrictions as the static method. In other words, no access to instance variables.

Anonymous Inner Classes

Anonymous inner classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface.

Type - 1 (Subclass of the named type)

class Popcorn {
public void pop() {
System.out.println("popcorn");
}
}class Food {
Popcorn p = new Popcorn()
{
public void pop() {
System.out.println("anonymous popcorn");
}
};
}
Polymorphism is in play when anonymous inner classes are involved. You can only call methods on an anonymous inner class reference that are defined in the reference variable type!

This is no different from any other polymorphic references, for example,

class Horse extends Animal{
void buck() { }
}
class Animal {
void eat() { }
}
class Test {
public static void main (String[] args)
{
Animal h = new Horse();
h.eat(); // Legal, class Animal has an eat() method
h.buck(); // Not legal! Class Animal doesn't have buck()
}
}

Type - 2 (Implementer of the specified interface type)

interface Cookable {
public void cook();
}
class Food {
Cookable c = new Cookable()
{ public void cook()
{ System.out.println("anonymous cookable implementer");
}
};
}
Anonymous interface implementers can implement only one interface.

Type - 3 (Argument defined anonymous inner classes)

class MyWonderfulClass {
void go() {
Bar b = new Bar();
b.doStuff(new Foo() {
public void foof() { System.out.println("foofy");
} // end foof method
}); // end inner class def, arg, and b.doStuff stmt.
} // end go()
} // end class
interface Foo {
void foof();
}
class Bar {
void doStuff(Foo f) {}
}
An argument-local inner class is declared, defined, and automatically instantiated as part of a method invocation.
The key to remember is that the class is being defined within a method argument, so the syntax will end the class definition with a curly brace, followed by a closing parenthesis to end the method call, followed by a semicolon to end the statement: });

An anonymous inner class is always created as part of a statement; don't forget to close the statement after the class definition with a curly brace.

This is a rare case in Java, a curly brace followed by a semicolon.Because of polymorphism, the only methods you can call on an anonymous inner class reference are those defined in the reference variable class (or interface), even though the anonymous class is really a subclass or implementer of the reference variable type.

An anonymous inner class can extend one subclass(type-1) or implement one interface(type-2), Unlike non-anonymous classes (inner or otherwise), an anonymous inner class cannot do both. In other words, it cannot both extend a class and implement an interface, nor can it implement more than one interface.

Static Nested Classes

Static nested classes are inner classes marked with the static modifier.

class BigOuter {
static class Nested { }
}

A static nested class is not an inner class, it's a top-level nested class.The class itself isn't really "static"; there's no such thing as a static class. The static modifier in this case says that the nested class is a static member of the outer class.

That means it can be accessed, as with other static members, without having an instance of the outer class. Because the nested class is static, it does not share any special relationship with an instance of the outer class.

In fact, you don't need an instance of the outer class to instantiate a static nested class.Instantiating a static nested class requires using both the outer and nested class names as follows:

BigOuter.Nested n = new BigOuter.Nested();

Example :

class BigOuter {
static class Nest {void go()
( System.out.println("hi");
}
}
}
class Broom {
static class B2 {void goB2() {
System.out.println("hi 2");
}
}
public static void main(String[] args) {
BigOuter.Nest n = new BigOuter.Nest(); // both class names
n.go();
B2 b2 = new B2(); // access the enclosed class
b2.goB2();
}
}

Which produces:
hihi 2

Just as a static method does not have access to the instance variables and non-static methods of the class, a static nested class does not have access to the instance variables and non-static methods of the outer class.

Look for static nested classes with code that behaves like a nonstatic (regular inner) class.

Thursday, April 3, 2008

LAST MINUTE REVISION POINTS

1. Evaluation and execution –remember that evaluation is from left to right but
execution is from right to left.

2. There must be some statement after do keyword in do – while loop for it to
compile without error.
i.e.
do ; while(false); //correct
do {;}while(false); //correct
do {}while(false); //correct
do while(false); //error

3. If “t” is a reference variable then ,
t.equals(null) is
false
(null).equals(t) compiler error
let’s say t2 is some other reference variable then
t.equals(t2)
false and not error
consider,
t = null;
t.equals(t2); //not compiler error but runtime error

4. If a class is declared inside a package with public modifier then that class
becomes invisible to all other classes in other packages unless they import the
package or use extended form of addressing the class.

5. The Iterator method of collection interface when invoked returns an instance of
Iterator class.

6. given,
char c = ‘a’;
int i = 1;
c + =i; //correct
c = c+ i; //illegal

7. when use int numbers in basic arithmetic operation then the output is an integer
number. Hence ,
int i = 4/3;
“i” will have the value 1.

8. Native methods can be set to any access level - public , protected, private, default.

9. The methods in the immediate super class in the inheritance tree may be accessed
through the use of keyword “super” , but classes above the immediate super class
are not visible.

10.
Valid comments
· /* this is a comment */
· /** this is a comment */
· /*this is a comment **/
· // /** this is a comment */ */
Important:-
· /* //this is a comment */
11. invalid comments
· /** this is a comment */ */

12. If a method declares some exception in throws clause and the subclass of the
given class while overriding the method declares some new exception then before
assuming that it causes compiler error first check whether the new exception
thrown in the subclass’ method is unchecked exception or not.

13. After solving the logic inside the problem before jumping to conclusion check
whether some code is unreachable or not. Because if it happens so then it results
in compiler error.

14. The following form of instantiating a static inner class results in compiler error,
new ().new ();

15. long l = Integer.MAX_VALUE;
float f = l;
double d = l;
then “d==f” is false due to rounding of numbers in float literal.
But when we assign l to Long.MAX_VALUE or to Integer.MIN_VALUE then
we get the result of “d==f” as true.

16. We can place label statements around a block of code wherever we wish , unless
the name used is not a keyword and follows all the rules meant for identifier.
For eg.
labelA:
{
…..some complex code….
…..some complex code….
if(someThingIsTrue)
{
break labelA;
}
}
this way we place break statement with label in any labeled block of code
which may break out of the code if something comes true.
Furthur the same labels can be used for other block of code as long as they
don’t overlap.

17. An abstract method cannot be marked as both
· Abstract and strictfp
· Abstract and native
· Abstract and synchronized
· Abstract and final
· Abstract and private
· Abstract and static

18. Shift operators can be used only on integers .

19. Switch statements can evaluate byte , short, char , int.
but not long, float.double.
i.e. long l = 10;
switch(l){}//causes compiler error
before jumping to conclusion about switch statements , verify whether
the case arguments are lying within the range of the switch argument.
For e.g. byte b = 10;
Switch(b)
{
case 10: …….. complexcode………break;
case 1000: …….. complexcode………break;
}
here second case statement causes compiler error since it is out of range of
byte literal.

20. The case argument must be primitive literal type or final variable.

21. For loop declarations,
valid
· for(int i=0,j=0;i<10;i++);invalid
· for(i=0,int j=0;;);
· int k =1;
for(int i=0,k=0;;);

Search Amazon for Best Books on Java J2EE

Blogarama

blogarama - the blog directory

Search your favourite topics

Google