Developing Applications Using Java SE (1)
Developing Applications Using Java SE (1)
Java Programming
Introduction To Java
MyFile.java MyClass.class
JVM + +
Libraries compiler
+
JRE utilities
JDK
• Download JDK 8
http://bit.ly/3TJqjJA
• Now alter the 'Path' variable so that it also contains the path
to the Java executable.
2
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 14
First Java Application
class HelloWorld
{
public static void main(String[] args)
{
System.out.println(“Hello Java”);
}
}
– Must be static.
• because it is the first method that is called by the Interpreter
(HelloWorld.main(..)) even before any object is created.
System PrintStream
+ PrintStream out:static
+ Print(String):void
+ Println(String):void
• To compile:
Prompt> javac hello.java
• To run:
Prompt> java HelloWorld
Hello Java
Prompt>
• If no package is specified,
– then the compiler places the .class file in the default
package (i.e. the same folder of the .java file).
Current Directory
• To run:
• Example:
prompt> jar cf App.jar HelloWorld.class
• Class names:
MyTestClass , RentalItem
_______________________________________________________________________
• Method names:
myExampleMethod() , getCustomerName()
_______________________________________________________________________
• Variables:
mySampleVariable , customerName
_______________________________________________________________________
• Constants:
MY_STATIC_VAR , MAX_NUMBER
_______________________________________________________________________
• Package:
pkg1 , util , accesslayer
Web Server
(www.abc.com)
www.abc.com\index.html
Download
MyApplet.class
start()
Constructor
stop()
▪ start():
• called whenever the browser’s window is activated.
__________________________________________________________________________________________________
▪ paint(Graphics g):
• called after start() to paint the applet, or
• whenever the applet is repainted.
__________________________________________________________________________________________________
▪ stop():
• called whenever the browser’s window is deactivated.
__________________________________________________________________________________________________
▪ destroy():
• called when the browser’s window is closed.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 33
Applet Life Cycle cont’d
import java.applet.Applet;
import java.awt.Graphics;
<html>
<body>
<applet code=“HelloApplet”
width=400 height=350>
</applet>
</body>
</html>
Hint:
use the self closing tag: <param name= value= />
Introduction to OOP
Using Java
• What is OOP?
– OOP is mapping the real world to Software
• What is OOP?
– Each object is an instance of a class.
• What is a Class?
– A class is a blueprint of objects.
– A class is an object factory.
– A class is the template to create the object.
– A class is a user defined datatype
• Object:
– An object is an instance of a class.
– The property values of an object instance is different
from the ones of other object instances of a same class
– Object instances of the same class share the same
behavior (methods).
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 45
Introduction to OOP – Object & Class
class
object
• What is an Object?
– An object is a software bundle of variables and related
methods.
Class Object
Encapsulates the attributes, The living thing that interacts
and behaviors into a blue-print and actually runs.
code to provide the design
concept.
• Example:
Polymorphism
getter
• To declare a method:
<modifier>* <Return type> <name> ([<Param Type> <Param
Name>]*)
{
<Statement>*
}
• Example:
class StudentRecord {
private String name;
public String getName(){ return name; }
public void setName(String str){ name=str; }
public static String getSchool(){...........}
}
• Inheritance:
– Inheritance is to extend the functionality of an existing class
– Inheritance represents is – a relationship between the Child and
its Parent.
Animal
Kind of
or
is - a In Java
Inheritance
Child Parent
super
Compilation error
• Now if we try to call the play method inside the Dog class
the newly overridden method inside the Dog class will
respond.
• If we want to call the parent method we can use the
super reference.
• Overloading and overriding are used to redefine the
method implementation with preserving the method
name.
• This helps the class users to remember only a little about
my class, and in the other hand the class will behave
differently according to the implemented method.
• Note: overriding can be done to attributes but it is not
recommended.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 80
polymorphism
Animal
numOfLegs
speed
name
play()
eat(AnimalFood f)
Primitive Reference
byte → Byte
char → Character
short → Short
int → Integer
long → Long
float → Float
double → Double
String s3 = Integer.toHexString(254);
System.out.println("254 is " + s3);
POSITIVE_INFINITY
• Unary Operators:
+ - ++ -- ! ~ ()
positive negative increment decrement boolean bitwise casting
complement inversion
Widening
(implicit casting)
Narrowing
char (requires explicit casting)
• Arithmetic Operators:
+ - * / %
add subtract multiply division modulo
• Assignment Operators:
= += -= *= /= %= &= |= ^=
• Relational Operators:
• Shift Operators:
>> << >>>
right shift left shift unsigned right shift
• Ternary Operator:
int y=15;
int z=12;
int x=y<z?10:11;
If(y<z)
x=10;
else
x=11;
• Or on one line:
MyClass myRef = new MyClass();
str1 = null;
Stack
str1.anyMethod(); // ILLEGAL!
//Throws NullPointerException
Stack myArr
System.out.println(myArr[2]);
myArr[3] = … ; // ILLEGAL!
//Throws ArrayIndexOutOfBoundsException
“Gosling”
namesArr[0] = new String(“Hello”);
namesArr[1] = new String(“James”); Stack
namesArr
namesArr[2] = new String(“Gosling”);
System.out.println(namesArr[1]);
if(myStr1.equalsIgnoreCase(sp1))
if(myStr1 == sp1)
// Shallow Comparison (just compares the references)
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 108
Strings Operations cont’d
• The ‘+’ and ‘+=‘ operators were overloaded for class String
to be used in concatenation.
“Hello”
String s1 = new String(“Hello”);
“Welcome”
String s2 = new String(“Hello”); Heap
“Hello”
String strP1 = “Welcome” ;
String strP2 = “Welcome” ;
print(“Pass”); print(“fail”);
switch(myVariable){ • byte
case value1: • short
…
… • int
break; • char
case value2:
… • enum
… • String “Java 7”
break;
default:
…
}
while (boolean_condition)
{
…
…
…
}
int x = 0;
while (x<10) {
System.out.println(x);
int x = 0;
x++;
}
false
x<10?
true
print(x);
x++;
int x = 0;
do{
int x = 0; System.out.println(x);
x++;
} while (x<10);
print(x);
x++;
false
x<10?
true
initialization
Loop false
condition
true
statements
step
average /= samples.length;
javadoc myfile.java
• Example 1:
/**
* @author khaled
*/
• Example 2:
/**
* @param args the command line arguments
*/
* *
** **
*** ***
**** ****
• Bonus: Write the same program using 1 loop
❑ Exception Handling
• The following table illustrates these keywords and how they are
used.
Class C Class H
package3 package4
import package2.F;
import package1.A; import package1.A;
Class D Class I
Class E Class J
package1.A a Ff
Class C Class H
w, x, y o, p, q
package3 package4
import package1.A; import package1.A;
class D extends package1.A
Class I
Class D Class E Class J
x y package1.A a Ff
x
• You can use it to draw strings, basic shapes, and show images.
• You can also use it to specify the color and font you want.
• In order to work with colors in your GUI application you use the
Color class.
Toolkit t= Toolkit.getDefaultToolkit();
String[] s = t.getFontList();
• Example:
– attempting to open a file that does not exist, or
– attempting to write in a file that the OS has marked as
read only.
– attempting to use a reference whose value is null, or
– attempting to access an array element that is beyond
the actual size of the array.
Exception
Object
Yes Handler No
for this
exception?
Throwable
Exception Error
e.g. Out of Memory
e.g. Stack Overflow
… … IOException RunTimeException
Checked Exceptions
… … NullPointerException
Unchecked Exceptions
2. Put them all inside the same try block and then
write multiple catch blocks for it
(one catch for each exception type).
3. Put them all inside the same try block and then
just catch the parent of all exceptions: Exception.
• If more than one catch block are written after each other,
– then you must take care not to handle a parent exception before a
child exception
try { ...... }
catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: “);
}
catch (IOException e) {
System.err.println("Caught IOException: “);
}
In Java 7:
try { ...... }
catch (FileNotFoundException | IOException e) {
System.err.println(“...................“);
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Example2 { public static void main (String[] args)
{
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String line;
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Interfaces
computeArea()
implements implements
Shape Building
class Demo2
{
public static void main (String args[])
{
ByTwos twoOb = new ByTwos();
ByThrees threeOb = new ByThrees();
Numbers ob;
for(int i=0; i < 5; i++) {
ob = twoOb;
System.out.println("Next ByTwos value is " +
ob.getNext());
ob = threeOb;
System.out.println("Next ByThrees value is " +
ob.getNext());
}
JavaTM Education & Technology Services
} }
Copyright© Information Technology Institute http://jets.iti.gov.eg 176
General Consideration about interfaces
Multi-Threading
• A Thread is
– A single sequential execution path in a program
– Each thread has its own stack, priority & virtual set of
registers.
th1
Garbage Event Dispatcher
Collection Thread Thread
th2 run()
th3
run()
run()
▪ Class Thread
▪ start()
▪ run()
▪ sleep()
▪ suspend()*
▪ resume()*
▪ stop()*
▪ Class Object
▪ wait()
▪ notify()
▪ notifyAll()
run() {
…………
}
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 184
Working with Threads cont’d
Selected by
schedule
Ready
start()
* Deprecated function
** there is no guarantee that yield() method will put the current thread into ready state
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 190
Synchronization
• Example:
Two threads want to
access the same file, one
thread reading from the
file while another thread
writes to the file.
Inner Classes
class OuterClass
{
...
class InnerClass
{
...
}
}
2. It increases encapsulation.
class MyInnerClass{
public void aMethod(){
//you can access private members of the outer class here
x = 3 ;
}
}
}
• When you compile the java file, two class files will be
produced:
▪ MyClass.class
▪ MyClass$MyInnerClass.class
– When you create an object of static inner class, you don’t need to
use an object of the outer class (remember: it’s static!).
– Since it is static, such inner class will only be able to access the
static members of the outer class.
});
th.start();
}
}
• When you compile the java file, two class files will be
produced:
▪ MyClass.class
▪ MyClass$1.class
Event Handling
Registration
Event Registration Event Listener
Registration Event Listener
Source Event Listener
Registration
Button
Action
ActionListener
Event
Action
Event
Event Queue
JVM
Action Registration
Event Button ActionListener
AWTEvent
KeyEvent MouseEvent
MouseWheelEvent
Listener
Event Method(s)
Interface(s)
ActionEvent ActionListener actionPerformed (ActionEvent e)
componentHidden (ComponentEvent e)
componentShown (ComponentEvent e)
ComponentEvent ComponentListener
componentMoved (ComponentEvent e)
componentResized (ComponentEvent e)
componentAdded (ComponentEvent e)
ContainerEvent ContainerListener
componentRemoved (ComponentEvent e)
Listener
Event Method(s)
Interface(s)
focusGained (FocusEvent e)
FocusEvent FocusListener
focusLost (FocusEvent e)
windowClosed (WindowEvent e)
windowClosing (WindowEvent e)
windowOpened (WindowEvent e)
WindowEvent WindowListener windowActivated (WindowEvent e)
windowDeactivated (WindowEvent e)
windowIconified (WindowEvent e)
windowDeiconfied (WindowEvent e)
keyPressed (KeyEvent e)
KeyEvent KeyListener keyReleased (KeyEvent e)
keyTyped (KeyEvent e)
mousePressed (MouseEvent e)
mouseReleased (MouseEvent e)
MouseListener mouseClicked (MouseEvent e)
mouseEntered (MouseEvent e)
MouseEvent mouseExited (MouseEvent e)
mouseMoved (MouseEvent e)
MouseMotionListener
mouseDragged (MouseEvent e)
MouseWheel
MouseWheelListener mouseWheelMoved (MouseWheelEvent e)
Event
→