By N Michael
Numeric Literals are are used to indicate Octal Hexadecimal values
Value | Means | |
0X | 0H | Hexadecimal |
012 | AH | Octal |
0777 | FFH | Octal |
Character Literals are are used to insert special characters into Strings
\n | New line |
\b | Backspace |
\r | Carrage return |
\t | Tab |
\f | Form feed |
\\ | Back slash |
\ | Single quote |
\" | Double quote |
\ddd | Octal |
\xdd | Hex |
\udddd | Unicode |
Integer | byte | |
short | ||
int | ||
long | ||
Floating Point | float | |
double | ||
Boolean | boolean | |
character | char | |
IEEE754 floating point Specification
strictfp
== | Is equal |
!= | Not equal |
> | Greater than |
< | Smaller than |
<= | Smaller equal |
>= | Greater equal |
Top of Page
& | And |
| | Or |
^ | Xor |
<< | Shift left |
>>> | Shift right |
~ | Zero fill shift right |
&& | And Short Circuit operator (drop out on first false) |
= | |
+= | Plus and assign |
-= | Minus and assign |
/= | divide and assign |
*= | multiply and assign |
%= | Modulus and assign |
^= | Xor and assign |
&= | And and assign |
|= | Or and assign |
<<= | Shift left and assign |
>>= | Shift right and assign |
>>>= | Zero fill shift right and assign |
= ++X | Prefix increment opperator X is incremented before assignment |
= x++ | Postfix increment opperator X is incremented after assignment |
= --X | Prefix decrement opperator X is incremented before assignment |
= x-- | Postfix decrement opperator X is incremented after assignment |
IF Else
if (expression)
{
some_code_to_execute
}
else if (expression)
{
some_code_to_execute
}
else
{
some_code_to_execute
}
The nested If
if (expression1)
{
if (expression2)
{
some_code_to_execute
}
}
Conditional (Tenary) Opperator
myVariable=(BooleanExpression)?TrueReturnExpression:FalseReturnExpression;
The Switch statement
switch (expression)
{
case ConditionalValue1:
some_code_to_execute
break; // Leave loop (You must put a break for each Case)
case ConditionalValue2:
some_code_to_execute
break; // Leave loop (You must put a break for each Case)
default:
some_code_to_execute
break; // Leave loop (You must put a break for each Case)
}
The For Loop
for (initialExpression;testCondition;iterationExpression)
{
some_code_to_execute
}
The Nested For Loop
for (initialExpression1;testCondition1;iterationExpression1)
{
for
(initialExpression2;testCondition2;iterationExpression2)
{
some_code_to_execute
}
}
The While Loop
while (loopconditionExpression)
{
some_code_to_execute
}
Do while Loop
do
{
some_code_to_execute
} while (loopconditionExpression)
Loops Breaking and continuing
[looptype]
{
some_code_to_execute;
continue // resume executing at
top (forcing the next loop iteration)
some_code_to_execute;
continue Here // resume executing
at label HERE
some_code_to_execute;
break; // Leave loop
some_code_to_execute
break Here // Leave and continue
executing at label HERE
some_code_to_execute
Here: // label HERE
some_code_to_execute
}
8 ARRAYS
Are ordered collections of objects.Objects such as Variables or even Strings or even other
arrays
Of the same type
Method1
Step 1 Declare Array
Int [ ] numbers; // Declaring an array Java Style
Int numbers [ ] // Declaring an array C++ style
Step 2 Define Array
Numbers = new int [5];
Method 2
Int [ ] Numbers= new int [5]; // combinding the above
Method 3
Int [ ] Numbers={4,6,7,11,14,2,22}; // giving an array initial values
Or
Int [ ] numbers= new int[5];
Numbers[4]=23;
Numbers[3]=32;
Creating Array Variables
String [] diffucultWords;
int [] itemsPurchased;
Multidimentional Arrays
int coords [][] = new int[12][15];
coords [0][1]=21;
coords[1][4]=36;
Creating Array Objects
When you use the new keyword all the arrayelementss are automatically initialized
int is initialized to 0
9 Formated Printing (Floating Point)
format.applyPattern(printPattern)
0 print a digit or a zero to pad space
# print a digit or a space
. Set
the decimal point position
NumberFormat.setMinimumIntegerDigits(5);
NumberFormat.setMaximumIntegerDigits(9);
Format | Value | Printout |
0.00 | 6.456 | 006.46 |
#.## | 6.456 | 6.46 |
###.0 | 6.456 | 6.5 |
unformatted | 6.0 | 6.0 |
0.00 | 6.0 | 006.00 |
#.## | 6.0 | 6 |
###.0 | 6.0 | 6.0 |
unformatted | 6564 | 6564.0 |
0.00 | 6564 | 6564.00 |
#.## | 6564 | 6564 |
###.0 | 6564 | 6564.0 |
10 Casting and Converting Objects and primitive types
Primitive types
(typename) value
(int) (x/y);
netPrice = (int) Price;
Casting objects
GreenApple a;
Apple a2;
a=new GreenApple();
a2 (Apple) a;
11 Math Class
Constants
Math.E = e = 2.718281828459
Math.PI = 3.14159265359
Function | Return Type | Argument type |
sin | Static double | double |
cos | Static double | double |
tan | Static double | double |
asin | Static double | double |
acos | Static double | double |
atan | Static double | double |
atan2 | Static double | double a/ double b |
round | Static long | double |
round | Static int | float |
ceil | Static double | double |
flour | Static double | double |
rint | Static double | double |
IEEEremainder | Static double | double a double b |
sqrt | Static double | double |
pow | Static double | double a double b |
exp | Static double | double |
log | Static double | double |
random | Static synchronised double | |
toDegrees | Static double | double |
toRadians | Static double | double |
abs | Static int | int |
abs | Static long | long |
abs | Static float | float |
abs | Static double | double |
min | Static int | int |
min | Static long | long |
min | Static float | float |
min | Static double | double |
max | Static int | int |
max | Static long | long |
max | Static float | float |
max | Static double | double |
12 Strings and String Class Functions
3 methods to declare
strings
Method 1
String hatcolor; // declaring
Hatcolor="Black";// using string
Method 2
String hatColor= "Black";
Method 3
String hatColor= new String("Black"); // Since Strings are objects
they can also be decalared as
// classes
All strings are allocated to the pool of literal strings
Java strings are imutable ie they have their size set in stone
String Buffers are mutable their sizes can be changed dynamically
Function | Return Type | Argument type |
charAt | char | String |
concat | String | String |
compareTo | int | String |
compareToIgnoreCase | int | String |
endsWith | boolean | String |
equals | boolean | String |
equalsIgnoreCase | boolean | String |
indexOf | int | String |
length | int | String |
replace | String | String |
startsWith | boolean | String |
substring | String | String |
toLowerCase | String | String |
toUpperCase | String | String |
toString | String | String |
trim | String | String |
13 StringBuffer Class Functions
Function | Return Type | Argument type | Comments |
charAt | char | int index | |
capacity | int | ||
length | int | ||
append | object | ||
append | String | ||
insert | int offset, String str | ||
delete | int start , int end | ||
reverse | |||
setCharAt | int offset, char ch | ||
setLength | int len | ||
14 Graphics
Graphics Coordinate System
0,0 |
|||
20,20 |
|||
60,60 |
Drawing Shapes
public void paint(Graphics g)
{
//drawing
code goes here
}
Shape | Function |
Line | g.drawLine(x1,y1,x2,y2) |
Rectangle | g.drawRect(x1,y1,x2,y2) |
Rounded Rectangle | g.drawRoundRect(x1,y1,x2,y2) |
Fill a Rounded Rectangle | g.fillRoundRect(x1,y1,x2,y2) |
Oval | g.drawOval(x1,y1,x2,y2) |
Fill an Oval | g.fillOval(x1,y1,x2,y2) |
Arc | g.drawArc(x1,y1,x2,y2) |
Fill an Arc | g.fillArc(x1,y1,x2,y2) |
Copy an Area | CopyArea(x1,y1,x2,y2) |
Clear an Area | ClearArea(x1,y1,x2,y2) |
public void paint(Graphics g)
{
Font f = new
Font("TimesRoman",Font.Plain,18);
g.setFont(f);
g.drawstring("Hello My string
");
}
Function | Arguments | Type returned |
.setFont | object | |
.setName | ||
.setSize | ||
.setStyle | ||
.getFont | ||
.getName | ||
.getSize | ||
.getStyle | ||
isBold | boolean | |
isPlain | boolean | |
isitalic | boolean | |
Font Methods
stringWidth | Width of a string | |
charWidth | Width of a character | |
getAscent | Ascent of character | |
getDecent | Decent of character | |
getLeading | Leading between characters | |
getHeight | Height of character | |
16 Colour
Color c=new Color(R1,G1,B1);
R1=0 to 255 Red
G1=0 to 255 Green
B1=0 to 255 Blue
Red | 255,0,0 |
Green | 0,255,0 |
Blue | 0,0,255 |
Pink | 255,175,175 |
Orange | 255,200,0 |
Light Gray | 192,192,192 |
Gray | 128,128,128 |
Dark Gray | 64,64,64 |
Black | 0,0,0 |
g.setColor(new Color(R1,G1,B1));
g.setColor(Color.Gray);
System.in.read();
System.out.println(String)
StringBuffer stBf = new stringBuffer;
Char ch;
String st;
try
{
st=;
while ((ch=(char)
System.in.read()) !=\n)
{
System.out.println(ch);
st=st+ch;
}
}
catch(Exception e)
{
System.out.println("Error :
" +e.toString());
}
Classes are ADTs (Abstract Data Types) which combine both Variables(Attributes) and Functions (Methods)
A Class is a blueprint defining an object Defining its Attributes(Variables) and Its Methods(Functions)
An Object is an instance of a Class and is a bundle (in memory) consisting of Variables and Methods.
Objects interact with eachother using Messages
Events are raised by Methods and are handled by Methods
Objects have State ( stored in its Attributes/Variables)
Objects have Behaviour (defined in its Methods)
Member Variables Provide the state of the Class and its objects.
Two types of Member Variables (Attributes )
Class Variables
They are shared by all Object instances of the Class
Only the Classes Objects can assess them
Are declared as Static each ocupying a single location in memory
static int myValue;
Instance Variables
Each Object has its own copy of the instance variables
If declared as Private the Instance Variables can only be accessed by member methods of
the same Object instance
Class Methods
Are shared by all object instances of the Class
Each Class method occupies a single memory location
They are declared as Static
static int myMethod( )
Instance Methods
Each Object instance has its own copy of instance methods
If declared as Private these methods can only be accessed by member methods of the same
Object instance
The Constructor
This method is called as the object instance is being created
It allways has the same name as the Class
It is allways declared as a Void method
The Finalize Method
Public class myClass
{
// Attributes
// Class Variables
static type VariableName;
// Instance Variables
type VarName;
// Methods
//Class Method
static type MethodName( )
{
// Some code here
}
//Instance Method
type myClass( ) // constructor
{
// Some code here
}
type MethName( )
{
}
}
Method Signatures(Method Overloading) Each Method has a unique signature made up of the following elements:
Return_Type Method_Name(Method_Parameters);
Thus you can have more than one method with the same name making the method an Over-loaded
Method
By overloading methods you can give a method different meanings
int Plus (int x, int y)
double Plus(double x, double y)
String Plus(Sring a, String b)
In this example me have overloaded the method Plus as it has three similar methods with different signatures
Calling a Method
Since we have declared methods in our classes we may want to use/call them
Remember methods are not accesable on their own but as object instance members
This means we need to make reference of the Object as well as the Method refer to example
below
MyClass MyObjectInstanceOfMyClass = new MyClass(Its_Parameters_here);
Int i;
i= MyObjectInstanceOfMyClass.MyMemberMethodOfMyClass;
Parameter List of Members
This is part of the Methods signature
It is the part of the Method where we define what types of values the method will receive
As well as assigning variables to accept the values to be passed to the method
Method(type1 paramerterName1, type2 paramerterName2, type3 paramerterName3,
etc)
Pass by Reference
When you pass an object to a method you are merery passing a reference to the Object
The method has full control of the Objects Variables (Attributes) and caution should be
excercized here
Since Arrays and Strings are Objects caution should be excercized when passing them to
methods
Sphere globe=new Sphere(10,10,1,1);
Obj.change(globe) // passing object globe to method
Coding the Class
Class myClass
{
//Attributes (Internal Variables
used by the Class object)
int attribute1;
char myCharAttribute2;
String myStringAttribute
// Methods (These are the
Functions in the class
void myClass( ) // This method is
known as the Constructor
{
// it is always executed first as the object instance is made
some_Code_here_ ;
void myMethod1( ) // This is one of many methods you add to
your classint herMethod2( int myVar, char hisVar) // another method
Method(AttributeName)
{
this. AttributeName= AttributeName;
}
B=this.myMethod( )
Modifier | Desctiption |
public | Used to make methods/Attributes universally accessable |
private | To restrict methods/attributes to be only accessible inside the class |
protected | To restrict methods/attributes to be only accessible to the classes that are subclasses of current class |
package | Is implied when no
modifier is used infront of variable or method This is used to hide the name of method or attribute. It is the default level of protection |
public class myClass( )
// Methods
}
public int herMethod( )
}
int yourMethod( ) // Package
}
}
Creating New Objects You use new with the name of the class you want to create an instance of.
Creating Array Objects (Arrays are Objects )
Multidimentional Arrays
Date Programs
Calling Methods String str ="Hello there new world";
21 Casting and Converting Objects and Primitive types
(typename) object
Primitive types
(typename) value
(typename) expression
a= (int) (x/y);
netPrice= (int) Price;
Casting Objects
GreenApple a;
Apple a2;
a=new GreenApple; // a is an Apple object
a2= (Apple) GreenApple //a2 is an Apply object
made from a GreenApple
Applets
Are downloaded from the World Wide Web
vis your browser
And run in the browsers Virtual Machine
Your class should include a main method
class myAccount
public myAccount(String name,String number) //constructor
public static void main(String args[]) // Main method
}
Compiling your Class file (Both Applets & Applications)
Running your application
Running an Applet
23 APPLETS
Creating Applets
Applets have more activities corresponding
to major events to address than applications
APPLET MAIN METHODS
Initialization
public void init( )
When an applet is first loaded this method is called during creation of initial object instance to set the initial state of the object
Starting
public void start( )
After Initialization, or after stopping and
starting this method is called
Stopping
public void stop( )
On stopping this method is called
Stopping and starting go hand in hand.
Stopping occurs when the user leaves the page
containing the current applet or when you call stop( )
Destroying
public void destroy( )
This method is called by the applet to cleanup
before it is freed or the browser exits
To launch an Applet (HTML TAGs)
<APPLET CODE="myapplet.class"
"ARCHIVE=myFile.jar" WIDTH=50 HEIGHT=20>
</APPLET>
Creating a Sub Classes in your applets
All applets are sub classes of the
Applet Class
A sub class of Applet inherits the behavior from this class
public class myApplet extends java.applet.Applet
{
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color
Font f=new
Font(TimesRoman",Font.Bold,36);
public void paint(Graphics g)
{
g.setFont(f);
g.setColor(Color.red);
g.drawString("Hello
world",5,50);
}
}
24 Source Files
Example of a Package
Package Geometry;
// imports
import java.awt.Graphics
// Class Definition/s
public class Line
{
// Attributes
. Etc
// Methods
..
etc
}
Can be used as object variations of primitive data types
Primitive Data type | Wrapper Class |
boolean | Boolean |
byte | Byte |
char | Character |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
26 Low-Level System-Access Classes
The System and Runtime classes offer access to system information and resources
The System Class
You dont need to instantiate an object from
the System Class.
The System class encaptulates the
standard input and standard output and error output streams
I=System.in.read( );
System.out.println("I="+I);
Str=e.toString( );
System.out.println("Error="+ str);
The Runtime Class
Offers access to the runtime environment
FreeMemory=rt.freeMemory; // Bytes
TotalMemory=rt.totalMemory; // Bytes
You can derive Sub Classes from a Base Class or Super Class
They will inherit both methods and attributes
Mamals
Primates Rodents Carnivores (Super class)
Cats Dogs (derived Classes)
Inherited Data members
Access Modifier | Access from sub class in same package | Access from sub class |
No Access Modifier( equivalent to a C++ friend function) | Yes | No |
Public | Yes | Yes |
Private | No | No |
Protected | Yes | Yes |
Enables different subclasses to implement the same method differently
Method Overioding
A method in a Base class and the same one in a sub class can have identical (signature) parameters
Overiding methods in sub classes will replace the same method in the super class
Overriding method must be defined in the sub class
Java.lang.Object (Universal super Class) MyClass1 Myclass2
clone() | Makes identical copy of a class |
equal() | |
getclass() | Returns the object class |
toString() | Returns a character representation of the object id |
finalize() | Object destructor |
Object reference
Is stored as a 32bit address pointing to the object
Implicid Casting
Casting a super class object from a sub class objectExplicit Casting Casting a sub class object from a super class object
Not allowed
You cant cast another sub class object from a object that is also a sub class from the same super class
One or more methods will Not be declared
You cnat instantiate an abstract class
You must create sub classes to instanciate objects
use the key word abstract for class abstract methods
Public abstract class myclass
{
public abstract void sound();
public abstract void affection();
}
Can not be sub classed
Public final class Lion
{
}
"Like variables Final denotes Const in VB"
A device for unrelated objects to interface with each other.
Public interface interfaceName
{
}
class myClass implements interfacename,interface2,interface3 etc
{
}
An interface is a total abstraction it has no implimentation
This is Javas way of implementing "multiple inheritance"
Top of Page
Sample Applications and Applets
Number | Description |
S1 | Fuel Consumption Calculator |
S2 | Student Symbol |
S3 | StudentMarks |
S1 Fuel Consumption Calculator
class fuelConsumption
{
//Attributes
private double litres;
private double kilometers;
private double Rate;
public String sRegistration;
public String sModel;
//Methods
public fuelConsumption(String model,String registration)//constructor
{
litres=0.0;
kilometers=0.0;
Rate=0.0;
sModel=model;
sRegistration=registration;
}
public void setLitres(double l)
{
litres=l;
}
public void setKilometers(double k)
{
kilometers=k;
}
public double getLitres( )
{
return litres;
}
public double getKilometers( )
{
return kilometers;
}
public double getRate( )
{
return Rate;
}
private void calculateRate( )
{
Rate=100.0 * litres / kilometers;
}
public static void main(String args[])
{
fuelConsumption fcalc = new
fuelConsumption("Hyundai Elantra","KFK612GP");
fcalc.setLitres(52.34);
fcalc.setKilometers(712.72);
fcalc.calculateRate();
System.out.println("Consumption for "
+fcalc.sModel + " " + fcalc.sRegistration);
System.out.println("Litres= " +
fcalc.getLitres());
System.out.println("kilometers= " +
fcalc.getKilometers());
System.out.println("Consumption Rate =
" + fcalc.getRate() + "litres/100Km");
}
}
class studentSymbol
{
//Attributes
private double Rate;
public double studentMarks;
public String studentName;
public String studentSymbol;
//Methods
public studentSymbol(String student,double marks)//constructor
{
studentMarks=marks;
studentName=student;
}
public void symbol(double marks)
{
if (marks>79)
studentSymbol="A";
else if (marks>69)
studentSymbol="B";
else if (marks>59)
studentSymbol="C";
else if (marks>49)
studentSymbol="D";
else if (marks>39)
studentSymbol="E";
else
studentSymbol="F";
}
public static void main(String args[])
{
int i,j;
studentSymbol marks = new
studentSymbol("John Doe",82.12);
System.out.println("Student : " +
marks.studentName);
System.out.println("marks : " +
marks.studentMarks);
marks.symbol(marks.studentMarks);
System.out.println("symbol : " +
marks.studentSymbol);
System.out.println(" ");
System.out.println("Mark Symbol");
for(i=10;i<100;i+=10)
{
marks.symbol(i);
System.out.println(i+" "+marks.studentSymbol);
}
}
}
class StudentMarks
{
public String getSymbol(double marks)
{
String symbol;
int mks; mks=(int) marks/10;
symbol="F";
switch (mks)
{
case 10:
case 9:
case 8:
symbol="A";
break;
case 7:
symbol="B";
break;
case 6:
symbol="C";
break;
case 5:
symbol="D";
break;
case 4:
symbol="E";
break;
default:
symbol="F";
break;
}
return symbol;
}
public static void main(String args[])
{
int i;
double marks;
String symbol;
StudentMarks Student= new StudentMarks( );
for(i=0;i<12;i++)
{
marks=100*Math.random( );
symbol=Student.getSymbol(marks);
System.out.println("Mark " + marks + "Symbol=" + symbol );
}
}
}
Tell Nico What you think of his Java Page
Please send mail to: Nicom@rocketmail.com with comments about the content this Java Page.