Sun Certified Java Programmer (Java 2)
Basic Object Oriented Concept
Object
An Instance of a class
HAS State and Behavior
State Is Contained in ITS Member Variables
Behavior Is Implement THROUGH ITS METHODS.
Message
For Objects to Interact with One Another
Result of a message is a method invocation Which performs actions or modifies the state of the receiving object
Classes
An Object`s Class Is The Object`s Type
The Ability To Derive One Class from Another and Inherit ITS State and Behavior
Most General Classes Appear Higher In The Class Hierarchy
Most Specific Classes Appear Lower In The Class Hierarchy
Subclasses Inherit State and Behavior from Their SuperClasses
Interface
A Collection of Method Definitions WITHOUT ACTUAL IMPLEMENTATIONS
For defining a protocol of behavior what can be used by any class anywhere in the class hierarchy.
Packages
A Collection of Related Classes and interfaces
Java.lang is imported by default automaticly
Java Language Fundamentals
The Order for Every "Heading" is as Follows:
Package Declarations - package my.applications.uinterface;
Import Statements - Import Java.Awt. *
Class Definitions - Public Class Myclass {.....
Order of public vs. non-public class definitions doesn`t matter.
Allows Only One Top-Level Public Class Per Source File
Name of Source File Must Be The Same As Name of The Public Class
Main () Method Must BE:
public
Static
NOT RETURN A VALUE (Void Return Type)
Take an array of strings: (String [] args) or (string args []) DOESN`t Matter
`args` is Just A Common Name, You can Use any name you like" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
LEGAL EXAMPLES:
Public static void main (string [] args)
STATIC PUBLIC VOID MAIN (String Args []) Command Line Arguments Are Placed in The String Array Starting At 0 After Java Command and The Program Name
For Non-Applet Java Application, There Must Be a Main Method
For applet, you do not use main ()
Applet:
A Subclass of Panel, Which Itself Is A Subclass of Container
Init () - Called When Applet is first instantiated.
Start () - Called When THE Web Page Containing The applet is to be displayed
Stop () - Called When the Web Browser Is About To show another web page and quit theurrent one
HTML Required to Display An Applet In A Web Page:
Applet>
Param tag allows you to pass a value to an applet:
To use these values in your applet, use the getparameter (String paramname) Method to return the value as a string:
Greeting = GetParameter ("Message");
Java Identifier
Consists of letters and Digits
Must Begin with a letter, "$" or "_"
Unlimited Length
Cannot Be The Same as a reserved keyword
Java Reserved Word
Reserved Keywords Cover Categories Such As Primitive Types, Flow Control Statements, Access Modifiers, Class, Method, And Variable Declarations, Special Constants, And Unused Words
Abstract - Boolean - Break - Byte - Case - Catch - Caar - Class - Const - Continue - Default - Do - Double - Else - EXTENDS - FINAL - FINALLY - FLOAT - IMPORT - INSTANCEOF - INT - IMPLEMENTS - IMPORT - InstanceOf - int Interface - Long - Native - Native - NULL - Package - Private - Protected - PUBLIC - RETURN - SHORT - Static - Super - Switch - Synchronized - THIS - THROWS - TRANSIENT - TRY - VOID - VOLATILE - while
True, False and Null Are Litrals, Not Keywordsprimities
Occupy pre-defined NumBers of Bits
Have Standard Implicit Initial Values
Type Conversion
You cannot Assign Booleans to any other Type.
You cannot assign a byte to a char.
You can assign a variable of type x to type y only y contacts a wiler range of values Than X.
Primitives in Order of `Width` Are Char / Short, Int, Long, Float, Double.
For Objects, You CAN Assign Object X To Object Y Only et......................
Promotion
In Arithmetic Operations, Variable May Be Widened Automatical For the Purpose of Evaluating The Expression
The Variables Themselves Would Not Be Changed, But for ITS Calculation Java Uses A Widened Value.
Casting
Similar to Forcing a Type Conversion - Values Can Be Casted Between Different Primitive Types
Done by Placing The Destination Cast Type Keyword Between Parentheses Before The Source Type Expression
Some Cast Operations May Result in Loss of Information
Variables Derived from these Primitive Types That Are Declared In Nested Blocks Could Only Be Access In That Block and Its Sub-Blocks, And Are Destroyed When a Block The Belong To Is Stopped
Major Primitive Types:
Primitive Type
Size
Range of values
Byte
8 bit
-27 to 27-1
Short
16 bit
-215 to 215-1
Int
32 Bit, All Are Signed
-231 to 231-1
Long
64 bit
-263 to 2 63-1
Charr
16 Bit Unicode
`/ u0000` to` / uffff`
(0 to 216-1)
Java Unicode Escape Format: a "/ u" FOLLOWED by Four Hexadecimal Digits. E.G.,
Char x = `/ u1234`
Other Primitive Types:
Long - Can Be Denoted by a trailing "l" or "l"
Float - Can Be Denoted by a trailing "f" or "f" Double - Can Be Denoted by a trailing "d" or "d"
Booleans - True Or False ONLY, Cannot Be Cast to or from Other Types
Array - Declared useing the square brackets "[]". EXAMPLE OF LEGAL DECLARATIONS:
Int [] x;
INT X [];
INT i [] []; Declares A Two Dimensional Array.
Can Be create Dynamically Using the New Keyword
Can be create element list of Can BE CREATED STATIMENT LIST
Array Element Counts from 0. for EXAMPLE, INT [10] Actually Has 10 Elements, From 0 to 9, Not from 1 to 10
Array Can Be Constructed After Declaration, Or To Have Everything Done on The Single Line
Int [] i;
i = new int [10];
Oral
INT i [] = new int [10];
Array Members Can Be Initialized Either Through a for loop, or through direct assignment
Int MyArray [] = new int [10];
For (int J = 0; j MyArray [j] = j; } Oral Char mychar [] = new char [] {`a`,` e`, `I`,` o`, `u`}; Do Not get confused with string. Strings arewarebuffer classes. Bitwise Operation Numerics Can Be Manipulated At The Bit Wevel Using The Shift and Bitwise Operators Java Includes Two Separate Shift-Right Operators for Signed and UNSIGNed Operations, The ">>" And the ">>>" >> Performs a signed Right-Shift. If THEN IT RIGHT - SHIFTS The Bits, IT Fills In A 1S on The Left. if The Leftmost Bit is 0, THEN IT RIGHT-SHIFTS ......................... ...CRIPLILE, TEACE. >>> Performs An Unsigned Right-Shift. The Left Side Is Always Filled with 0s. << Performs a left-shift. The right side is always filled with 0s. Java Operator Operators That Compare Values Equal to, "==" NOT Equal to, "! =" Greater Than, ">" Less Than, "<" Greater Than or equal to, "> =" Less tour or equal to, "<=" Logical Operators Logical and, "&" Logical or, "|" Logical XOR, "^" Boolean Not, "!" Short-circuit logical and, "&&" Short-circuit logical or, "||" Operator precedence determines The ORDER OF Evaluation When Different Operators Are Used, Alth Precedence Can Be Explicitly Set with Parentheses "()". Multiple Operators of The Same Precedency Are Evaluated from Left to Right IN Logical Boolean Expressions, The Right Operand Is Only Evaluated After The Left Hand Operand Has Been Evaluated First. For short-circuit logical expression . For Example, When String x = "hey"; String y = "hey"; Java Creates Only One String Object, So The Result of Comparison Is Always True. To Avoid The Above Situation, Use The New Keyword So That String X and y can be of different Objects. In Booleans, Equals () Returns True If The Two Objects Contain The Same Boolean Value. In string, equals () returns true if the strings contain the Same sequence of character. Java modifier Private Accessible only from inside the classcannot be inherited by Subclasses protected Accessible Only by classes in The Same Package or Subclasses of this class public Can Be Accessed by Anyone Static Belongs to the class, not to any particular instance of the class For Variables, There IS Only One Copy for All Instances of The Class. If An Instances The Value, The Other Instances See That Changes For methods, it can be called without having created an instance, and can not be used the this keyword, nor be referred to instance variables and methods directly without creating an instance For inner classes, they can be instantiated without having an instance of the enclosing class Methods of the Inner Class Cannot Refer to Instance Variables or Methods of The Enclosing Class Directly Final Variable`s value cannot be changed Methods Cannot Be Overridden Classes cannot be subclassed. Native Method Written in Non Java Language Outside the JVM in a library Optimized for speed Abstract Method Which is Not Implement with code body SYNCHRONIZED Method Makes Non-Atomic Modifications to The Class or Instance For Static Method, Lock for The Class Is Acquired Before Executing The Method For Non-Static Method, a Lock for the Specific Object Instance Is Acquired TRANSIENT Field Is Not Part of The Object`s Persistent State SHOULD NOT BE Serialized Volatile Field May Be Accessed by unsynchronized threads CERTAIN CODE OPTIMIZATIONS MUST NOT BE Performed on IT None Class- Non-Public Class Is Accessible Only in ITS Package Interface - Non-Public Interface Is Accessible Only in ITS Package MEMBER - MEMBER That Is Not Private, Protected, or Public IS Accessible Only With ITS Package Summary of class member accessibilityAccessible to: Visibility public protected Package Private Same Class YES YES YES YES Different Class But Same Package YES YES YES NO Subclass in Different Package YES YES NO NO Non-subclass in Different Package YES NO NO NO Flow Control IF / ELSE IF (response == yes) { . // Code to Perform Yes Action . } else { . // Code to Perform Cancel Action . } - IF CAN Be Used without Braces - argument for if () Must Be a boolean or an expression Which Evaluates to a boolean Switch / case Switch (Month) Case 1: system.out.println ("January"); Break; System.out.println ("February"); Break; System.out.Println ("march"); break; Default: system.out.println ("hi!"); Break; } - After the correct case is executed, IT Will Continue To Execute All Those After IT Unless a Break, Return or Throw Statement for For (i = 0; i // do something.. } Uses pre-increment INSTEAD OF POST-INCREMENT. E.G. there is no difference betWeen for (int i = 0; i <5; myvar) and for (int i = 0; i <5; myvar ) While / do while Do { Statements While (BooleaneXpression); Break / Continue - Break causes the current loop to be believedoned - Affects Only The Execution of Loop That They Are IN - Labeled Versions of Break / Continue Allow You To Jump To / Break Out of Wherever the Label IS - Java Does Not Support Goto Return - Use return to exit from the current method and jump back to the statement of the calling method - To have return really return a value, put the value (or an expression that calculates the value) after the return keyword; e.g., return myvar; - The value returned must match the type of method`s declared return value - IF The Method Is Declared Void Confusions among classes, overloaded and overridden methods To DETERMINE AT Run Time if an Object is an instance of a specified class or some subclass of what class, we can use the instanceof operator. SomeObject InstanceOf SomeClass Evaluates As True if someObject is an instance of someclass, or is an instance of a subclass of someclass. SomeObject InstanceOf SomeInterface Evaluates As True IFABJECT IS An Instance of a Class Which Implements SomeInterface. To Identify A Method in Java, We Look at the name of the method and the arguments it takes. Sometimes we refer this to a method`s signature. IF The Arguments Are Different But The Method Names Are The Same, You Are DEALING WITH AN OVERLOADED METHOD. IF The Arguments and The Method Names Are The Same, You Are Dealing with An Overridden Method, That The Method of The Superclass Has Been Replaced by That of the Subclass. You cannot Define Two Methods with the Same Class with The Same Name and The Same Arguments. ................ .. The overriding method must return............ If the object is an instance of the derived class, then the overridden version defined in the derived class will be used instead of the one defined in the parent superclass.Here is how you define a CAT subclass from the superclass ANIMAL using the extends keyword: Class cat extends Animal {? .. super.someMethod () will call the version of someMethod () in the immediate super class. An attempt to use the superclass`s superclass`s method using by using super.super.someMethod () is not allowed To use this () and / or super () to access overloaded or parent-class constructors, you must place them at the very beginning of the code block in the constructor, and that you can only make one of these types of calls THIS () is buy to call any of the kether overloaded constructors defined in the class before perform performing actions specific to current constructor . If the inner class is defined inside a method, it has access to those method A non-static inner class is defined by being placed inside the class definition (for the inner class) or inside another class definition (the outer class). It has access to all member variables and methods of the containing class. An anonymous inner class is defined where it is instantiated inside a method, and is implementing an interface or extending a class without using the implements or extends keywords. Since they are anonymous, they can not have any constructor Inner x = new Inner (); is the code fragment needed to construct an instance of Inner where Inner is an inner class defined in the current class To write code to construct an instance on an inner class where either no this object exists, or. The Current this Object is not an instance of the outer class, you must create an instance of the outr Class first: Outer.inner y = new outer (). New inner (); Garbage Collection . . You can increase the likelihood of object finalization and garbage collection using the System class`s runFinalization () method which in turns will call the finalize () methods on all objects that are waiting to be garbage collected. You can also ask the garbage collector to Run by calling system`s GC () Method. Thread Control A Thread Is A Single Sequential Flow Of Control Wtem. Java Is Designed for Multi-Threaded Operations. Java Threads Are Implement by The Thread Class, Which is Part of The Java.lang Package. From The Programmer`s Perspective, Thread Class Implementation IS System Independ, Although The Actual Implementation of Concurrent Operation Is Provided by a System-Specific Implementation. The thread`s run () method is where all the operations take place. You provide the body to a Thread by subclassing the Thread class and overriding its run () method, or by creating a Thread with a Runnable object as its target. A Thread`s State INDICES What THREAD IS CURRENTLY DOING: New - Creates A New Thread But Does Not Start It, Making It Merely An Empty Thread Object with no system resources being allocated for IT .................................... NOT RunNable - A Thread Becomes "Not Runnable" State When Some INVOKES ITS SLEEP () Method / Suspend () Method, Usees Its Wait () Method to Wait On A Condition Variable, or That The Thread is Blocking On I / O. DEAD - A Thread Can Die Either from Natural Causees, Such as The Run () Method Has Completed, or Being Killed by Calling ITS Stop () Method. In Any Case, The Thread Can Never Be Restarted A Thread`s Priority Tells The Thread Scheduler WHEN THREAD CAN Be Run in Relation To Other Threads. Daemon Threads Are Threads That Provide Services for Other Threads Synchronizing Threads - if independent and concurrently running threads are sharing data or resources, they must consider the state and activities of other threads by using Object`s notify () and wait () methods to coordinate with each other You can also synchronize threads around. . A thread is put intoo a waiting state by calling the wait () method () method () method () / notifyall () Tell The Thread / All The Waiting Threads The Lock for this Object Has Become available. ERROR AND EXCEPTION All Java Methods Use The Throw Statement to Throw an Exception. The Throw Statement Requires A Single Argument: a Throwable Object. Throwable Has Two Direct Descendants: Error and Exception: Error - dynamic error or some other "hard" failure in the virtual machineException - a problem occurred but that the problem is not a serious systemic problem that you can catch and trap the problem Runtime Exceptions are exceptions that occur within the Java virtual machine during. runtime, such as NullPointerException which occurs when a method tries to access a member of an object through a null reference. Sometimes unpredictable, the compiler allows runtime exceptions to go uncaught, although you can catch these exceptions just like other exceptions. A method is not Required to Specify That throws runtimeexceptions though. Java Requires That Methods Either Catch or Specify All Checked Exceptions That Can Be Thrown Wtem An Example of Throwing An Exception: Public Object MyPopupbox () THROWS EMPTYSTACKEXCEPTION {? A popular way to handle exceptions is to place code inside a try {} block. You can create one or more catch () {} blocks after the try block with code to deal with all Different Types of Exceptions That Might Be Thrown Finally blocks execute whether the code executes without an exception, or an exception is thrown and successfully caught, or an exception is thrown and not caught. Except for code in a finally block, the execution of the remaining method is stopped if there is an exception That Is Thrown But Not Caught, or That The Exception is Not Caught Correctly. Commonly usemed methods for numeric and string ABS () - Gets The Absolute Value CEIL (Double) - Gets The Smallst Double Value That Is Not Less Than The Argument Floor (double) - Gets The Largest Double Value That Is Not Greater Than The Argument Max (Value1, Value2) - FINDS OUT The Greater Value MIN (Value1, Value2) - Finds Out The Smaller Valuerandom () - GENERATES A Random Number Between 0.0 and 1.0 Round (double) - Round to the closest long SQRT (Double) - Gets The Square Root of A Double Value Length () - Gets the string length Touppercase () - Converts String to Uppercase TOLOWERCASE () - Converts String to LowerCase EqualsignoreCase (String) - Compares The Content of Two String Objects While Ignoring The Case. Charat (int) - Returns the Character At The Specified Index Concat (string) - Concatenates the Specified String to the end of the current string Substring (int) - RETURns a new string "is a substring of the current string. Trim () - Removes All White Space from Both Ends of The String Tostring () - RETURns a string representation of the object Collection classes / Interfaces in the java.util package Set Cannot Contain Any DuPlicate Elements HAS No Explicit Order to ITS Elements Sortedset A Set Which Maintains Its Elements in Ascending Order. List A Collection Which Can Contain Duplicate Elements Elements is Ordered Stack A Subset of Vector Last-in, first-out Map Holds Keys for US to Look Up Cannot Have Duplicate Keys Standard I / O streams The Three Standard Streams Managed by The Java.lang.system Class Are: Standard Input - System.in, Typically Reads Input Entered by User. Standard Output - System.out, Typically Displays Information To The User. Standard Error - System.err, Used to Display Error Messages to The User. Input and Output Stream Java.io Package Contains The InputStream Class and The OutputStream Classes: FileInputStream and FileOutputStream - Read Data from Or Write Data To a file PipedInputStream and PipedOutputStream - implement the input and output components of a pipe that channels the output from one program or thread into the input of another.ByteArrayInputStream and ByteArrayOutputStream - read data from or write data to a byte array in memory. SequenceInputStream - Concatenate Multiple Input Streams INTO One. StringBufferInputStream - Allow Programs To Read from A StringBuffer as if it were an input stream. Java AWT Stands for Abstract Window Toolkit An Uniform Interface to Various Windowing Environments Interface between java.awt and the native windows toolkit is provided by the java.awt.toolkit class and the package java.awt.peer Framework for any GUI application is provided by the java.awt.Component class and its subclasses, that every GUI element except menus corresponds to a subclass of Component Menus subclasses the java.awt.MenuComponent class. Component Class Repensents A Gui Component That Has Size, Font, And Color Attributes, CAN RedRaw Itself and Handle Events Which Occur With IT`s Display Area. Common Methods Include: Hide () - hide the component Show () - Show the Component Disable () - Disable the component by Mostly Graying It Out Enable () - Enable a Disabled Component Repaint () - Paint The Component As Soon as Possible. Handleevent () - for you to override in Order to Provide Specific Responses To User Events Validate () - Verify That The Component Has Been CREATED AND DISPLAYS PROPERLY Container Components Belong to a subclass of the java.awt.container class Know how to add () and removeents to layout () THE VARIOUS COMPONENTS USING a LAYOUT Manager Component this is not an instance of window or a subclass must be added to a container to be visible on screenlabel Displays a line of text this cannot be edited by User List Presents a scrollable list of items identified by string names Scrollbar Mostly Automatically Generated When Required by List or TextArea Components. Orientation Specified by the constants scrollbar.horizontal and scrollbar.Vertical Five Basic Operations: Line Up, Line Down, Page Up, Page Down, and Absolute Positioning Textfield Holds a Single Line of Text In a Little Window In Which User Is Allowed to Edit Text You can set a textfield to read-only by using set-only (false) Textarea a Text Pane Containing Lines of Editable Text Event handling GUI Is Event Driven When an event occurs, the native windows toolkit first receives the event. The event is then passed to the AWT class that represents the component. The handleEvent () method of the corresponding object is then invoked. Until the Event is fully handled by some event Handler, IT Continues To Propagate Up The Container Hierarchy, Passing from Each Component To Its Parent Container. Common Event-Handler Methods Include: Mousedown () () (), mouseup (), mousemove (), mouseenter () (), mouseexit (), keydown () () () () Layout Managers WHEN You Add Components Into a Container, It is The Layout Manager of The Container Which Determines The Actual Size and Location of Each Component. All Containers Have A Default Layout Manager, But You Can Designate Which Layout Manager To Use by Passing a New Instance of The Layoutmanager To The Container`s setLayout () Method Borderlayout Possible Placements Are "North," "South," East, "" WEST, "AND" center. "Components Around The Edges Are Laid Out First and The Center Component Gets The Leftover Room Components Are Stretched Out To Meet The Edges of The Container Cardlayout Lets Several Components Occupy The Same Space Only One Component Visible At A Time User flips through the "cards" FlowLayout . Each row is centered in the parent component by default. Gridlayout Arranges Components in a Grid of Same Size Rectangular Cells Contents of Each Cell Are Resized to Fill the Cell Cells Are Populated from Left to Right in Each Row and The Down To The Next Row GridbagLayout Based on a Rectangular Array Of Cells Each Component May Occupy A Rectangular Area Covering Several Cells Each Child Component Has An Associated Gridbagconstraints Object To Give Hints To The Layout Manager About Its Minimum Size and Preferred Position In The Container.