Java 2
Java 2
Introduction
to
Object-
Oriented
Programming
SYNTAX:
javac <filename>.java
EXAMPLE:
javac Welcome.java
SYNTAX:
java <filename>
EXAMPLE:
java Welcome
Java code
(*.java)
Java Compiler
bytecodes
(*.class)
Java Virtual
Machine
MAC PC UNIX
Download BlueJ:
http://www.bluej.org/download/download.html
Minimum Requirements:
Pentium II processor or its
equivalent
64Mb main memory
Recommended:
400MHz Pentium III processor
or above and a 128Mb main
memory
[http://www.techfactors.ph] TechFactors Inc. ©2005
Launch BlueJ
/*
This class contains the main() method
*/
package Group.Student;
compile-time errors
runtime errors
Summary…
Laboratory Exercise
//write the class name here //write the object name here
Class Human Man
//write the data of the class here //write the data of the object here
Name Name: Jonathan
Age Age: 29
Birthday Birthday: March 4, 1975
//write the methods of the class here //write the methods of the object
Grow here
Give_Name Grow
Get_Name Give_Name
Get_Age Get_Name
Get_Age
//write the class name here //write the object name here
Line 1
A single line comment.
A comment is read by he java compiler but,
as a command, it is actually ignored.
Any text followed two slash symbols(//)
is considered a comment.
Example:
// Welcome to Java [http://www.techfactors.ph] TechFactors Inc. ©2005
Explaining Welcome.java
Line 2 defines the beginning of the
Welcome class. When you declare a class
as public, it can be accessed and used
by the other class.
Notice that there is also an open brace to
indicate the start of the scope of the class.
To declare a class here is the syntax
<method>class<class_name>
Example: public class Welcome{
[http://www.techfactors.ph] TechFactors Inc. ©2005
Explaining Welcome.java
Line 3 shows the start of the method
printWelcome().
Syntax :
<modifier> <return_type> <method_name>
(<argument_list>) { <statements>) }
Void is the return type for the printWelcome()
Method. A method that returns void returns
nothing. Return type are discussed further
in lesson 8
Example: public void printWelcome() {
[http://www.techfactors.ph] TechFactors Inc. ©2005
Explaining Welcome.java
Line 4 shows how to print text in java. The
println() method displays the message
inside the parentheses on the screen, and
then the cursor is placed on the next line. If
you want cursor to go to the next available
space after printing, use print() method.
Syntax:
System.out.println(String);
Example:
System.out.println("Welcome to Java!");
[http://www.techfactors.ph] TechFactors Inc. ©2005
Explaining Welcome.java
Line 5 and 6 }
}
Contains closing braces. The braces on
line 5 closes the method
printWelcome() and the braces on line
6 closes the class Welcome.Take note
that the opening brace on line 3 is
paired with the closing brace on line 5
and the brace on line 2 is paired with
the closing brace on line 6
[http://www.techfactors.ph] TechFactors Inc. ©2005
Explaining Main.java
/*
This class contains the main() method
*/
/*
This class contains the main() method
*/
Explaining Main.java
Line 5
Declares the Main class. the brace after the
class indicates the start of the class.
Summary…
SYNTAX EXAMPLE/S
System.out.println(String); System.out.println("Welcome to Java!");
/* /*
multi-line comment This class contains the main() method
*/ */
//single line comment // author@
//prints_a_msg
/** /**
Java doc multi-line comment */ This method will compute the sum of two
integers and return the result.
*/
Below is a simple Java program that will print your name and age on the
screen. Fill the missing portions with the correct code. Type the program,
compile and run it.
First.java //filename
1 /*
2 This class contains the main() method
3 */
4 package Group.Student;
5
6 public class First {
7 public static void main(String args[]) {
8 Name ____________= new Name();
9 myName.________________();
10 }
11 }
Below is a simple Java program that will print your name and age on the
screen. Fill the missing portions with the correct code. Type the program,
compile and run it.
Name.java //filename
1 package Group.Student;
2 // author@
3 public class __________{
4 public void printName() {
5 System.out.print("____________");// prints your name
6 System.out.println("____________");//prints your age
7 }
8 }
Laboratory Exercise
Data Types,
Literals,
Keywords and
Identifiers
Examples:
boolean Passed=true;
char EquivalentGrade=’F’;
byte YearLevel=2;
short Classes=19;
int Faculty_No=6781;
long Student_No=76667;
float Average=76.87F;
Casting
• the process of assigning a value of a
specific type to a variable of another
type.
• The general rule in type conversion is:
• upward casts are automatically done.
• downward casts should be expressed
explicitly.
[http://www.techfactors.ph] TechFactors Inc. ©2005
Sample Code
package Group.Lesson3;
public class Core
{
public Core(){ }
/**
* The main method illustrates implicit casting from char to int
* and explicit casting.
*/
public static void main(String[] args)
{
int x=10,Average=0;
byte Quiz_1=10,Quiz_2=9;
char c='a';
Average=(int) (Quiz_1+Quiz_2)/2; //explicit casting
x=c; //implicit casting from char to int
System.out.println("The Unicode equivalent of the character 'a' is : "+x);
System.out.println("This is the average of two quizzes : "+Average);
}
} [http://www.techfactors.ph] TechFactors Inc. ©2005
End of Lesson 3
Summary…
II. Write C if the given statement is correct on the space provided before each
number. Otherwise, write I. Correct statements do not contain bugs.
________________1.) System.out.print(“Ingat ka!”, V);
________________2.) boolean B=1;
________________3.) double=5.67F;
________________4.) char c=(char) 56;
________________5.) System.out.print(‘ I love you! ‘);
[http://www.techfactors.ph] TechFactors Inc. ©2005
Self-check
III.Below is a simple Java program that will print your name and age on the screen.
Fill the missing portions with the correct code. Type the program, compile and
run it.
public class First
{
public ________________(){ }//Constructor for objects of class Core
public static void main(String[] args)
{
int I=90;
short S=4;
________________;//statement to cast I to S
System.out.println(“I=___________________ );//print I
System.out.println(“S=___________________ );//print S
}
}
LABORATORY EXERCISE
Java Operators
• Unary
• Binary
• Ternary
• Shorthand
Operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
++ Increment
-- Decrement
[http://www.techfactors.ph] TechFactors Inc. ©2005
The Arithmetic_operators
package program
Group.Lesson4.Arithmetic;
public class Arithmetic_operators
{
public Arithmetic_operators() { } // Constructor
public static void main(String[] args)
{
int x=30, y= 2;
int Add=0,Subtract=0,Multiply=0,Divide=0;
int Modulo=0,Inc1=0,Inc2=0,Dec1=0,Dec2=0;
Add=x+y;
Subtract=x-y;
Multiply=x*y;
Divide=(int)x/y;
Modulo=x%y;
[http://www.techfactors.ph] TechFactors Inc. ©2005
The Arithmetic_operators program (Continued)
System.out.println("30+2="+Add+"\n30-2="+Subtract);
System.out.println("30*2="+Multiply+"\n30/2="+Divide+"\n30%2="+Modulo);
System.out.println("x="+x+"\ny="+y);
x++;
++y;
System.out.println("x="+x+"\ny="+y);
--x;
y--;
System.out.println("x="+x+"\ny="+y);
Inc1=x++;
Inc2=++y;
System.out.println("Inc1="+Inc1+"\nInc2="+Inc2);
System.out.println("x="+x+"\ny="+y);
Dec1=--x;
Dec2=y--;
System.out.println("Inc1="+Inc1+"\nInc2="+Inc2);
System.out.println("x="+x+"\ny="+y);
}
}
[http://www.techfactors.ph] TechFactors Inc. ©2005
The Arithmetic_operators program output
package Group.Lesson4.Relational;
Operators Description
! NOT
|| OR
&& AND
| short-circuit OR
Operand1 RESULT
! true false
! false true
[http://www.techfactors.ph] Te
Logical Operator- Truth Tables
[http://www.techfactors.ph] Te
Logical Operator- Truth Tables
[http://www.techfactors.ph] Te
Logical Operator- Truth Tables
[http://www.techfactors.ph] Te
The Logical_operators program
package Group.Lesson4.Logical;
public class Logical_operators
{
// Constructor for objects of class Logical_operators
public Logical_operators(){}
public static void main(String[] args)//execution begins here
{
//local variables
int x = 6 , y = 7;
boolean Logical_OR=false, Logical_OR_ShortCircuit=false;
boolean Logical_AND=false, Logical_AND_ShortCircuit=false;
boolean Logical_NOT=false, Logical_XOR=false;
System.out.println("x=6 y=7");
Logical_OR= (x<y)||(x++==y);
System.out.println("(x<y)| (x++==y) "+Logical_OR);
[http://www.techfactors.ph] TechFactors Inc. ©2005
The Logical_operators program (Continued)
Logical_AND_ShortCircuit=(x<y)& (x==y++);
System.out.println("(x>y)& (x++==y) “ +Logical_AND_ShortCircuit);
Logical_AND= (x<y)&&(x++==y);
System.out.println("(x>y)&&(x++==y) "+Logical_AND);
Logical_NOT= !(x>y)||(x++==y);
System.out.println("!(x>y)||(x++==y) "+Logical_NOT);
Example:
4=0000000000000100
-4=1111111111111100
Operators Description
~ Complement
& AND
| OR
^ XOR (Exclusive OR)
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift
Operand1 RESULT
~ 1 0
~ 0 1
[http://www.techfactors.ph] Te
Bitwise Operator - Truth Tables
1 | 1 1
1 | 0 1
0 | 1 1
0 | 0 0
[http://www.techfactors.ph] Te
Bitwise Operator - Truth Tables
1 ^ 1 0
1 ^ 0 1
0 ^ 1 1
0 ^ 0 0
[http://www.techfactors.ph] Te
Bitwise Operator - Truth Tables
1 & 1 1
1 & 0 0
0 & 1 0
0 & 0 0
[http://www.techfactors.ph] Te
Bitwise Operator – Examples
x= 0000000000010000
~x= 1111111111101111 x= 0000000000010000
Therefore, ~x=-17. Left_shift=
0000000010000000
x= 0000000000010000 Left_shift = 128
y= 0000000000011011
Or= 0000000000011011 z= 1111111111111100
Right_shift=
x= 0000000000010000 1111111111111111
y= 0000000000011011 Right_shift= -1
And= 0000000000010000
Negative=1111111111111100
x= 0000000000010000 Negative=0011111111111111
y= 0000000000011011 Negative= 1073741823
Xor= 0000000000001011
The Bitwise_operators program
package Group.Lesson4.Bitwise;
//print results
System.out.println("x=16 y=7 z=-4");
System.out.println("~x = "+Complement);
System.out.println("x|y = "+Or);
System.out.println("x&y = "+And);
System.out.println("x^y = "+Xor);
System.out.println("x<<3 = "+Left_shift);
System.out.println("z>>2 = "+Right_shift);
System.out.println("Negative>>>2 = "+Unsigned_Right_shift);
}
}
Operators Description
+= Assignment With Addition
-= Assignment With Subtraction
System.out.println("Assign_With_Addition+=2 "+Assign_With_Addition);
System.out.println("Assign_With_Subtraction-=2 "+Assign_With_Subtraction);
System.out.println("Assign_With_Multiplication*=2 "+Assign_With_Multiplication);
System.out.println("Assign_With_Division/=2 "+Assign_With_Division);
System.out.println("Assign_With_Modulo%=2 "+Assign_With_Modulo );
System.out.println("Assign_With_Bitwise_And&=2 "+Assign_With_Bitwise_And);
System.out.println("Assign_With_Bitwise_Or|=2 "+Assign_With_Bitwise_Or );
System.out.println("Assign_With_Bitwise_XOR^=2 "+Assign_With_Bitwise_XOR);
System.out.println("Assign_With_LeftShift<<=2 "+Assign_With_LeftShift);
System.out.println("Assign_With_RightShift>>=2 "+Assign_With_RightShift);
System.out.println("Assign_With_UnsignedRightShift>>>=2 "+Assign_With_UnsignedRightShift);
}
}
expression
boolean expressions
truth value
truth table
shorthand operators
bit
sign bit
Summary…
1.x=a++;
2.y=--b;
3.!((++a)!=4)&&(--b==4))
4.(c++!=b)|(a++==b)
5.t=a+b*c/3-2;
Decisions
Syntax:
if (<boolean condition is true>)
{
<statement/s>
}
Example:
if(x!=0){
x=(int)x/2;
}
int x=0;
String Str_1;
Example:
if (A%2==0) {
System.out.println (A+" is an EVEN number");
} else {
System.out.println (A+" is an ODD number");
}
Syntax:
if (<boolean condition is true>){
<statement/s>
}
else
{
<statement/s>
}
[http://www.techfactors.ph] TechFactors Inc. ©2005
The IfElse program
package Lesson5.If_Else;
import java.io.*;
Syntax:
if (<boolean condition is true>){
<statement/s>
}
else if (<boolean condition is true>) {
<statement/s>
}
else
{
<statement/s>
}
Example:
if (number1>number2) {
System.out.println (number1+" is greater than "+number2);
} else if (number1<number2){
System.out.println (number1+" is less than "+number2);
} else {//number1==number2
System.out.println (number1+" is equal to "+number2);
}
Syntax:
switch(<expression>) {
case <constant1>:
<statements>
break;
case <constant2>:
<statements>
break;
:
:
default:
<statements>
break;
}
[http://www.techfactors.ph] TechFactors Inc. ©2005
switch Statement
Example:
switch(month){
case 1:System.out.println("January has 31 days");
break;
case 2:System.out.println("February has 28 or 29 days");
break;
case 3:System.out.println("March has 31 days");
.
.
.
default:System.out.println("Sorry that is not a valid month!");
break;
}
Wrapper class
Summary…
LABORATORY EXERCISE
switch(<expression>) { switch(Number){
case case 1:System.out.println("One ");
<constant1>:<statements> break;
break; case 2:System.out.println("Two");
case break;
<constant2>:<statements> case 3:System.out.println("Three");
break; break;
: default:System.out.println("Sorry!");
: break;
default:
}
<statements>
break;
}
[http://www.techfactors.ph] TechFactors Inc. ©2005
Self-check
Loops
[http://www.techfactors.ph] TechFactors Inc. ©2005
General Topics
• for structure
• while structure
• do-while structure
Syntax:
for (<initialization>;<condition>;<increment>)
{
<statement/s>
}
[http://www.techfactors.ph] TechFactors Inc. ©2005
The For_loop program and output
package Lesson6.For;
public class For_loop
{
public For_loop() { }
public static void main(String[] args)
{
for(int Ctr=1;Ctr<=5;Ctr++){
System.out.println(Ctr);
}
}
} [http://www.techfactors.ph] TechFactors Inc. ©2005
while loop
Example:
int Ctr=1;
while(Ctr<=5){
System.out.println(Ctr);
Ctr++;
}
Syntax:
while (boolean condition is true)
{
<statement/s>
}
[http://www.techfactors.ph] TechFactors Inc. ©2005
Sample Code and output
Syntax:
do {
<statement/s>
} while (<boolean condition is true>);
Summary…
LABORATORY EXERCISE
• Nested loops
• continue
• break
– how it behaves
Nested loops
II. A Java program that prints the given output using nested do-while loops.
Fill-in the missing portions.
Exception classes
try
catch
finally
Exception classes
LABORATORY EXERCISE
Classes
• Classes
• Inheritance
• Interface
• Objects
• Constructors
• Overloading Methods
• Overriding Methods
[http://www.techfactors.ph] TechFactors Inc. ©2005
Classes
Example:
<modifiers> class
<class_name>{
[<attribute_declarations>]
[<constructor_declarations>]
[<method_declarations>]
}
Angelina.setName("Angel");
Angelina.setAge(69);
Angelina.setBirthday(dateToday);
System.out.println("Greetings, "+Angelina.getName());
Angelina.happyBirthday(dateToday);
System.out.println();
Allan.setDetails("Allan",20,new Date(3,5));
}
[http://www.techfactors.ph] TechFactors Inc. ©2005
The Date program
package Lesson8;
public class Date
{ // instance variables - replace the example below with your own
int day, month, year;
//Constructor for objects of class Date with no parameters
public Date()
{ // initialize instance variables
day = 1;
month=1;
year=2005;
}
package Lesson8;
public class Teacher extends Person implements Employee
{
private double salary;
// constructors
public Teacher(){
super();
salary = 4000;
}
public Teacher(double salary) {
super();
this.salary = salary;
}
public void setDetails(String name, int age, Date birthday, double salary){
super.setDetails(name, age, birthday);
this.salary = salary;
System.out.println("Good afternoon, "+name+". Your salary is "+salary+".");
System.out.println(" Your birthday this year is on ");
birthday.print_Date();
System.out.println("You are now "+age+" years old.");
System.out.println();
}
public double getSalary(){
return salary;
}
}
package Lesson8;
public interface Employee
{
public void setSalary(double salary);
public void setDetails(String name, int age, Date birthday, double salary);
public double getSalary();
}
• Superclass
• Subclass
• Inheritance
• Interface
• Method
• Signature
• Overloading Constructor
• Overriding Method
[http://www.techfactors.ph] TechFactors Inc. ©2005
End of Lesson 8
SUMMARY
SYNTAX EXAMPLE/S
<modifier> class <class_name> public class Student extends
[extends <superclass>] Person
}
[http://www.techfactors.ph] TechFactors Inc. ©2005
End of Lesson
LABORATORY EXERCISE
Arrays
• Single-dimensional arrays
• Array of Objects
• Multidimensional arrays
SYNTAX:
Example:
First Element Last Element
YearLevel 1 2 3 4
SYNTAX:
System.arraycopy(<Array_source>,
<Array_sourcePosition>,
<Array_destination>,
<Array_destinationPosition>,
<numberOfElements>);
<data_type> [ ][ ] <array_identifier> =
new <data_type>[<size1>][<size2>];
<data_type> <array_identifier> [ ] [ ]
= new <data_type>[<size1>]
[<size2>];
• Array Element
• Array Index
SUMMARY
System.arraycopy(<Array_source>, System.arraycopy(YearLevel,0,GradeLe
<Array_sourcePosition>, <Array_destination>, vel,1,YearLevel.length);
<Array_destinationPosition>,
<numberOfElements>);
}
//method that prints the contents of an array of String
public static void __________(_______[] Array){
for(intsubscript=0;subscript<Array.length;subscript++){
//prints the array element
System.out.print(__________); if(____________________){
//prints a comma in-between elements
System.out.print(", ");
}
}
System.out.println();
} [http://www.techfactors.ph] TechFactors Inc. ©2005
}
Self-check 2
public class Array2
{
// Constructor for objects of class Array2
public Array2 (){ }
public static void main(String[] args)
{
final int Row=5;
final int Column=5;
int [] [] Table=new int [Row][Column];
for(int Row_Ctr=0;Row_Ctr<Row;Row_Ctr++){
for(int Col_Ctr=0;Col_Ctr<Column;Col_Ctr++){
Table[Row_Ctr][Col_Ctr]= Row_Ctr+Col_Ctr;
}
}
}
}
Table[0][0]= ___________
Table[2][1]= ___________
Table[1][3]= ___________
Table[4][4]= ___________
Table[3][2]= ___________
LABORATORY EXERCISE
GUI
SYNTAX:
FlowLayout( )
FlowLayout(int align)
FlowLayout(int align, int hgap, int
vgap)
Examples:
setLayout(FlowLayout());
setLayout(FlowLayout(FlowLayout.LEFT
));
setLayout(FlowLayout(FlowLayout.RIG
HT,23,10));
[http://www.techfactors.ph] TechFactors Inc. ©2005
Layout
SYNTAX:
GridLayout( );
GridLayout(int rows, int cols);
GridLayout(int rows, int cols, int hgap, int vgap);
Examples:
setLayout(GridLayout());
SouthPanel.setLayout(new GridLayout(4,3));
SYNTAX:
BorderLayout( );
Examples:
setLayout(new BorderLayout());
add(NorthPanel, BorderLayout.NORTH);
CheckboxGroup group = new CheckboxGroup();
Checkbox b;
NorthPanel.add(new Label(" Shapes "));
NorthPanel.add(b = new Checkbox("Rectangle", group,
false));
b.addItemListener(this);
NorthPanel.add(b = new Checkbox("Circle", group,
false));
b.addItemListener(this);
NorthPanel.add(b = new Checkbox("Square", group,
false));
b.addItemListener(this);
NorthPanel.add(b = new Checkbox("Triangle", group,
false)); [http://www.techfactors.ph] TechFactors Inc. ©2005
b.addItemListener(this);
The DrawControl program (continued)
CenterPanel.setLayout(new GridLayout(4,1));
add(CenterPanel,BorderLayout.CENTER);
CenterPanel.add(new Label(" Colors "));
Choice colors = new Choice();
colors.addItemListener(this);
colors.addItem("red");
colors.addItem("green");
colors.addItem("blue");
colors.addItem("pink");
colors.addItem("orange");
colors.addItem("black");
colors.setBackground(Color.white);
[http://www.techfactors.ph] TechFactors Inc. ©2005
The DrawControl program (continued)
SouthPanel.setLayout(new GridLayout(4,3));
add(SouthPanel, BorderLayout.SOUTH);
Button CLEAR = new Button("CLEAR");
Button DRAW = new Button("DRAW");
CLEAR.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent event){
onCommand(1);
}
}
);
DRAW.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent event){
onCommand(2);
}
}
);
SouthPanel.add(CLEAR);
SouthPanel.add(DRAW);
[http://www.techfactors.ph] TechFactors Inc. ©2005
}
The DrawControl program (continued)
• Frames
• Checkbox
• Checkbox Group: Radio Button
• Choice
• Button
• Abstract Class
• Component
• Frame
• Dialog
• Panel
• Layout Manager
SUMMARY
LABORATORY EXERCISE