Professional Documents
Culture Documents
Basic Concept in OOPS
Basic Concept in OOPS
• An instance of a class
• Has state and behavior State is contained in its member variables
• Behavior is implemented through its methods.
Message
Classes
Interface
Packages
• 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. However, there
must be a set of "[]"
• Legal examples:
• Command line arguments are placed in the String array starting at 0 after the java
command and the program name
Applet:
</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
abstract - boolean - break - byte - case - catch - char - class - const - continue - default -
do - double - else - extends - final - finally - float - for - goto - if - implements - import -
instanceof - int - interface - long - native - new - null - package - private - protected -
public - return - short - static - super - switch - synchronized - this - throw - throws -
transient - try - void - volatile - while
Primitives
(0 to 216-1 )
• Java unicode escape format: a "\u" followed by four hexadecimal digits. e.g.,
char x='\u1234'
• Array - declared using the square brackets "[]". Example of legal declarations :
int[] x;
int x[];
int[] i;
i = new int[10];
OR
• Array members can be initialized either through a FOR loop, or through direct
assignment
myarray[j]=j;
}
OR
• Do not get confused with string. Strings are implemented using the String and
StringBuffer classes.
Bitwise Operation
• numerics can be manipulated at the bit level 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 the first bit on the left is 1, then when it right-
shifts the bits, it fills in a 1s on the left. If the leftmost bit is 0, then when it right-
shifts the bits, it fills in a 0s on the left. The first bit represents the sign of a
number to preserve the sign of the number.
• >>> 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
Logical Operators
• Multiple operators of the same precedence 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, if the left hand condition does not evaluate to
true, the right hand condition will not be evaluated at all
• For Objects, == determines whether the variables reference the same object in
memory, rather than comparing their contents.
• 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
characters.
Java Modifiers
private
protected
public
static
• For variables, there is only one copy for all instances of the class. If an instance
changes the value, the other instances see that changes
• For methods, it can be called without having created an instance, and cannot 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
native
abstract
synchronized
transient
volatile
none
• member - member that is not private, protected, or public is accessible only within
its package
Flow Control
if/else
if (response == yes) {
...
// code to perform yes action
...
} else {
...
// code to perform Cancel action
...
}
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 you
put in a break, return or throw statement
for
while/ Do while
do {
statements
while (booleanExpression);
break/continue
- Break causes the current loop to be abandoned, while continue causes execution to skip
the rest of the code in the current iteration and start at the top of the loop with the next
iteration
- Labeled versions of break/continue allow you to jump to/break out of wherever the label
is
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, use the form of return that doesn't return a value - simply
a return with nothing but semi colon after it.
• 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 within the same class with the same name and the
same arguments.
• The return type is not part of a methods signature. Overloaded methods are
completely different methods that can return completely different types.
• The overriding method must return the same type as the method in the superclass.
• 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 { ¡K..
• 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 used to call any of the other overloaded constructors defined in the class
before performing actions specific to current constructor
• A static inner class cannot refer to instance variables and methods of the
containing class directly unless you create an instance and refer to the
variable/class in that instance.
• If the inner class is defined inside a method, it has access to those method ¡¥s
local variables that are declared final
• 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 cannot 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 outer class first: Outer.Inner y = new Outer().new Inner();
Garbage Collection
• When your program has no more references to an object, the object is finalized
and is then garbage collected automatically by Java.
• Finalization - Java runtime system gives the object a chance to clean up after itself
before it is garbage collected. This is done through a call to the object's finalize()
method.
• 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
1. 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
2. Runnable - the start() method creates the system resources necessary to run the
thread, schedules the thread to run, and calls the thread's run() method.
3. Not Runnable - a thread becomes "Not Runnable" state when someone invokes its
sleep() method / suspend() method, uses its wait() method to wait on a condition
variable, or that the thread is blocking on I/O.
4. Dead - a thread can die either from natural causes, 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 this 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 condition variable through the
use of monitors, which prevent two threads from simultaneously accessing the
same variable.
• A thread is put into a Waiting state by calling the wait() method. notify()/
notifyAll() tell the thread / all the waiting threads the lock for this object has
become available.
• Set
oCannot contain any duplicate elements
oHas no explicit order to its elements
• SortedSet
o A Set which maintains its elements in ascending order.
• List
o A collection which can contain duplicate elements
o Elements are ordered
• Stack
o A subset of Vector
o Last-in, first-out
• Map
o Holds keys for us to look up
o cannot have duplicate keys
• java.io package contains the InputStream class and the OutputStream classes:
o FileInputStream and FileOutputStream - read data from or write data to a
file
o 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.
o ByteArrayInputStream and ByteArrayOutputStream - read data from or
write data to a byte array in memory.
o SequenceInputStream - concatenate multiple input streams into one.
o StringBufferInputStream - allow programs to read from a StringBuffer as
if it were an input stream.
Java AWT
• Stands for Abstract Window Toolkit
• Container Components
o Belong to a subclass of the java.awt.Container class
o Know how to add() and remove() components to or from the container and
how to layout() the various components using a layout manager
o Component that is not an instance of Window or a subclass must be added
to a container to be visible on screen
• Label
o Displays a line of text that cannot be edited by user
• List
o Presents a scrollable list of items identified by string names
• Scrollbar
o Mostly automatically generated when required by List or TextArea
components. orientation specified by the constants
Scrollbar.HORIZONTAL and Scrollbar.VERTICAL
o Five basic operations: line up, line down, page up, page down, and
absolute positioning
• TextField
• TextArea
o a text pane containing lines of editable text
• Event Handling
o GUI is event driven
o 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:
• Layout Managers
o 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.
o 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
o Possible placements are "North," "South," "East," "West," and "Center."
o Components around the edges are laid out first and the center component
gets the leftover room
o Components are stretched out to meet the edges of the container
• CardLayout
o Lets several components occupy the same space
o Only one component visible at a time
o User flips through the "cards"
• FlowLayout
o Components are arranged left to right in a row until no more can fit in,
then a new row is begun.
o Each row is centered in the parent component by default.
• GridLayout
o Arranges components in a grid of same size rectangular cells
o Contents of each cell are resized to fill the cell
o Cells are populated from left to right in each row and then down to the
next row
• GridBagLayout
o Based on a rectangular array of cells
o Each component may occupy a rectangular area covering several cells
o 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