www.bilalahmad.20m.com ! Its My Home on Internet...


 * Home* *About Me* *Guest Book* * Games* *Tips* * Al-Islam/Pakistan*


SUN CERTIFIED JAVA PROGRAMMER

 

(COURSE SUMMARY)

 

By

 

ATIF AHMED (Hyderabadi)

 

 

AN INTRODUCTION:

 

JAVA is an innovative programming language that first of all enables us to write programs called Applets that we can embed in internet web pages. JAVA also allows to write Application.

 

The most important characteristic is to be machine independence. Java programs will run unchanged on any computer that supports JAVA.

 

Java programs are intrinsically more portable than program written in other languages.

 

Java is a platform-neutral, Object-Oriented programming language, which provides a large number of predefined library classes, which greatly simplify common programming tasks.

 

The Java 2 Platform Standard Edition has grown to 76 packages and over 2000 classes.

 

 

Object Oriented

Text Box: Java Programs
Text Box: Applets
Text Box: Applications
Text Box: Console
Text Box: Windowed Java
 

 

 

 

 

 

 

 

 

 


                Class:

A Class is a term, which describes a specification for a collection of objects with common properties. A Class is a specification or template - expressed as a piece of program code, which defines what goes to make up a particular sort of object.

 

                Sub-class:

A Sub-class is a Class that inherits all the properties of the parent class that includes extra specialization.

 

                Encapsulation:

Refers to hiding items of data and methods within an object by specifying them as private in the definition of the class.

 

                Variable:

It is a named piece of memory that you use to store information in your program.

 

                Naming & Coding Conventions:                         http://www.javasoft.com/docs/codeconv/ 

 


ACCESS MODIFIERS:

 

Public:             Specifies that the method is accessible from outside the class.

 

Static:               Specifies that the method is a class method that is to be executable, even though no class has been created. (Methods that are not Static can only be executes as a particular object of the class.

 

A Static field exists once only for the class.

 

 

 

ARRAYS:

 

-       Arrays have a length field or property not a length( ) method.

e.g. for(int j=0; j<array.length; j++);

-       Strings have length( ) method.

e.g. s.length();

-       Java does not formally support multi dimensional arrays, however it does support arrays of array, also known as nested arrays.

According to Java Language Specifications "The number of bracket pairs indicates depth of array nestings".

http://java.sun.com.docs/books/jls/html/10.doc.html#27805

 

-       Arrays are always initialized when they are created.

 

 

AWT (Abstract Window Toolkit):

 

-       The AWT automatically repaints portion of a window that require repainting as the result of window movement and resizing operation.

 

CHARACTER CODING:

 

-       UTF characters are as big as they need to be.

-       UTF è UCS Transformation Format (UCS è Universal Character Set).

-       Unicode characters are all 16 bits. It is a standard character set that was developed to accommodate the characters necessary for all languages. It uses a 16-bit code to represent a Character.

-       Full Unicode character set on internet at http://www.unicode.org

-       There is no such thing as a Bytecode character; bytecode is the format generated by the Java compiler.

-       8859_1 is common ASCII format.

 

 

COLLECTIONS:

 

-       Map does not extend Collection, List & Set do so.

-       You cannot add Primitives to Vectors.

-         Neither a Map nor a Set may have duplicate elements.

 

List:

Ordered and allow duplication.

You construct a list by calling new List (10, false).

The first parameter (10) specifies the number of visible items.

The second parameter (false) specifies whether multiple selection is supported.

A list always acquires a vertical scroll bar if the number of items exceeds the number of visible items.

A NULL value may be added to any List provided that the List is non-empty.

The GetPreferredSize( ) method returns he preferred size of a Component.

 

Map:

 

-       Unlike hashTables, hashMaps do not provides synchronized access. HashMaps only provide synchronized Access through synchronized wrappers.

-       HashMaps doesnot maintain their mappings in sorted order.

-       HashMaps handles null keys while hashTables do not.

-       When an element is put into a hashMap or a hashTable multiple times, only the last put is maintained.

-       HashMaps allow null values while hashTables do not.

 

 

 

 

 

Sets:

 

No duplication No special order. (Cannot contain duplicate items but has no special order.)

 

Q) Which would be most suitable for storing data elements that must not appear in the store more than once, if searching is not a priority?

 

Ans.) A set prohibits duplication while a list or collection does not. A map also prohibits duplication of the key entries, but maps are primarily for looking up data based on the unique key. So, in this case, we could have used a map, storing the data as the key and leaving the data part of the map empty. However, we are told that searching is not a priority, so the proper answer should be a set.

 

The Add( ) method returns false if we attempt to add an element with a duplicate value.

 

Vectors:

 

                To determine the Vector's length invoke the size method( ).

          A Vector provides synchronized addition and removal methods.

          A Vector can contain duplicate items.

A Vector does not maintain their items in sorted order.

          When a Vector is created with a given size, it can grow beyond that size.           

 

CONSTRUCTORS:

 

-       It is the code that runs automatically when a class is created.

-       Constructors have same name as the class and no return value.

-       The compiler supplies a default Constructor if no Constructors are provided for a class.

-       I you create Constructors of your own Java does not supply the default zero parameter Constructor.

-       May be public or protected.

-       Cannot be native, abstract, static, synchronized or final.

-       There is no Constructor of the "Byte" class, which takes type "int" as a parameter.

-       Constructors do not have the return type.

-         Constructors may throw Exceptions.

 

 

CONTAINERS:

 

-       The Validate( ) method ids used to cause a Container to be laid out and redisplayed.

-       The add( ) method is used to add a Component to a Container.

-       The getComponent( ) method is used to access a Component that is Contained in a Container

-       The getParent( ) method is used to access a Components container.

-       Th CheckBoxGroup class used to define radio Buttons.

 

 

DECLARATION, INITIALIZATIONS, & ACCESS CONTROL:

(Variables, Methods & Classes)

 

-       Variables in the enclosing method are only accessible if those variables are marked final.

-       A final class may not have any abstract methods. Any class with abstract methods must itself be abstract, and a class may not be both abstract and final.

-       Method arguments are allowed to be final. You see this in the context of inner classes.

-       Static initializers are executed before main( ) is executed i.e. the statements in the Static initializers will be executed (only once) when the class is first created.

-       Static variables will be initialized before non-static variables, no matter where they declared.

-       Floating-point operations do not throw exceptions.

-       By default Objects will be initialized to Null and Primitives to their corresponding default values. The same rule applies to Array of Objects and Primitives.

-       Array indices begin with 0.

-       Only one class per file can be declared public.

-       The static keyword indicates that this method can be run without creating an instance of the class.

-       The difference between Java method and methods in a non-Object Oriented Language is that the method belongs to a class.

-      Class Variables:

A Class variable must be declared using the keyword static preceding the type name.

-      Instance Variables:

A variable that is declared without using the keyword static preceding the type name.

-      Automatic Variables:

Useful for temporary manipulation of data. If you want a value to persist between Calls to a method then a variable needs to either be static or to be created at class level.

-       Static methods can only access Static variables.

-       The access hierarchy is        private Ô friendly Ô protected Ô public

-       Constants have names in Capital letters like “PI”.

-       Class level variables are always initialized to default values. In case of an int this will be “0”. Method level variables are not given default values and if you attempt to use one before it has been initialized, it will cause an error.

-       A class that contains an abstract method must itself be declared as abstract. It may however contain non-abstract methods. Any class derived from an abstract class must either define all of the abstract methods or be declared abstract itself.

-       A top-level class cannot be defined as private.

 

 

main( ) METHOD:

 

Since main( ) is defined as Static, we need to create an instance of the class in order to call any non-Static methods. Like:

 

          MyClass m = new MyClass ( );

m.amethod ( );

 

 

 

EXCEPTIONS:

 

-       Throwable is the Super class of both Error & Exception.

-         The Finally clause of a try-catch statement always executes unless its thread terminates.

 

 

EVENTS:

 

TextFields, Buttons & MenuItems generate ActionEvents but TextAreas do not.

 

ActionEvents:                  Button is pressed, List item is double clicked, Menu item is selected.

AdjustmentEvent:   Scrollbar is manipulated.

ItemEvent:             Checkbox or List item is clicked, Choice selection is made, or Checkable menu item is selected or deselected.

KeyEvent:              Keyboard.

MouseEvent:         Mouse

TextEvent:             Text area or Text field is changed.

WindowEvent:       Window.

 

 

EVENT LISTENERS:

 

-       Event Listeners are interfaces that define the methods that event-handling classes must implement.

-       An Event Adapter is a class that provides a default implementation of an Event Listener.

-       The Windows Adapter class is used to handle window-related events.

-         A Component may handle its own events by adding itself as an event handler or by overriding its event-dispatching method.

 

 

FILE I/O:

 

-       Can delete a file.

-       Return the name of the Parent directory.

-       The File class does not provide a way to change the current working directory.

-       Readers and Writers only deal with character I/O.

-       A File object can be used to access the files in the current working directory.

-       File objects are used to access files and directories on the local file system.

-       File objects can be garbage collected.

-       File does not provide any methods to change the current working directory.

-       The creation of a File object does not result in the creation of a corresponding directory of file in the local file system.

-       The Garbage collection of a File object does not normally have any effect on the local file system.

-       Constructing an instance of File does not create a file on local file system.

 

 

FONTS:

 

-         Ascent, Leading and Height are available through FontMetrics.

 

 

 

FRAME:

 

-       A newly constructed Frame has zero-by-zero size and is not visible. You have to call both setSize() (or setBounds()) and setVisible().

-         To set the Frame visible use either Show( ) or setVisible( ) methods.

 

 

GARBAGE COLLECTION:

 

-       Garbage collection cannot be forced.

-       Calling System.gc() or Runtime.gc() is not 100 percent reliable, since the garbage-collection thread might defer to a thread of higher priority.

-       It executes as a low-priority, background thread.

-       It keeps track of which Objects are reachable & unreachable.

-       I cannot be directed to garbage collect an Object.

-       The garbage collector operates in a non-determined manner. It cannot be forced to garbage collect a specific Object.

 

INNER CLASSES:

 

-       public, private, protected & static are all legal access modifiers for this inner class.

-       may extend another class.

-       A local inner class may be final or abstract.

 

Q. What modifiers may be used with an inner class that is a member of an outer class?

 

Ans.   A (non-local) inner class may be declared as public, protected, private, static, final & abstract.

 

 

INTERFACES:

 

-       Using Interfaces, you can specify what a class must do, but not how it does it.

-       Interfaces are syntactically similar to classes.

-       They lack instance variables.

-       They cannot be instantiated.

-       Their methods are declared without any body.

-       To implement an interface, a class must create the complete set of methods defines by the interface.

 

 

java.lang PACKAGE:

 

E.g.-I

1.  import java.lang.Math;

2.  Math myMath = new Math();

3.  System.out.println ("cosine of 0.123 = " + myMath.cos (0.123));

 

The constructor for the Math class is private, so it cannot be called.

The Math class methods are static, so it is never necessary to construct an instance.

The import at line 1 is not required, since all classes of the java.lang package are automatically imported.

The java.lang.Math class is final, so it cannot be subclassed.

 

Multiple inheritance is illegal in Java.

E.g.

1. class MyListener extends MouseAdapter, KeyAdapter {

2.   public void mouseClicked(MouseEvent mev) {

3.     System.out.println("Mouse clicked.");

4.   }

 

 

 

LAYOUT MANAGERS:

 

BorderLayout:

-       The default layout manager for Frame is Border.

-       Components at North and South will be the same width.

-       Components at East and West will be the same height.

-       No other generalizations are possible.

-       A component to a container that uses a Border layout manager, and you don't specify a region as a second parameter, then the component is added at Center, just as if you had specified BorderLayout.CENTER as a second parameter.

 

 

GridLayout:

 

-         The GridLayout is best if the table elements are of equal size. Other wise, use a GridBagLayout.

 

 

GridBagLayout:

 

-       The GridBagLayout lays out the Components of a Container in a grid where the size of the Component may vary.

 

GridBagConstraints:

-       The gridwidth and gridheight fields determine the size of a component's region. The region size affects the component's size, provided the component is not its preferred size.

-       The fill field determines, for each dimension, whether a component will be its preferred size or its region's size.

-       Anchor field is for controlling component placement like GridBagConstratints.NORTH

 

 

LOCKING:

 

-       Only Classes have Locks, but Primitive types do not.

 

 

 

MONITOR:

 

A monitor is an instance of any class that has synchronized code.

Key to Synchronization is the concept of the Monitor (also called SEMAPHORE).

A Monitor is an object that is used as a mutually exclusive Lock, or MUTEX.

When a thread acquires a Lock, it is said to have entered the Monitor.

The Monitor is a control mechanism, a very small box that can hold only one Thread.

Once a thread enters a Monitor, all other threads must wait until that Thread exits the Monitor.

A Monitor can be used to protect a shared asset from being manipulated by more than one thread at a time.

There is no class "Monitor"; instead, each object has its own implicit monitor that is automatically entered when one of the object's Synchronized methods is called.

Once a thread is inside a Synchronized method, no other thread can call any other Synchronized method on the same object.

When you call notify() on a monitor, you have no control over which waiting thread gets notified.

An object has only one lock, which controls access to all synchronized methods and synchronized blocks.

 

NATIVE:

 

Q. Why might we define a method as Native?

 

Ans.   To get access hardware that Java does not know.

          To write optimized code for performance in a language such as C/C++.

 

 

OPERATORS:

 

-       The result type of a ternary operator must be fully determined at compile time.

-       Using the rules of promotion for binary operands, is double. Because the result is a double, the output value is printed in a floating-point format. E.g. ((x > 4) ? 99.99 : 9));

-       Conditional operators have high Precedence than Assignment operators.

-         Java allows you to use ~ operator for integer type variables. The simple way to calculate is ~ i = ( - i ) - 1.

-       When the == operator is performed on two primitive types, numeric promotion will take place before the two values are compared.

-       % and the IEEEremainder( )       9.0%5.0 results 4.0          Math.IEEEremainder(9.0,5.0) results –1.0

 

 

 

 

OVERLOADING & OVERRIDING:

 

E.g.-I

 

1. class Fish extends Animal {

2.   public void bite(int howHard) { ...}

3. }

4.

5. class Shark extends Fish {

6.   public int bite(long howHard) { ... }

7. }

 

If the bite() method in class Shark took an int argument instead of a long, then line 6 would override the method on line 2; in that case line 6 would be illegal, because the return types would be required to match. However, int this case there is no overriding. The method in line 6 has a different argument list, so it is considered a different method, and it is allowed to have any type.

 

-       If two or more methods in the same class have same name, the method is said to be Overloaded.

-       You can have two methods in a class with the same name but they must have different parameter types and order.

-       It is the parameter order and types that distinguish between any two versions of Overloaded method.

-       The return type does not contribute towards distinguishing between methods.

-       Overloaded methods are effectively independent, and there are no constraints on the accessibility, return type, or exceptions that may be thrown.

-       Changing the parameter names is not sufficient to count as overloading.

-       To Override a method, completely replace its functionality in a subclass, the Overriding version of the method must have exactly the same signature as the version in the base class it is replacing. This includes the return type.

-       Subclasses may make their versions of overridden methods more public, but not more private.

-       The Overriding and Overridden methods must have the same name, argument list, and return type.

-       The Overriding method must not limit access more than the Overridden method.

-       The Overriding method must not throw any Exception that may not be thrown by the overridden method.

-       The Overridden cannot be more private.

-       Overridden methods cannot be more private but they can be more public or at the same level of publicness. Public visibility is more public than default or package visibility.

 

PLATFORM INDEPENDENCY:

 

Java makes no guarantees about component size from platform to platform, because it uses each platform's own fonts and component appearance. The whole point of layout managers is that you don't have to worry about platform-to-platform differences in component appearance.

 

 

SHIFTING NUMBERS:

 

E.g.-I

int k = 7 << 32003;

 

Before a shift takes place, the right-hand operand (32003) is reduced modulo the number of bits of its data type. Here the operand is an int, so the real number of positions to be shifted is not 32003 but 32003 % 32, which is 3. So the 7 operand is actually only left-shifted by 3 bit positions. This is equivalent to multiplying by 8, so the correct answer is 56.

 

 

STRING CLASS:

 

String objects are Constants. StringBuffer objects are not.

Append( ) method is not part of java.lang.String.

 

Substring( ):

                   Substring( int startIndex)

                   Substring( int startIndex, int endIndex)

                            

The startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index.

 

.equals( ) , .equalsIgnoreCase( ) , .startsWith( ) ,. endsWith( ) , .compareTo( ) , .copyValueof( )   is defined in the String Class.

 

 

E.g.-I ( Compile time error)

 

public class Conv{

public static void main(String argv[]){

Conv c=new Conv();

String s=new String("ello");

c.amethod(s);

}

 

public void amethod(String s){

Text Box: The only operator overloading offered by Java is the + sign for the String class. A char is a 16 bit integer and cannot be concatenated to a string with the + operator.
 

 

char c='H';

c+=s;

System.out.println(c);

}

}

 

 

STRINGBUFFER CLASS:

 

String objects are Constants. StringBuffer objects are not.

 

. capacity( ) , .ensureCapacity( ) , .setLength( )

 

 

TEXT:

 

The number of rows comes first, then the number of columns.

 

Q) You want to construct a text area that is 80 character-widths wide and 10 character-heights tall. What code do you use?

A) new TextArea(10,80)

 

 

 

THREADS:

 

E.g.-I

1. try {

2.   sleep(100);

3. } catch (InterruptedException e) { }

 

The thread will sleep for 100 milliseconds (more or less, given the resolution of the JVM being used). Then the thread will enter the Ready state; it will not actually run until the scheduler permits it to run.

 

PRIORITIES:

 

E.g.-II

 

 1. class HiPri extends Thread {

 2.   HiPri() {

 3.     setPriority(10);

 4.   }

 5.

 6.   public void run() {

 7.     System.out.println("Another thread starting up.");

 8.     while (true) { }

 9.   }

10.

11.   public static void main(String args[]) {

12.     HiPri hp1 = new HiPri();

13.     HiPri hp2 = new HiPri();

14.     HiPri hp3 = new HiPri();

15.     hp1.start();

16.     hp2.start();

17.     hp3.start();

18.   }

19.  }

 

A)   When the application run, thread hp1 will execute; threads hp2 and hp3 will never get the CPU.

B)   When the application run, all the threads will get to execute, taking time-sliced turns in the CPU.

C)   A is true on a preemptive platform, B is true on a time-sliced platform. The moral is that such code should be avoided, since it gives such different results on different platforms.

 

Yield ( ):

 

To call from the currently running thread to allow another thread of the same priority to run.

 

Q) A thread wants to make a second thread ineligible for execution. To do this, the first thread can call the yield ( ) method on the second thread. (T/F)

A) F. The yield() method is static and always causes the current thread to yield. In this case, ironically, it is the first thread that will yield.

 

-       A notified thread must first acquire the lock of the object on which it is waiting. Even then, it may not run immediately: it enters the Ready state, and executes at the Thread Scheduler's discretion.

-       Suspend, Resume & Stop methods are deprecated in Java2.

-       Threads enter the Waiting State when they block on I/O.

-       Thread states are Ready, Running, Waiting and Dead.

-       High-level thread states are Ready, Running, Waiting & Dead.

 

Synchronized: Ensures only one Thread at a time may access a class or object.

 

 

 

TRANSIENT:

 

-       Transient variables are not serialized.

-       Transient variables may never be static.

-       Only variables may be Transient.