SlideShare a Scribd company logo
1 of 249
Download to read offline
Lesson 1


               Introduction
                     to
              Object-Oriented
               Programming

           Prof. Erwin M. Globio, MSIT
             Java Training Specialist
            http://eglobiotraining.com
Object Oriented Programming


           Model Real World Objects

           Encapsulate Data and Function
Java is used for Networking



              Has many classes to program
               Internet communications
              Java-enabled devices
                 mobile phones
              Web pages with additional
               animation and functionality
                 Java servlets
Java is Simple


            Derived from C/C++
            Simpler than C/C++.
            No preprocessors
            Pointers were eliminated
            Common data structures that use
             pointers such as stacks, lists and
             trees are available
Java is Robust


            Employs strong type checking
            Every data structure is defined
             and its type is checked during
             compilation and runtime
            Built-in exception handling
            Garbage collection is done
             automatically
Java is Dynamic




            There are many available Java
             resources in the Internet.
            Using interfaces
            Classes are dynamically loaded.
Java is Secure


            System breakers can not gain
             access to system resources
                  the Java bytecode verifier
                  loaded classes can not access the
                   file system
                  a public-key encryption system
                  (in the future)
Java is Free
            Java can be downloaded from the
             Internet for FREE
            Just visit http://java.sun.com/
Java is Portable


  You can compile your Java code from the
  command line.


                   SYNTAX:
                   javac <filename>.java
                   EXAMPLE:
                   javac Welcome.java
Java is Portable


  Java program can then execute on any
  machine which has the Java Virtual
  Machine, thus, making it portable.

                   SYNTAX:
                   java <filename>
                   EXAMPLE:
                   java Welcome
Java is Portable

                    Java code
                     (*.java)



                         Java Compiler

                    bytecodes
                     (*.class)

                            Java Virtual
                             Machine




                   MAC           PC        UNIX
IDE: BlueJ

 Download the appropriate version
 Check the system requirements
IDE


Download BlueJ:
http://www.bluej.org/download/download.html



 Install J2SE 1.4.2 (Java 2 SDK version
  1.4.2) or newer first before installing BlueJ
IDE: BlueJ


             Minimum Requirements:
              Pentium II processor or its
               equivalent
              64Mb main memory
             Recommended:
              400MHz Pentium III processor
               or above and a 128Mb main
               memory
Launch BlueJ




               Let‟s make your
                first Java project
                using BlueJ…
Sample codes
package Group.Student;

 public class Welcome{
   public void printWelcome() {
        System.out.println("Welcome to Java!"); //prints_a_msg
   }
 }
Sample codes



        /*
        This class contains the main() method
          */
          package Group.Student;

         public class Main {
           public static void main(String args[]) {
              Welcome Greet= new Welcome();
              Greet.printWelcome();
           }
         }
Common Programming Errors




          compile-time errors

          runtime errors
Compile Time Error
Compile Time Error
Compile Time Error
Run-Time Error
Run-Time Error
Word Bank
             class
             object
             interface
             message
             method
             inheritance
             encapsulation
             compile-time errors
             runtime errors
End of Lesson 1




             Summary…
End of Lesson 2




        Laboratory Exercise
Self-check
Create a class and describe it in terms of its attributes (data) and functions
(methods). Then, instantiate at least 2 objects. Use the tables below.

  //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
  Name                                       here
  Age                                        Name: Jonathan
  Birthday                                   Age: 29
                                             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

                                                 [http://www.techfactors.ph] TechFactors Inc. ©2005
Self-check
Create a class and describe it in terms of its attributes (data) and functions
(methods). Then, instantiate at least 2 objects. Use the tables below.

   //write the class name here                //write the object name here


                                              //write the data of the object
   //write the data of the class              here
   here
                                              //write the methods of the
                                              object here
   //write the methods of the
   class here
Skills Workout




         Type the Java program given in this
           lesson in the specified package.
           Compile and run it. If errors are
           encountered, debug it.
Lesson 2




           Your First Java
              Program
Welcome.java


public class Welcome{
  public void printWelcome() {
       System.out.println("Welcome to Java!"); //prints_a_msg
  }
}
Explaining Welcome.java

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
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{
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() {
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!");
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
Explaining Main.java


    /*
    This class contains the main() method
      */

     public class Main {
       public static void main(String args[]) {
          Welcome Greet= new Welcome();
          Greet.printWelcome();
       }
     }
Explaining Main.java
Line 1-3
Contains a multi-line comment. Anyting in
 between /* and */ is considered a
 comment.

/*
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.


public class Main {
Explaining Main.java
Line 6
Program execution starts from line 6. The Java
  interpreter should see this main method definition as
  is, except for args which is user defined.



public class Main {
Explaining Main.java
Line 7 shows how an object is defined in Java. Here, the
  object Greet is created. The word “Greet” is user
  defined. (You can even have your name in its place!).
  The general syntax for defining an object in Java is:
 Syntax:
     <class_name> <object_name> =
      new<class_name>(<arguments>);

Example: Welcome Greet= new Welcome();
Explaining Main.java
Line 8
Illustrates how a method of a class is called. If you look
   at the Welcome class, you’ll notice that we declared a
   mehod named printWelcome().By declaring an
   instance of the Welcome class (in tis case, the Greet
   variable is an instance of a Welcome class, courtesy of
   line 7), you can execute the method withi the specific
   class.
Syntax: <class_name>.<method_name>(<arguments>);
 Example:       Greet.printWelcome();
Explaining Main.java
Line 9-10
  }
}
Contains wo closing braces. The brace on line 9 closes
  the main method and brace on line 10 indicates the
  end of the scoope of the class Main.
Word Bank

new - used in telling the compiler to create
 an object from the specified class.

public - modifier that indicates a class,
 method, or class variable can be
 accessed by any object or method directly.
End of Lesson 2




             Summary…
Syntax Review
             SYNTAX                                            EXAMPLE/S
package                                          package Group.Student;
<top_package_name>[.<subpackage_name>]*;

import                                           import School.Section.Student;
<top_package_name>[.<subpackage_name>].          import School.Section.*;
<class_name>;

<modifier> class <class_name>                    public class First

<class_name> <object_name> = new <class_name>    Welcome Greet= new Welcome();
(<arguments>);

< package_name>.<class_name> <object_name> =  School.Section.Student Alma = new
new <package_name>.<class_name>(<arguments>); School.Section.Student ();

<modifier> <return_type> <method_name>           public static void main(String args[])
(<argument_list>) { <statements>}                {}
                                                 public void printWelcome( ) { }
                                            [http://www.techfactors.ph] TechFactors Inc. ©2005
Syntax Review

         SYNTAX                            EXAMPLE/S
System.out.println(String);   System.out.println("Welcome to Java!");

System.out.print (String);    System.out.print("Hello");

/*                             /*
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.
                              */
Self-check

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       }
Self-check

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       }
End of Lesson 2




        Laboratory Exercise
Lesson 3




     Data Types, Literals,
       Keywords and
          Identifiers
Magic words
Casting – process of converting a value to the
  type of variable.

Constant – identifier whose value can never be
  changed once initialized.

Identifier – user-defined name for methods,
  classes, objects, variables and labels.
Literals – values assigned to variables or constant

Unicode – universal code that has a unique number to
  represent each character.

Variable – identifier whose value can be changed.

 Java keyword – word used by the Java compiler for
  a specific purpose
Java Keywords




           [http://www.techfactors.ph] TechFactors Inc. ©2005
Java Keywords


  Some key points about Java keywords:
    • const and goto are keywords but are
      not used in Java.
    • true and false are boolean literals that
      should not be used as identifiers.
    • null is also considered a literal but is
      not allowed as an identifier.
Identifiers
Rules for Identifiers:

  •   The first character of your identifier can start with a
      Unicode letter.
  •   It can be composed of alphanumeric characters and
      underscores.
  •   there is no maximum length
  •   create identifiers that are descriptive of their purpose.
  •   Your identifier must have no embedded spaces.
  •   Special characters such as ? and like are not accepted.
Data Types




   Java has two sets of data types:
   • primitive
   • reference (or non-primitive).
Data Types

        Data Type      Default
             boolean   false
             char      „u0000‟
             byte      0
             short     0
             int       0
             long      0
             float     0L
             double    0.0D
Data Types

        Data Type      Examples
             boolean       true
             char      „A‟,‟z‟,‟n‟,‟6‟
             byte          1
             short         11
             int           167
             long          11167
             float         63.5F
             double        63.5
Variables
   Variable Declaration Syntax:
    <data_type> <identifier>;
       Examples:
         boolean Passed;
         char EquivalentGrade’;
         byte YearLevel;
         short Classes;
         int Faculty_No;
         long Student_No;
         float Average;
Variables and Literals

 Variable and Literal Declaration Syntax:
  <data_type> <identifier>=<literal>;



            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;
Variables and Literals

        You can also declare several variables for
         a specific data type in one statement by
         separating each identifier with a comma(,)
Examples:
  boolean Passed =true, Switch;
  char EquivalentGrade=’F’,ch1, ch2;
  byte Bytes, YearLevel =2;
  short SH, Classes =19;
  int Faculty_No =6781, Num1;
  long Student_No =76667, Employee_No, Long1;
  float Average=96.89F, Salary;
  double Logarithm=0.8795564564, Tax, SSS;
  String LastName=”Your LastName”,FirstName=”Your FirstName”,
  MiddleName;
Constants
Example:
  static final String Student_ID=”098774656”;



Syntax for declaring constants:

  static final <type> <identifier> =
    <literal>;
  final <type> <identifier> = <literal>;
Type Conversion/ Casting

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.
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);
  }
}
End of Lesson 3




             Summary…
Self-check
I. Write I if the given is not an acceptable Java identifier on the space provided
    before each number. Otherwise, write V.
________________ 1.) Salary
________________ 2.) $dollar
________________ 3.) _main
________________ 4.) const
________________ 5.) previous year
________________ 6.) yahoo!
________________ 7.) else
________________ 8.) Float
________________ 9.) <date>
________________10.) 2_Version

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! „);
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
    }
}
End of Lesson 10




   LABORATORY EXERCISE
Lesson 4




           Java Operators
Operators




            •   Unary
            •   Binary
            •   Ternary
            •   Shorthand
Arithmetic Operator


                 Operators
                      +    Addition
                      -    Subtraction
                      *    Multiplication
                      /    Division
                      %    Modulo
                      ++   Increment
                      --   Decrement
The Arithmetic_operators program
package 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;
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);
  }
}
The Arithmetic_operators program output




                                [http://www.techfactors.ph] TechFactors Inc. ©2005
Relational Operator




               >      Greater than
               >=     Greater than or equal to
               <      Less than
               <=     Less than or equal to
               ==     Equal to
               !=     Not Equal to
The Relational_operators program


package Group.Lesson4.Relational;

public class Relational_operators
{

  public Relational_operators() { }// Constructor for objects of class
Relational_operators

  public static void main(String[] args)//execution begins here
  {
    //local variables
    int x = 5, y = 7;
    boolean Relational_Equal=false, Relational_NotEqual=false;
    boolean Relational_LessThan=false, Relational_LessThanOrEqualTo=false;
    boolean Relational_GreaterThan=false;
    boolean Relational_GreaterThanOrEqualTo=false;
The Relational_operators program (Continued)
    //evaluate expressions
    Relational_Equal=          x==y;
    Relational_NotEqual=        x!=y;
    Relational_LessThan=         x<y;
    Relational_LessThanOrEqualTo= x<=y;
    Relational_GreaterThan=        x>y;
    Relational_GreaterThanOrEqualTo= x>=y;
    //print results
    System.out.println("x=5 y=7");
    System.out.println("x==y "+Relational_Equal);
    System.out.println("x!=y "+Relational_NotEqual);
    System.out.println("x<y "+Relational_LessThan);
    System.out.println("x<=y
"+Relational_LessThanOrEqualTo);
    System.out.println("x>y "+Relational_GreaterThan);
    System.out.println("x>=y
"+Relational_GreaterThanOrEqualTo);
  }
}
The Relational_operators program output




                              [http://www.techfactors.ph] TechFactors Inc. ©2005
Logical Operator



 Operators         Description
 !                 NOT
 ||                OR
 &&                AND
 |                 short-circuit OR

 &                 short-circuit AND
Logical Operator- Truth Tables


 The NOT (!) operator


          Operand1               RESULT


 !           true                 false
 !           false                true
Logical Operator- Truth Tables


 The OR (|) operator


  Operand1              Operand2    RESULT

      true         |         true       true
      true         |        false       true
      false        |         true       true
      false        |        false      false
Logical Operator- Truth Tables


 The XOR (^) operator


  Operand1              Operand2    RESULT

         true       ^        true      false
         true       ^       false      true
        false       ^        true      true
        false       ^       false      false
Logical Operator- Truth Tables


 The AND (&) operator
  Operand1            Operand2    RESULT


       true       &        true      true
       true       &       false      false
       false      &        true      false
       false      &       false      false
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_ShortCircuit= (x<y)| (x++==y);
    System.out.println("(x<y)| (x++==y) "+Logical_OR_ShortCircuit);

    Logical_OR=           (x<y)||(x++==y);
    System.out.println("(x<y)| (x++==y) "+Logical_OR);
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);

Logical_XOR=           (x>y)^ (x++==y);
System.out.println("(x>y)^ (x++==y) "+Logical_XOR);

System.out.println("!((x>y)^ (x++==y)) "+!Logical_XOR);//NEGATE
  }
The Logical_operators program output




                             [http://www.techfactors.ph] TechFactors Inc. ©2005
REVIEW
 RECALL: How do you get the equivalent of a certain number in bits?
ANSWER: You divide the number by 2 until you reach 0. Jot down the
   remainder for each division operation and that‟s the equivalent.

     RECALL: How do you convert a bit sequence to integer?
  ANSWER: You multiply each bit by powers of 2. Then, add all the
               products to get the equivalent.
               RECALL: How many bits does an integer have?
                                   ANSWER: 16 bits


        Try converting 16 and 27 to bits.

          Hope you got these answers:
           16=0000000000010000
           27=0000000000011011
REVIEW

    If you have a negative number, you still
have to convert the same way you would if it
were a positive number. Then, get the
complement and add 1. That‟s it!



                  Example:
             4=0000000000000100
            -4=1111111111111100
Bitwise Operator

           Operators   Description
           ~           Complement
           &           AND
           |           OR
           ^           XOR (Exclusive OR)
           <<          Left Shift
           >>          Right Shift
           >>>         Unsigned Right Shift
Bitwise Operator - Truth Tables


 The BITWISE COMPLEMENT

          Operand1                RESULT




~             1                     0

~             0                     1
Bitwise Operator - Truth Tables


 The BITWISE OR (|)

Operand1              Operand2    RESULT


      1           |          1        1
      1           |          0        1
      0           |          1        1
      0           |          0        0
Bitwise Operator - Truth Tables


 The BITWISE XOR (^)

   Operand1             Operand2   RESULT

         1          ^         1        0
         1          ^         0        1
         0          ^         1        1
         0          ^         0        0
Bitwise Operator - Truth Tables


 The BITWISE AND (&)
            Operand1         Operand2   RESULT


                 1       &        1        1
                 1       &        0        0
                 0       &        1        0
                 0       &        0        0
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= 1111111111111111
x=   0000000000010000    Right_shift= -1
y=   0000000000011011
And= 0000000000010000    Negative=1111111111111100
                         Negative=0011111111111111
x=   0000000000010000    Negative= 1073741823
y=   0000000000011011
Xor= 0000000000001011
The Bitwise_operators program
package Group.Lesson4.Bitwise;

public class Bitwise_operators
{
   //Constructor for objects of class Bitwise_operators
  public Bitwise_operators() {       }
  public static void main(String[] args)//execution begins here
  {
     //local variables
     int x = 16 , y = 27, z=-4, Negative=-4;
     int Complement=0,Or=0,And=0,Xor=0,Left_shift=0;
     int Right_shift=0, Unsigned_Right_shift=0;
     //operations
     Complement           = ~x;
     Or              = x|y;
     And              = x&y;
     Xor             = x^y;
     Left_shift        = x<<3;
     Right_shift        = z>>2;
     Unsigned_Right_shift= Negative>>>2;
The Bitwise_operators program (continued)


//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);
   }
}
The Bitwise_operators program output
Shorthand Operator with Assignment

           Operators     Description
           +=            Assignment With Addition
           -=            Assignment With Subtraction
           *=            Assignment With Multiplication
           /=            Assignment With Division
           %=            Assignment With Modulo
           &=            Assignment With Bitwise And
           |=            Assignment With Bitwise Or
           ^=            Assignment With Bitwise XOR
           <<=           Assignment With Left Shift
           >>=           Assignment With Right Shift
           >>>=          Assignment With Unsigned Right
                         Shift
The Shorthand_operators program
package Group.Lesson4.Shorthand;
public class Shorthand_operators
{ //Constructor for objects of class Shorthand_operators
  public Shorthand_operators(){ }
  public static void main(String[] args)//execution begins here
  { //local variables
     int Assign_With_Addition=4, Assign_With_Subtraction=4, Assign_With_Multiplication=4;
     double Assign_With_Division=7;
     int Assign_With_Modulo=7,        Assign_With_Bitwise_And=7;
     int Assign_With_Bitwise_Or=23, Assign_With_Bitwise_XOR=23, Assign_With_LeftShift=23;
     int Assign_With_RightShift=10, Assign_With_UnsignedRightShift=10;
     Assign_With_Addition           +=2;
     Assign_With_Subtraction          -=2;
     Assign_With_Multiplication       *=2;
     Assign_With_Division           /=2;
     Assign_With_Modulo              %=2;
     Assign_With_Bitwise_And           &=2;
     Assign_With_Bitwise_Or           |=2;
     Assign_With_Bitwise_XOR            ^=2;
     Assign_With_LeftShift          <<=2;
     Assign_With_RightShift          >>=2;
     Assign_With_UnsignedRightShift >>>=2;
     System.out.println("                           Results");
The Shorthand_operators program (continued)



        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);
    }
}
The Shorthand_operators program output
Operator Precedence
Word Bank



             expression
             boolean expressions
             truth value
             truth table
             shorthand operators
             bit
             sign bit
End of Lesson 4




             Summary…
Self-check

Evaluate the given expressions/statements. Write
the result on the blanks provided before each
number. Given that a=3, b=4,c=6.


             1.x=a++;
             2.y=--b;
             3.!((++a)!=4)&&(--b==4))
             4.(c++!=b)|(a++==b)
             5.t=a+b*c/3-2;
Lesson 5




           Decisions
Decision making
In life we make decisions. Many
  times our decision are based on
  how we evaluate the situation.
  Certain situation need to be
  evaluated carefully in order to
  make the correct results or
  decision.
In Java , decisions are made using
  statements like if, if else, nested-if
  and switch.
In this lesson , we will examine hot
  these conditional statements are
  applied to simple programming
  problems.
Decision Statements              If Statement:
    public class If_Statement
    {
    public static void main (String [] args)
      {
          int x = 0;
          System.out.println ("Value is:" + x);
          if(x%2==0)
          {
              System.out.println ("VAlue is an even number.");
            }
            if (x%2 ==1)
            {
                System.out.println ("Value is an odd number.");
            }
        }
    •     }
Wrapper Class

           Primitive Data   Wrapper Class
           Type
           boolean          Boolean
           char             Character
           byte             Byte
           short            Short
           int              Integer
           long             Long
           float            Float
           double           Double
if Statement

         Syntax:
                  if (<boolean condition is true>)
                  {
                      <statement/s>
                  }


               Example:
                 if(x!=0){
                         x=(int)x/2;
                       }
The If_Statement program
package Lesson5.If;
import java.io.*;
public class If_Statement
{
  //Constructor for objects of class If_Statement
  public If_Statement(){ }

    public static void main(String[] args) throws IOException
    {
      BufferedReader dataIn=new BufferedReader(new InputStreamReader(System.in));

        int x=0;
        String Str_1;

        System.out.print("Enter an integer value: ");
        Str_1=dataIn.readLine();
        x=Integer.parseInt(Str_1);
        if(x!=0){
            x=(int)x/2;
        }
        System.out.println("x= "+x);
    }
}
if-else Statement

 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>
                        }
The IfElse program
package Lesson5.If_Else;

import java.io.*;

public class IfElse {
  public IfElse() { }
  public static void main(String[] args)throws IOException
  {
     BufferedReader dataIn=new BufferedReader(new InputStreamReader(System.in));
     //declare local variables
     int A=0;
     String Str_A;
     //input
     System.out.print("Enter an integer value for A: ");
     Str_A=dataIn.readLine();
     A=Integer.parseInt(Str_A);
     //determine if input is odd or even and print
     if (A%2==0) {
         System.out.println (A+" is an EVEN number");
     } else {
         System.out.println (A+" is an ODD number");
     }
  }
}
nested-if Statement

             Syntax:
                 if (<boolean condition is true>){
                 <statement/s>
                 }
                 else if (<boolean condition is true>) {
                 <statement/s>
                 }
                 else
                 {
                 <statement/s>
                 }
nested-if Statement



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);
}
The NestedIf program and output
public class NestedIf {
  public NestedIf() { }
  public static void main(String[] args)throws IOException
  {
     BufferedReader dataIn=new BufferedReader(new InputStreamReader(System.in));
     //declare local variables
     double number1=0.0,number2=0.0;
     String Str_number1,Str_number2;
     //input Str_number1 and convert it to an integer (number1)
     System.out.print("Enter a number: ");
     Str_number1=dataIn.readLine();
     number1=Double.parseDouble(Str_number1);
     //input Str_number2 and convert it to an integer (number2)
     System.out.print("Enter another number: ");
     Str_number2=dataIn.readLine();
     number2=Double.parseDouble(Str_number2);
     //determine if number1 is greater than, less than or equal to number2
     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);
     }
  }
}
switch Statement

             Syntax:
                   switch(<expression>) {
                   case <constant1>:
                      <statements>
                      break;
                   case <constant2>:
                      <statements>
                      break;
                      :
                      :
                   default:
                      <statements>
                      break;
                   }
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;
     }
The Switch_case program
public Switch_case(){ }//Constructor for objects of class Switch_case
  public static void main(String[] args) throws IOException{
     BufferedReader dataIn=new BufferedReader(new
InputStreamReader(System.in));
     int month=0;
     String Str_month;
     System.out.print("Enter month [1-12]: ");
     Str_month=dataIn.readLine();
     month=Integer.parseInt(Str_month);
     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");
          break;
        case 4:System.out.println("April has 30 days");
          break;
        case 5:System.out.println("May has 31 days");
          break;
The Switch_case program (continued) and output
case 6:System.out.println("June has 30 days");
  break;
case 7:System.out.println("July has 31 days");
  break;
case 8:System.out.println("August has 31 days");
  break;
case 9:System.out.println("September has 30 days");
  break;
case 10:System.out.println("October has 31 days");
  break;
case 11:System.out.println("November has 30 days");
  break;
case 12:System.out.println("December has 31 days");
  break;
default:System.out.println("Sorry that is not a valid month!");
  break;     }}}
Word Bank




             Wrapper class
End of Lesson 5




             Summary…
End of Lesson 10




   LABORATORY EXERCISE
Syntax Review
        SYNTAX                             EXAMPLE/S
if (<boolean condition is   if(x!=0){
true>) {                            x=(int)x/2;
<statement/s>               }
}
if (<boolean condition is   if (A%2==0) {
true>){                          System.out.println (A+" is EVEN");
<statement/s>               }
}                           else
else                         {
 {                               System.out.println (A+" is ODD ");
<statement/s>               }
}
SYNTAX                                               EXAMPLE/S
Syntax Review
if (<boolean condition is true>){         if (number1>number2) {
<statement/s>                                  System.out.println (number1+" is greater than "+number2);
}                                          } else if (number1<number2){
else if (<boolean condition is true>) {            System.out.println (number1+" is less than "+number2);
<statement/s>                              } else {//number1==number2
}                                                  System.out.println (number1+" is equal to "+number2);
else{                                      }
<statement/s>
}


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;
}
Self-check



       In the next slide is a simple Java program
that will determine if a number is zero, positive or
negative then print the appropriate message on
the screen. Fill the missing portions with the
correct code. Type the program, then compile and
run it.
Self-check
 public class NestedIf {
   public NestedIf() { }//constructor
   public static void main(String[] args)
   {
      int number=3;

         if (__________) // FILL-IN THE BLANK
         {
             System.out.println (number+” is ZERO!”);
         }
          else if (___________) //FILL-IN THE BLANK
          {
             System.out.println (number+" is a POSITIVE number!”);
         }
          else
         {
             System.out.println (number+" is a NEGATIVE number!”);
         }
     }
 }
Lesson 6




           Loops
General Topics




   • for structure
   • while structure
   • do-while structure
loop




       A loop is a structure in Java that
          permits a set of instructions to
          be repeated
 The for loop is usually used when the number of
 iterations that needs to be done is already
 known.

 The while loop checks whether the prerequisite
 condition to execute the code within the loop is
 true or not. If it is true, then the code loop is
 executed.

 The do-while loop executes the code within it
 first regardless of whether the condition is true or
 not before testing the given condition.
3 Main Parts of for loop
Initialization - initial values of variables
     that will be used in the loop.
Test condition - a boolean expression that
     should be satisfied for the loop to
     continue executing the statements
     within the loop’s scope; as long as the
     condition is true.
Increment/Operations- dictates the change
     in value of the loop control variable
     everytime the loop is repeated.
for loop
    Example:
      for(int Ctr=1;Ctr<=5;Ctr++){
         System.out.println(Ctr);
       }


  Syntax:
       for (<initialization>;<condition>;<increment>)
       {
           <statement/s>
       }
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);
     }
  }
}
while loop
      Example:
             int Ctr=1;
             while(Ctr<=5){
                    System.out.println(Ctr);
                    Ctr++;
             }

             Syntax:
                  while (boolean condition is true)
                         {
                         <statement/s>
                         }
Sample Code and output

public class While_Loop
{
  //Constructor for objects of class While_loop
  public While_Loop() { }

    public static void main(String[] args)
    {
      int Ctr=1;
      while(Ctr<=5){
         System.out.println(Ctr);
         Ctr++;
      }
    }
}
do-while loop
    Example:
          int Ctr=1;
          do{
                 System.out.println(Ctr);
                 Ctr++;
           }while(Ctr<=5);

            Syntax:
            do {
                         <statement/s>
            } while (<boolean condition is true>);
Sample Code

public class DoWhile
{
  public DoWhile() { }
  public static void main(String[] args)
   {
     int Ctr=1;
     do{
         System.out.println(Ctr);
         Ctr++;
     }while(Ctr<=5);
   }
}
End of Lesson 6




             Summary…
Self-check




             In the next slides are three
             simple Java programs. Fill
             the missing portions with
             the correct code. Type the
             programs, compile and run
             them.
Self-check (For_loop2)

             public class For_loop2
             {
               //Constructor for objects of class For_loop2
               public For_loop2() { }
               /**
                * main()-prints all even numbers from 1-10
             automatically using a for loop
                *
                * @param        String[] args
                * @return      nothing
                */
               public static void main(String[] args)
               {
                   for(int Ctr=____;Ctr<=_____;Ctr____){
                     System.out.println(Ctr);
                   }
               }
             }
Self-check (DoWhile2)
             public class DoWhile2
             {
               //Constructor for objects of class DoWhile2
               public DoWhile2() { }
               /**
                * main()-prints the numbers 1-10 automatically
             using a do_while loop
                *
                * @param       String[] args
                * @return     nothing
                */
               public static void main(String[] args)
               {
                   int Ctr=________;
                   do{
                      System.out.println(Ctr);
                      Ctr______;
                   }while(Ctr<=_________);
               }
             }
Self-check (While_Loop2)
             public class While_Loop2
             {
               //Constructor for objects of class While_loop2
               public While_Loop2() { }
               /**
                * main()-prints odd numbers from 2 to 20
             automatically using a while loop
                *
                * @param       String[] args
                * @return     nothing
                */
               public static void main(String[] args)
               {
                   int Ctr=____________;
                   while(Ctr<=__________){
                      System.out.println(Ctr);
                      Ctr_______________;
                   }
               }
             }
End of Lesson




   LABORATORY EXERCISE
More Loops
General Topics




                 •   Nested loops
                 •   continue
                 •   break
Nested_For loops

    The Nested_For program prints the multiplication
        table. To do this, it has two loops. One loop is
        inside the other. This is why it is called a nested
        loop.
Nested_For loops

           public class Nested_For
           {
             // Constructor for objects of class Nested_For
             public Nested_For(){ }

               public static void main(String [] args)
               {
                 for(int Row=1;Row<=10;Row++){
                    for(int Column=1;Column<=10;Column++){
                       System.out.print(Row*Column+"t");
                    }
                    System.out.println();
                 }
               }
           }
Nested_For loops – how it behaves
       To see how this program behaves at any given time,
    we need to set breakpoints. To do that, just click on
    line number.




    Click on line 15.
Nested_For loops – how it behaves

    Run the program by right-clicking on the Nested_For
        icon, click on void main(String [] args).




          Then, click on the
          Ok button.
Nested_For loops – how it behaves




                    – how it behaves
Nested_For loops – how it behaves
Nested_For loops – Output
Continue_Loop

   The difference is the
  inclusion of the if
  statement on line 17
  and the continue
  statement on line 18.
Continue_Loop
         public class Continue_Loop
         {
           // Constructor for objects of class Continue_Loop
            public Continue_Loop(){ }

             public static void main(String [] args)
             {
                for(int Row=1;Row<=10;Row++){
                  for(int Column=1;Column<=10;Column++){
                     if(Column==4){
                        continue;
                     }
                     System.out.print(Row*Column+"t");
                  }
                  System.out.println();
               }
             }
         }
Continue_Loop - Output




         The column containing the multiples of 4 is not included.
Loop_Break
This program is again
similar to the previous
programs in this lesson,
except for the inclusion
of the if and break
statements. The output
shows 3 columns only.
Loop_Break
        public class Loop_Break
        {
          //Constructor for objects of class Loop_Break
          public Loop_Break(){ }

             public static void main(String [] args)
             {
               for(int Row=1;Row<=10;Row++){
                  for(int Column=1;Column<=10;Column++){
                     if(Column==4){
                        break;
                     }
                     System.out.print(Row*Column+"t");
                  }
                  System.out.println();
               }
             }
        }
Labels
         public class Labels
         {
                  //Constructor for objects of class Labels
                  public Labels() {         }

           public static void main(String [] args)
           {
          here: for(int Row=1;Row<=10;Row++){
                 for(int Column=1;Column<=10;Column++){
                    System.out.print(Row*Column+"t");
                    if(Column==4){
                       break here;
                    }
                 }
                 System.out.println();
              }
           }
         }
Word Bank




            Nested loops
Self-check
I. A Java program that prints the multiplication table is given using nested
while loops. Fill-in the missing portions.
             public class Multiplication_Table
             {
               // Constructor for objects of class Multiplication_Table
                public Multiplication_Table (){ }
                public static void main(String [] args)
                {
                    int Row=_______;        //indicate the initial value
                    while(Row<____){
                                    Row++;
                                    int Column=_____;              //indicate the initial
             value
                      while(Column<_____){
                                            Column++;
                         System.out.print(Row*Column+"t");
                      }
                      System.out.println();
                   }
                }
             }
Self-check

 II. A Java program that prints the given output using nested do-while loops.
 Fill-in the missing portions.
Self-check
     public class Table{
       // Constructor for objects of class Table
        public Table(){ }
        public static void main(String [] args) {
             int Row=_______; //indicate the initial value
             do{
                         Row++;
                         int Column=_____;       //indicate the
     initial value
               do{
                                Column++;
                                if(_______){
                                        continue;
                                }
                  System.out.print(Row*Column+"t");
               } while(Column<_____);
               System.out.println();
            } while(Row<____);
        }
     }
LESSON 7
 Exceptions
Exceptions

 Unexpected errors or events within our
  program
import java.io.*;
public class Exception1{
public static void main(String[] args){
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
    int x=0;
    String Str_1;
    System.out.print(“Enter an integer value:”);
    try{
         Str_1 = dataIn.readLine();
         x = Integer.parseInt(Str_1);
    }
    catch(Exception e){
         System.out.println(“Error reported”);
    }
    x = (int)x/2;
    System.out.println(“x= ”+x);
}
}
import java.io.*;
public class Exception2{
public static void main(String[] args){
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
int x=0, y=0;
String Str_1, Str_2;
System.out.print(“Enter an integer value: ”);
try{
   Str_1 = dataIn.readLine();
   System.out.print(“Enter another value: ”);
   Str_2 = dataIn.readLine();
   x = Integer.parseInt(Str_1);
   y = Integer.parseInt(Str_2);
   x = x/y;
}
catch(ArithmeticException e){
   System.out.println(“Divide by zero error.”);
}
catch(NumberFormatException e){
   System.out.println(“Invalid number entered.”);
}
catch(Exception e){
   System.out.println(“Invalid number entered.”);
}
finally{
   System.out.println(“x= ”+x);
}
}
}
Exceptions

 Exception classes
 try
 catch
 finally
Exception classes

 Help handle errors
 Included within Java installation package
try-catch

 At least one catch for every try
 catch statements should catch different
  exceptions
 try-catch order
 catch immediately after a try
End of Lesson




   LABORATORY EXERCISE
Lesson 8




           Classes
General Topics


                 •   Classes
                 •   Inheritance
                 •   Interface
                 •   Objects
                 •   Constructors
                 •   Overloading Methods
                 •   Overriding Methods
Classes
Accessibility
Syntax

<modifier> class <class_name>
[extends <superclass>] {
     <declaration/s>
}


         Example:

         public class Student extends Person
Syntax
         <modifier> class <name>
         [extends <superclass>]
         [implements <interfaces>] {
             <declaration/s>
         }
         Example:
             public class Teacher
             extends Person
             implements Employee
Syntax



         <modifiers> class
         <class_name>{
              [<attribute_declarations>]
              [<constructor_declarations>]
              [<method_declarations>]
         }
The Person program
  package Lesson8;
  public class Person extends Object
  {
    private String name;
    private int age;
    private Date birthday;
    // class constructor
    public Person() {
        name = "secret";
        age = 0;
        birthday = new Date(7,7);
    }
    //overloaded constructor
    public Person(String name, int age, Date birthday){
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }
The Person program (continued)
//accessor methods - setters
   public void setName(String X){
     name= X;
   }
   public void setAge(int X) {
      age=X;
   }
   public void setBirthday(Date X){
      birthday=X;
   }
   public void setDetails(String X, int Y, Date Z){
      name= X;
      age=Y;
      birthday = Z;
   }
 //accessor methods - getters
   public String getName(){
      return name;
   }
The Person program (continued)
public int getAge(){
  return age;
  }

  //this method greets you on your bday and increments age
  public void happyBirthday(Date date){
         System.out.println("Today is
"+date.month+"/"+date.month+"/2005.");
     if (birthday.day == date.day && birthday.month == date.month){
         System.out.println("Happy birthday, "+ this.name + ".");
         age++;
         System.out.println("You are now "+age+" years old.");
     }
     else {
         System.out.println( "It's not " + this.name + "'s birthday today.");
     }
  }
}
The Someone program
package Lesson8;
public class Someone
{
  public static void main (String args[]){
     Date dateToday = new Date(3,7);
     Date bdayLesley= new Date(23,10);
     Person Angelina=new Person();
     Student Stevenson = new Student("Stevenson",20,new Date(22,10),4);
     Student Allan =new Student(3);
     Teacher Lesley= new Teacher("Lesley",28,bdayLesley,14000.25);

      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));
  }
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;
  }
The Date program (continued)
//Constructor for objects of class Date with day & month as parameters
   public Date(int this_Day,int this_Month)
   { // initialise instance variables
     if((this_Month>=1)&&(this_Month<=12)){
         month=this_Month;
         switch(month){
            case 1: case 3: case 5: case 7: case 8: case 10:
            case 12:if((this_Day>=1)&&(this_Day<=31)){day = this_Day;}
                 else {day=1;}
                 break;
            case 4: case 6: case 9:
            case 11:if((this_Day>=1)&&(this_Day<=30)){ day = this_Day;}
                 else {day=1;}
                 break;
            case 2:if((this_Day>=1)&&(this_Day<=28)){day = this_Day;}
                 else {day=1;}
                 break;
         }
     } else { month=1; }
     year=2005; }
The Date program (continued)



public void print_Date(){//prints the date mm/dd/yyyy
     System.out.println(month+"/"+day+"/"+year); }
}
The Student program
 package Lesson8;
 public class Student extends Person
 {
   private int yearlvl;
   //constructors
   public Student(){
      super();
      yearlvl=1;
   }
   public Student(int yearlvl) {
      super();
      if((yearlvl<=4)&&(yearlvl>=1)){
          this.yearlvl=yearlvl;
      } else {
          this.yearlvl=1;
      }
   }
The Student program (continued)

public Student(String name, int age, Date birthday, int
yearlvl){
     super(name, age, birthday);
     if((yearlvl<=4)&&(yearlvl>=1)){
         this.yearlvl=yearlvl;
     } else {
         this.yearlvl=1;
     }
     System.out.print("Hi, "+name+". ");
     System.out.print(“Your birthday this year is on ");
     birthday.print_Date();
     System.out.println("You are "+age+" years old.");
     System.out.println();
  }
The Student program (continued)
//accessor methods
  public void setYearlvl(int yearlvl){
     if((yearlvl<=4)&&(yearlvl>=1)){
         this.yearlvl=yearlvl;
     } else {
         this.yearlvl=1;
     }
  }
  public void setDetails(String name, int age, Date birthday){
     super.setDetails(name,age,birthday);
     System.out.print("Hello, "+name+". ");
     System.out.print("Your birthday this year is on ");
     birthday.print_Date();
     System.out.println("You are "+age+" years old.");
     System.out.println();
  }
The Student program (continued)
 public void setDetails(String name, int age, Date birthday, int
yearlvl){
     super.setDetails(name,age,birthday);
     if((yearlvl<=4)&&(yearlvl>=1)){
         this.yearlvl=yearlvl;
     } else {
         this.yearlvl=1;
     }
     System.out.print("Hello, "+name+". ");
     System.out.print(" Your birthday this year is on ");
     birthday.print_Date();
     System.out.println("You are "+age+" years old.");
     System.out.println();
   }
   public int getYearlvl(){
     return yearlvl;
   }
}
The Teacher program

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;
  }
The Teacher program (continued)


public Teacher(String name, int age, Date birthday, double salary){
     super(name, age, birthday);
     this.salary= salary;
     System.out.println("Good morning, "+name+". Your salary is "+salary+".");
     System.out.println(" Your birthday this year is on ");
     birthday.print_Date();
     System.out.println("You are "+age+" years old.");
     System.out.println();
  }
  //accessor methods
  public void setSalary(double salary) {
     this.salary = salary;
  }
The Teacher program (continued)


 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;
  }
}
The Employee program


package Lesson8;
public interface Employee
{
  public void setSalary(double salary);
  public void setDetails(String name, int age, Date birthday, double salary);
  public double getSalary();
}
Word Bank

   Superclass
   Subclass
   Inheritance
   Interface
   Method
   Signature
   Overloading Constructor
   Overriding Method
End of Lesson 8




              SUMMARY
Syntax Review

  The constructor of the superclass that has no
   parameters can be called this way:
  super ( );
  The constructor of the superclass that has
   parameters can be called this way:
  super (<argument list> );
  The syntax to call a method of the superclass is:
  super.<method_name> (<argument list> );
Syntax Review



SYNTAX                          EXAMPLE/S
<modifier> class <class_name>   public class Student
[extends <superclass>]
                                extends Person

<modifier> class <name>         public class Teacher
[extends <superclass>]          extends Person
[implements <interfaces>]
                                implements Employee
Syntax Review (continued)

 SYNTAX                                 EXAMPLE/S


 <modifiers> class <class_name>{         public class Person extends Object{
         [<attribute_declarations>]       //attribute declarations
                                            private String name;
         [<constructor_declarations>]
                                            private int age;
         [<method_declarations>]            private Date birthday;
 }                                          // class constructor
                                            public Person() {
                                               name = "secret";
                                               age = 0;
                                               birthday = new Date(7,7);
                                            }
                                        //accessor methods - setters
                                            public void setName(String X){
                                              name= X;
                                            }
                                        }
Self-check 1
I. Use the applications given on our lesson for exercise A and B.

                  A. Supply all the method signatures of Student to the
                     interface Learner, except for the constructors.

                       public interface Learner{




                       }

                  B. Create a constructor for Person with name and
                     age as parameters. Make sure that you assign
                     values to all the attributes of the class Person.
Self-check 2
II. Use this diagram in answering the next exercises.
Self-check

A. Supply all the method signatures
of Plane to the interface
FlyingObject, except for the
constructors.




                public interface FlyingObject{




                }
End of Lesson




   LABORATORY EXERCISE
Lesson 9




           Arrays
General Topics




                 • Single-dimensional arrays

                 • Array of Objects

                 • Multidimensional arrays
The Single_Array program
public class Single_Array
{
  //Constructor for objects of class Single_Array
  public Single_Array() { }
  public static void main(String[] args){
     int [] GradeLevel=new int [6];
     int [] YearLevel={1,2,3,4};
     System.out.print("The contents of the YearLevel array: ");
     print_Single_Array(YearLevel);
     System.out.print("The contents of the GradeLevel array: ");
     print_Single_Array(GradeLevel);
     System.arraycopy(YearLevel,0,GradeLevel,1,YearLevel.length);
     System.out.print("The contents of the GradeLevel array after
copying: ");
     print_Single_Array(GradeLevel);
     for(int Index=1;Index<GradeLevel.length;Index++){
           GradeLevel[Index]=Index*2;
     }
     System.out.print("The contents of the GradeLevel array after
assigning values: ");
     print_Single_Array(GradeLevel);
  }
The Single_Array program (continued) and
                     output
public static void print_Single_Array(int[] Array){
     for(int subscript=0;subscript<Array.length;subscript++){
        System.out.print(Array[subscript]); //prints the array
element
        if((subscript+1)<Array.length){ //prints a comma in-
between elements
            System.out.print(", ");
        }
     }
     System.out.println();
   }
}
Single Dimensional Array

SYNTAX:

<data_type> [ ] <array_identifier> = new <data_type>[<no_of_elements>];

<data_type> <array_identifier> [ ] = new <data_type>[<no_of_elements>];



              Example:
                                  First Element       Last Element


                                     [0]    [1]   [2]    [3]

                      YearLevel      1      2     3      4
System.arraycopy


 SYNTAX:

 System.arraycopy(<Array_source>,
 <Array_sourcePosition>,
 <Array_destination>,
 <Array_destinationPosition>,
 <numberOfElements>);
The Date program
package Group.Lesson9.Array_Object;
/**
 * @author Lesley Abe
 * @version 1
 */
public class Date
{ // instance variables - replace the example below with your own
    private int day, month, year;
    //Constructor for objects of class Date with no parameters
    public Date()
    { // initialize instance variables
       day = 1;
       month=1;
       year=2005;
    }
//Constructor for objects of class Date with day & month as parameters
The Date program (continued)
public Date(int this_Day,int this_Month)
  { // initialise instance variables
     if((this_Month>=1)&&(this_Month<=12)){
         month=this_Month;
         switch(month){
            case 1: case 3: case 5: case 7: case 8: case 10:
            case 12:if((this_Day>=1)&&(this_Day<=31)){day = this_Day;}
                else {day=1;}
                break;
            case 4: case 6: case 9:
            case 11:if((this_Day>=1)&&(this_Day<=30)){ day = this_Day;}
                else {day=1;}
                break;
            case 2:if((this_Day>=1)&&(this_Day<=28)){day = this_Day;}
                else {day=1;}
                break;
         }
     } else { month=1; }
     year=2005;
  }
The Date program (continued)


public static void main(String[] args)
  {
     Date[] Birthdays={ new Date(23,10), new Date(22,3) };
     Date[] Holidays=new Date[4];
     Holidays[0]=new Date(25,12);
     Holidays[1]=new Date(1,5);
     Holidays[2]=new Date(1,11);
     Holidays[3]=new Date(1,1);
  }
}
The Two_Dimensional_Array program
public class Two_Dimensional_Array
{ //Constructor for objects of class Two_Dimensional_Array
  public Two_Dimensional_Array() { }
  public static void main(String[] args)
  {
     final int YearLevel=4; // this is a constant
     final int Section=2; //this is a constant
     String TeacherName [] [] = new String [YearLevel] [Section];
     String Student [] [] = new String [YearLevel] [ ]; //non-rectangular array
     //String Student [] [] = new String [] [YearLevel]; //this is illegal!
     //assign teachers to all the classes in high school
     TeacherName [0] [0] = "Lesley Abe";
     TeacherName [0] [1] = "Arturo Jacinto Jr.";
     TeacherName [1] [0] = "Olive Hernandez";
     TeacherName [1] [1] = "Alvin Ramirez";
     TeacherName [2] [0] = "Christopher Ramos";
     TeacherName [2] [1] = "Gabriela Alejandra Dans-Lee";
     TeacherName [3] [0] = "Joyce Cayamanda";
     TeacherName [3] [1] = "Ana Lisa Galinato";
The Two_Dimensional_Array program (continued)
//indicate how many student assistants per year level
      Student [0]=new String [2];
      Student [1]=new String [2];
      Student [2]=new String [1];
      Student [3]=new String [1];
      //assign student assistants per year level
      Student [0] [0]= "Stevenson Lee";
      Student [0] [1]= "Brian Loya";
      Student [1] [0]= "Joselino Luna";
      Student [1] [1]= "Allan Valdez";
      Student [2] [0]= "John Dionisio";
      Student [3] [0]= "Geoffrey Chua";
    }
}
The Two_Dimensional_Array program
 (continued)

public static void main(String[] args)
  {
     Date[] Birthdays={ new Date(23,10), new
Date(22,3) };
     Date[] Holidays=new Date[4];
     Holidays[0]=new Date(25,12);
     Holidays[1]=new Date(1,5);
     Holidays[2]=new Date(1,11);
     Holidays[3]=new Date(1,1);
  }
}
Multi-Dimensional Array
SYNTAX:

 <data_type> [ ][ ] <array_identifier> =
 new <data_type>[<size1>][<size2>];

 <data_type> <array_identifier> [ ] [ ]
 = new
 <data_type>[<size1>][<size2>];
Word Bank
End of Lesson 9




              SUMMARY
Syntax Review
SYNTAX                                              EXAMPLE/S

<data_type> [ ] <array_identifier> = new            int [ ] GradeLevel=new int [6];
<data_type>[<no_of_elements>];
<data_type> < array_identifier> [ ] = new           int GradeLevel [ ] =new int [6];
<data_type>[<no_of_elements>];
<data_type> [ ] < array_identifier> = {< elements   int [ ] YearLevel={1,2,3,4};
separated by commas>};
< array_identifier> [<Index>] = <value>;            GradeLevel[Index]=Index*2;
<data_type> [ ][ ] <array_identifier> = new         String [ ] [ ] TeacherName = new String
<data_type>[<size1>][<size2>];                      [YearLevel] [ ];
<data_type> <array_identifier> [ ] [ ] = new        String TeacherName [ ] [ ] = new String
<data_type>[<size1>][<size2>];                      [YearLevel] [Section];

< array_identifier> [<Index1>] [<Index2>] =         TeacherName [0] [0] = "Lesley Abe";
<value>;
System.arraycopy(<Array_source>,                    System.arraycopy(YearLevel,0,GradeLev
<Array_sourcePosition>, <Array_destination>,        el,1,YearLevel.length);
<Array_destinationPosition>,
<numberOfElements>);
Self-check 1
public class Array1
{
  //Constructor for objects of class Array1
  public Array1() { }
  public static void main(String[] args){
     String [] __________={“Math”,”Science”,_________ };
     String [] MyTeachers={______________ };
     System.out.print("Here are my subjects: ");
              print_Array1(MySubjects);
     System.out.print("My favorite subject is: "+________);
     System.out.print("My favorite teacher is: "+________);

   }
//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();
   }
}
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;
         }
      }
  }
}
Self-check 2 (continued)

      What are the values of the following:


           Table[0][0]= ___________
           Table[2][1]= ___________
           Table[1][3]= ___________
           Table[4][4]= ___________
           Table[3][2]= ___________
End of Lesson




   LABORATORY EXERCISE
Lesson 10




            GUI
General Topics




     •   Abstract Window Toolkit (AWT)
          - java.awt package
          - components
           • Containers
           • Layout Managers
Layout

     SYNTAX:
          FlowLayout( )
          FlowLayout(int align)
          FlowLayout(int align, int hgap, int
          vgap)

         Examples:
         setLayout(FlowLayout());
         setLayout(FlowLayout(FlowLayout.LEF
         T));
         setLayout(FlowLayout(FlowLayout.RIG
         HT,23,10));
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));
Layout

    SYNTAX:
      BorderLayout( );




          Examples:
          setLayout(new BorderLayout());
Sample GUI Project
Project Output
The DrawTest program
package Group.Lesson10;
import java.awt.event.*;
import java.awt.*;
public class DrawTest {
  DrawPanel panel;
  DrawControls controls;
  public static void main(String args[]) {
     Frame Shapes = new Frame("Basic Shapes");
     DrawPanel panel = new DrawPanel();
     DrawControls controls = new DrawControls(panel);
     Shapes.add("Center", panel);
     Shapes.add("West",controls);
     Shapes.setSize(400,300);
     Shapes.setVisible(true);
     Shapes.addWindowListener(new WindowAdapter(){
                        public void windowClosing(WindowEvent e) {
                          System.exit(0);
                        }
                      }
                   );
  }
}
The DrawPanel program
package Group.Lesson10;
import java.awt.event.*;
import java.awt.*;
public class DrawPanel extends Panel {
  public static final int NONE = 0;
  public static final int RECTANGLE = 1;
  public static final int CIRCLE = 2;
  public static final int SQUARE = 3;
  public static final int TRIANGLE = 4;
  int mode = NONE;
  public DrawPanel() {
     setBackground(Color.white);
  }
The DrawPanel program (continued)
public void setDrawMode(int mode) {
    switch (mode) {
      case NONE:
      case RECTANGLE:
        this.mode = mode;
      case SQUARE:
        this.mode = mode;
        break;
      case CIRCLE:
        this.mode = mode;
        break;
      case TRIANGLE:
        this.mode = mode;
        break;
    }
      repaint();
  }
The DrawPanel program (continued)

public void paint(Graphics g) {
    if (mode == RECTANGLE) {
         g.fillRect(100, 60, 100,150);
    }
    if (mode == CIRCLE) {
         g.fillOval(100, 90, 100, 100);
     }
     if (mode == SQUARE) {
         g.fillRect(100, 90, 100, 100);
     }
     if (mode == TRIANGLE) {
         int xpoints[] = {90, 150, 210};
         int ypoints[] = {90, 200, 90};
         int points = 3;
         g.fillPolygon(xpoints, ypoints, points);
     }
  }
}
Methods Used


  fillRect(int x, int y, int width, int height)


  fillOval(int x, int y, int width, int height)


  fillPolygon(Polygon p)
The DrawControl program (continued)
package Group.Lesson10;
import java.awt.event.*;
import java.awt.*;
class DrawControls extends Panel implements ItemListener {
   DrawPanel target;
   Panel NorthPanel = new Panel();
   Panel CenterPanel = new Panel();
   Panel SouthPanel = new Panel();
   private static int Shape = 0;
   private static Color targetColor = Color.red;
   public DrawControls(DrawPanel target) {
      this.target = target;
      setLayout(new BorderLayout());
      setBackground(Color.lightGray);
      target.setForeground(Color.red);
      NorthPanel.setBackground(Color.lightGray );
      NorthPanel.setLayout(new GridLayout(6,1));
The DrawControl program (continued)
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));
  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);
   CenterPanel.add(colors);
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);
}
The DrawControl program (continued)



private void onCommand(int btnNUMBER) {
    switch(btnNUMBER){
      case 1:
         target.setForeground(Color.white);
         target.setDrawMode(0);
         break;
      case 2:
         target.setForeground(targetColor);
         target.setDrawMode(Shape);
         break;
    }
 }
The DrawControl program (continued)

public void itemStateChanged(ItemEvent e) {
     if (e.getSource() instanceof Checkbox) {
         Checkbox b = new Checkbox();
         b = (Checkbox)e.getSource();
         if ( b.getLabel().equals("Rectangle") ){
            Shape = 1;
         } else if ( b.getLabel().equals("Circle") ){
             Shape = 2;
         } else if ( b.getLabel().equals("Square") ){
             Shape = 3;
         } else if ( b.getLabel().equals("Triangle") ){
             Shape = 4;
         }
     }
The DrawControl program (continued)
if (e.getSource() instanceof Choice) {
        String choice = (String) e.getItem();
        if (choice.equals("red")) {
            targetColor=Color.red;
        } else if (choice.equals("green")) {
             targetColor=Color.green;
        } else if (choice.equals("blue")) {
             targetColor=Color.blue;
        } else if (choice.equals("pink")) {
             targetColor=Color.pink;
        } else if (choice.equals("orange")) {
             targetColor=Color.orange;
        } else if (choice.equals("black")) {
             targetColor=Color.black;
        }
      }
    }
}
Some Features of AWT


     •    Frames
     •    Checkbox
     •    Checkbox Group: Radio Button
     •    Choice
     •    Button
Word Bank




            •   Abstract Class
            •   Component
            •   Frame
            •   Dialog
            •   Panel
            •   Layout Manager
End of Lesson 10




              SUMMARY
Self-check
package Lesson10;
import java.awt.event.*;
import java.awt.*;
public class MyPanel
{
  public static void main(String args[]) {
     Panel WestPanel = new ________;             // initialize the panels
     Panel CenterPanel = new ________;
     Panel EastPanel = new ________;
     Panel MainPanel = new ________;
     Frame f = new Frame();
     WestPanel.setLayout(new ________); // set panel layout
     ________.____(new Label(" 1 "));            // add item to west panel
     ________.____(new Label(" 2 "));
     ________.____(new Label(" 3 "));
     ________.____(new Label(" 4 "));
     ________.____(new Label(" 5 "));
     ________.____(new Label(" 6 "));
     CenterPanel.add(new Label(" 1 "));
     CenterPanel.add(new Label(" 2 "));
     CenterPanel.add(new Label(" 3 "));
     CenterPanel.add(new Label(" 4 "));
     CenterPanel.add(new Label(" 5 "));
     CenterPanel.add(new Label(" 6 "));
     f.add(WestPanel,___________.______);
     f.add(CenterPanel,BorderLayout.CENTER);
     f.add(new Label("East"),BorderLayout.EAST);
     f.add(new Label("North"),BorderLayout.NORTH);
     f.add(new Label("South"),BorderLayout.SOUTH);
     f.________(250,250);//set the window size
     f.________(true); //allows the panel to be visible
     f._______________(new _____________(){// listen for an event in the window
                       public void windowClosing(WindowEvent e) {
                         System.exit(0);
                       }
                     }
                  );
  }
}
End of Lesson 10




   LABORATORY EXERCISE

More Related Content

What's hot (20)

Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Abstraction
AbstractionAbstraction
Abstraction
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Error managing and exception handling in java
Error managing and exception handling in javaError managing and exception handling in java
Error managing and exception handling in java
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
07 java collection
07 java collection07 java collection
07 java collection
 
Distributed DBMS - Unit 6 - Query Processing
Distributed DBMS - Unit 6 - Query ProcessingDistributed DBMS - Unit 6 - Query Processing
Distributed DBMS - Unit 6 - Query Processing
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php array
Php arrayPhp array
Php array
 
Unit 1 dsa
Unit 1 dsaUnit 1 dsa
Unit 1 dsa
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 

Viewers also liked

Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectOUM SAOKOSAL
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
11 ds and algorithm session_16
11 ds and algorithm session_1611 ds and algorithm session_16
11 ds and algorithm session_16Niit Care
 
Vb.net session 09
Vb.net session 09Vb.net session 09
Vb.net session 09Niit Care
 
15 ooad uml-20
15 ooad uml-2015 ooad uml-20
15 ooad uml-20Niit Care
 
09 iec t1_s1_oo_ps_session_13
09 iec t1_s1_oo_ps_session_1309 iec t1_s1_oo_ps_session_13
09 iec t1_s1_oo_ps_session_13Niit Care
 
Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01Niit Care
 
14 ooad uml-19
14 ooad uml-1914 ooad uml-19
14 ooad uml-19Niit Care
 
Deawsj 7 ppt-2_c
Deawsj 7 ppt-2_cDeawsj 7 ppt-2_c
Deawsj 7 ppt-2_cNiit Care
 
Java Garbage Collection - How it works
Java Garbage Collection - How it worksJava Garbage Collection - How it works
Java Garbage Collection - How it worksMindfire Solutions
 
Understanding Java Garbage Collection - And What You Can Do About It
Understanding Java Garbage Collection - And What You Can Do About ItUnderstanding Java Garbage Collection - And What You Can Do About It
Understanding Java Garbage Collection - And What You Can Do About ItAzul Systems Inc.
 
Aae oop xp_06
Aae oop xp_06Aae oop xp_06
Aae oop xp_06Niit Care
 

Viewers also liked (20)

Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
OOP java
OOP javaOOP java
OOP java
 
Dacj 2-2 c
Dacj 2-2 cDacj 2-2 c
Dacj 2-2 c
 
11 ds and algorithm session_16
11 ds and algorithm session_1611 ds and algorithm session_16
11 ds and algorithm session_16
 
Oops recap
Oops recapOops recap
Oops recap
 
 
Vb.net session 09
Vb.net session 09Vb.net session 09
Vb.net session 09
 
15 ooad uml-20
15 ooad uml-2015 ooad uml-20
15 ooad uml-20
 
09 iec t1_s1_oo_ps_session_13
09 iec t1_s1_oo_ps_session_1309 iec t1_s1_oo_ps_session_13
09 iec t1_s1_oo_ps_session_13
 
OOP Java
OOP JavaOOP Java
OOP Java
 
Rdbms xp 01
Rdbms xp 01Rdbms xp 01
Rdbms xp 01
 
Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01
 
14 ooad uml-19
14 ooad uml-1914 ooad uml-19
14 ooad uml-19
 
Deawsj 7 ppt-2_c
Deawsj 7 ppt-2_cDeawsj 7 ppt-2_c
Deawsj 7 ppt-2_c
 
Java Garbage Collection - How it works
Java Garbage Collection - How it worksJava Garbage Collection - How it works
Java Garbage Collection - How it works
 
Ds 8
Ds 8Ds 8
Ds 8
 
Understanding Java Garbage Collection - And What You Can Do About It
Understanding Java Garbage Collection - And What You Can Do About ItUnderstanding Java Garbage Collection - And What You Can Do About It
Understanding Java Garbage Collection - And What You Can Do About It
 
Aae oop xp_06
Aae oop xp_06Aae oop xp_06
Aae oop xp_06
 
Dacj 1-1 a
Dacj 1-1 aDacj 1-1 a
Dacj 1-1 a
 

Similar to JAVA Object Oriented Programming (OOP)

Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 
Unit of competency
Unit of competencyUnit of competency
Unit of competencyloidasacueza
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructorShivam Singhal
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Soumen Santra
 
How to run java program without IDE
How to run java program without IDEHow to run java program without IDE
How to run java program without IDEShweta Oza
 
Introduction
IntroductionIntroduction
Introductionrichsoden
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1sotlsoc
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction AKR Education
 

Similar to JAVA Object Oriented Programming (OOP) (20)

Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
Unit of competency
Unit of competencyUnit of competency
Unit of competency
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
 
How to run java program without IDE
How to run java program without IDEHow to run java program without IDE
How to run java program without IDE
 
java basic .pdf
java basic .pdfjava basic .pdf
java basic .pdf
 
01slide
01slide01slide
01slide
 
01slide
01slide01slide
01slide
 
Introduction
IntroductionIntroduction
Introduction
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
Javanotes
JavanotesJavanotes
Javanotes
 
Basics of java 1
Basics of java 1Basics of java 1
Basics of java 1
 
Java notes
Java notesJava notes
Java notes
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 

More from Prof. Erwin Globio

Cisco Router Basic Configuration
Cisco Router Basic ConfigurationCisco Router Basic Configuration
Cisco Router Basic ConfigurationProf. Erwin Globio
 
Introduction to iOS Apps Development
Introduction to iOS Apps DevelopmentIntroduction to iOS Apps Development
Introduction to iOS Apps DevelopmentProf. Erwin Globio
 
Introduction to Android Development Latest
Introduction to Android Development LatestIntroduction to Android Development Latest
Introduction to Android Development LatestProf. Erwin Globio
 
iOS Apps Development (SQLite Tutorial Part 2)
iOS Apps Development (SQLite Tutorial Part 2)iOS Apps Development (SQLite Tutorial Part 2)
iOS Apps Development (SQLite Tutorial Part 2)Prof. Erwin Globio
 
iOS Apps Development (SQLite Tutorial Part 1)
iOS Apps Development (SQLite Tutorial Part 1)iOS Apps Development (SQLite Tutorial Part 1)
iOS Apps Development (SQLite Tutorial Part 1)Prof. Erwin Globio
 
Introduction to Computer Programming
Introduction to Computer ProgrammingIntroduction to Computer Programming
Introduction to Computer ProgrammingProf. Erwin Globio
 
Solutions to Common Android Problems
Solutions to Common Android ProblemsSolutions to Common Android Problems
Solutions to Common Android ProblemsProf. Erwin Globio
 
Android Development Tools and Installation
Android Development Tools and InstallationAndroid Development Tools and Installation
Android Development Tools and InstallationProf. Erwin Globio
 

More from Prof. Erwin Globio (20)

Embedded System Presentation
Embedded System PresentationEmbedded System Presentation
Embedded System Presentation
 
BSCS | BSIT Thesis Guidelines
BSCS | BSIT Thesis GuidelinesBSCS | BSIT Thesis Guidelines
BSCS | BSIT Thesis Guidelines
 
Internet of Things
Internet of ThingsInternet of Things
Internet of Things
 
Networking Trends
Networking TrendsNetworking Trends
Networking Trends
 
Sq lite presentation
Sq lite presentationSq lite presentation
Sq lite presentation
 
Ethics for IT Professionals
Ethics for IT ProfessionalsEthics for IT Professionals
Ethics for IT Professionals
 
Cisco Router Basic Configuration
Cisco Router Basic ConfigurationCisco Router Basic Configuration
Cisco Router Basic Configuration
 
Introduction to iOS Apps Development
Introduction to iOS Apps DevelopmentIntroduction to iOS Apps Development
Introduction to iOS Apps Development
 
Cloud Computing Latest
Cloud Computing LatestCloud Computing Latest
Cloud Computing Latest
 
Introduction to Android Development Latest
Introduction to Android Development LatestIntroduction to Android Development Latest
Introduction to Android Development Latest
 
iOS Apps Development (SQLite Tutorial Part 2)
iOS Apps Development (SQLite Tutorial Part 2)iOS Apps Development (SQLite Tutorial Part 2)
iOS Apps Development (SQLite Tutorial Part 2)
 
iOS Apps Development (SQLite Tutorial Part 1)
iOS Apps Development (SQLite Tutorial Part 1)iOS Apps Development (SQLite Tutorial Part 1)
iOS Apps Development (SQLite Tutorial Part 1)
 
A tutorial on C++ Programming
A tutorial on C++ ProgrammingA tutorial on C++ Programming
A tutorial on C++ Programming
 
Overview of C Language
Overview of C LanguageOverview of C Language
Overview of C Language
 
Introduction to Computer Programming
Introduction to Computer ProgrammingIntroduction to Computer Programming
Introduction to Computer Programming
 
Android Fragments
Android FragmentsAndroid Fragments
Android Fragments
 
Solutions to Common Android Problems
Solutions to Common Android ProblemsSolutions to Common Android Problems
Solutions to Common Android Problems
 
Android Development Tools and Installation
Android Development Tools and InstallationAndroid Development Tools and Installation
Android Development Tools and Installation
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Action Bar in Android
Action Bar in AndroidAction Bar in Android
Action Bar in Android
 

Recently uploaded

Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 

Recently uploaded (20)

Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 

JAVA Object Oriented Programming (OOP)

  • 1. Lesson 1 Introduction to Object-Oriented Programming Prof. Erwin M. Globio, MSIT Java Training Specialist http://eglobiotraining.com
  • 2. Object Oriented Programming  Model Real World Objects  Encapsulate Data and Function
  • 3. Java is used for Networking  Has many classes to program Internet communications  Java-enabled devices  mobile phones  Web pages with additional animation and functionality  Java servlets
  • 4. Java is Simple  Derived from C/C++  Simpler than C/C++.  No preprocessors  Pointers were eliminated  Common data structures that use pointers such as stacks, lists and trees are available
  • 5. Java is Robust  Employs strong type checking  Every data structure is defined and its type is checked during compilation and runtime  Built-in exception handling  Garbage collection is done automatically
  • 6. Java is Dynamic  There are many available Java resources in the Internet.  Using interfaces  Classes are dynamically loaded.
  • 7. Java is Secure  System breakers can not gain access to system resources  the Java bytecode verifier  loaded classes can not access the file system  a public-key encryption system (in the future)
  • 8. Java is Free  Java can be downloaded from the Internet for FREE  Just visit http://java.sun.com/
  • 9. Java is Portable You can compile your Java code from the command line. SYNTAX: javac <filename>.java EXAMPLE: javac Welcome.java
  • 10. Java is Portable Java program can then execute on any machine which has the Java Virtual Machine, thus, making it portable. SYNTAX: java <filename> EXAMPLE: java Welcome
  • 11. Java is Portable Java code (*.java) Java Compiler bytecodes (*.class) Java Virtual Machine MAC PC UNIX
  • 12. IDE: BlueJ  Download the appropriate version  Check the system requirements
  • 13. IDE Download BlueJ: http://www.bluej.org/download/download.html  Install J2SE 1.4.2 (Java 2 SDK version 1.4.2) or newer first before installing BlueJ
  • 14. IDE: BlueJ Minimum Requirements:  Pentium II processor or its equivalent  64Mb main memory Recommended:  400MHz Pentium III processor or above and a 128Mb main memory
  • 15. Launch BlueJ Let‟s make your first Java project using BlueJ…
  • 16. Sample codes package Group.Student; public class Welcome{ public void printWelcome() { System.out.println("Welcome to Java!"); //prints_a_msg } }
  • 17. Sample codes /* This class contains the main() method */ package Group.Student; public class Main { public static void main(String args[]) { Welcome Greet= new Welcome(); Greet.printWelcome(); } }
  • 18. Common Programming Errors  compile-time errors  runtime errors
  • 24. Word Bank  class  object  interface  message  method  inheritance  encapsulation  compile-time errors  runtime errors
  • 25. End of Lesson 1 Summary…
  • 26. End of Lesson 2 Laboratory Exercise
  • 27. Self-check Create a class and describe it in terms of its attributes (data) and functions (methods). Then, instantiate at least 2 objects. Use the tables below. //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 Name here Age Name: Jonathan Birthday Age: 29 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 [http://www.techfactors.ph] TechFactors Inc. ©2005
  • 28. Self-check Create a class and describe it in terms of its attributes (data) and functions (methods). Then, instantiate at least 2 objects. Use the tables below. //write the class name here //write the object name here //write the data of the object //write the data of the class here here //write the methods of the object here //write the methods of the class here
  • 29. Skills Workout Type the Java program given in this lesson in the specified package. Compile and run it. If errors are encountered, debug it.
  • 30. Lesson 2 Your First Java Program
  • 31. Welcome.java public class Welcome{ public void printWelcome() { System.out.println("Welcome to Java!"); //prints_a_msg } }
  • 32. Explaining Welcome.java 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
  • 33. 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{
  • 34. 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() {
  • 35. 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!");
  • 36. 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
  • 37. Explaining Main.java /* This class contains the main() method */ public class Main { public static void main(String args[]) { Welcome Greet= new Welcome(); Greet.printWelcome(); } }
  • 38. Explaining Main.java Line 1-3 Contains a multi-line comment. Anyting in between /* and */ is considered a comment. /* This class contains the main() method */
  • 39. Explaining Main.java Line 5 Declares the Main class. the brace after the class indicates the start of the class. public class Main {
  • 40. Explaining Main.java Line 6 Program execution starts from line 6. The Java interpreter should see this main method definition as is, except for args which is user defined. public class Main {
  • 41. Explaining Main.java Line 7 shows how an object is defined in Java. Here, the object Greet is created. The word “Greet” is user defined. (You can even have your name in its place!). The general syntax for defining an object in Java is:  Syntax:  <class_name> <object_name> = new<class_name>(<arguments>); Example: Welcome Greet= new Welcome();
  • 42. Explaining Main.java Line 8 Illustrates how a method of a class is called. If you look at the Welcome class, you’ll notice that we declared a mehod named printWelcome().By declaring an instance of the Welcome class (in tis case, the Greet variable is an instance of a Welcome class, courtesy of line 7), you can execute the method withi the specific class. Syntax: <class_name>.<method_name>(<arguments>);  Example: Greet.printWelcome();
  • 43. Explaining Main.java Line 9-10 } } Contains wo closing braces. The brace on line 9 closes the main method and brace on line 10 indicates the end of the scoope of the class Main.
  • 44. Word Bank new - used in telling the compiler to create an object from the specified class. public - modifier that indicates a class, method, or class variable can be accessed by any object or method directly.
  • 45. End of Lesson 2 Summary…
  • 46. Syntax Review SYNTAX EXAMPLE/S package package Group.Student; <top_package_name>[.<subpackage_name>]*; import import School.Section.Student; <top_package_name>[.<subpackage_name>]. import School.Section.*; <class_name>; <modifier> class <class_name> public class First <class_name> <object_name> = new <class_name> Welcome Greet= new Welcome(); (<arguments>); < package_name>.<class_name> <object_name> = School.Section.Student Alma = new new <package_name>.<class_name>(<arguments>); School.Section.Student (); <modifier> <return_type> <method_name> public static void main(String args[]) (<argument_list>) { <statements>} {} public void printWelcome( ) { } [http://www.techfactors.ph] TechFactors Inc. ©2005
  • 47. Syntax Review SYNTAX EXAMPLE/S System.out.println(String); System.out.println("Welcome to Java!"); System.out.print (String); System.out.print("Hello"); /* /* 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. */
  • 48. Self-check 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 }
  • 49. Self-check 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 }
  • 50. End of Lesson 2 Laboratory Exercise
  • 51. Lesson 3 Data Types, Literals, Keywords and Identifiers
  • 52. Magic words Casting – process of converting a value to the type of variable. Constant – identifier whose value can never be changed once initialized. Identifier – user-defined name for methods, classes, objects, variables and labels.
  • 53. Literals – values assigned to variables or constant Unicode – universal code that has a unique number to represent each character. Variable – identifier whose value can be changed.  Java keyword – word used by the Java compiler for a specific purpose
  • 54. Java Keywords [http://www.techfactors.ph] TechFactors Inc. ©2005
  • 55. Java Keywords Some key points about Java keywords: • const and goto are keywords but are not used in Java. • true and false are boolean literals that should not be used as identifiers. • null is also considered a literal but is not allowed as an identifier.
  • 56. Identifiers Rules for Identifiers: • The first character of your identifier can start with a Unicode letter. • It can be composed of alphanumeric characters and underscores. • there is no maximum length • create identifiers that are descriptive of their purpose. • Your identifier must have no embedded spaces. • Special characters such as ? and like are not accepted.
  • 57. Data Types Java has two sets of data types: • primitive • reference (or non-primitive).
  • 58. Data Types Data Type Default boolean false char „u0000‟ byte 0 short 0 int 0 long 0 float 0L double 0.0D
  • 59. Data Types Data Type Examples boolean true char „A‟,‟z‟,‟n‟,‟6‟ byte 1 short 11 int 167 long 11167 float 63.5F double 63.5
  • 60. Variables  Variable Declaration Syntax: <data_type> <identifier>; Examples: boolean Passed; char EquivalentGrade’; byte YearLevel; short Classes; int Faculty_No; long Student_No; float Average;
  • 61. Variables and Literals  Variable and Literal Declaration Syntax: <data_type> <identifier>=<literal>; 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;
  • 62. Variables and Literals  You can also declare several variables for a specific data type in one statement by separating each identifier with a comma(,) Examples: boolean Passed =true, Switch; char EquivalentGrade=’F’,ch1, ch2; byte Bytes, YearLevel =2; short SH, Classes =19; int Faculty_No =6781, Num1; long Student_No =76667, Employee_No, Long1; float Average=96.89F, Salary; double Logarithm=0.8795564564, Tax, SSS; String LastName=”Your LastName”,FirstName=”Your FirstName”, MiddleName;
  • 63. Constants Example: static final String Student_ID=”098774656”; Syntax for declaring constants: static final <type> <identifier> = <literal>; final <type> <identifier> = <literal>;
  • 64. Type Conversion/ Casting 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.
  • 65. 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); } }
  • 66. End of Lesson 3 Summary…
  • 67. Self-check I. Write I if the given is not an acceptable Java identifier on the space provided before each number. Otherwise, write V. ________________ 1.) Salary ________________ 2.) $dollar ________________ 3.) _main ________________ 4.) const ________________ 5.) previous year ________________ 6.) yahoo! ________________ 7.) else ________________ 8.) Float ________________ 9.) <date> ________________10.) 2_Version 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! „);
  • 68. 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 } }
  • 69. End of Lesson 10 LABORATORY EXERCISE
  • 70. Lesson 4 Java Operators
  • 71. Operators • Unary • Binary • Ternary • Shorthand
  • 72. Arithmetic Operator Operators + Addition - Subtraction * Multiplication / Division % Modulo ++ Increment -- Decrement
  • 73. The Arithmetic_operators program package 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;
  • 74. 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); } }
  • 75. The Arithmetic_operators program output [http://www.techfactors.ph] TechFactors Inc. ©2005
  • 76. Relational Operator > Greater than >= Greater than or equal to < Less than <= Less than or equal to == Equal to != Not Equal to
  • 77. The Relational_operators program package Group.Lesson4.Relational; public class Relational_operators { public Relational_operators() { }// Constructor for objects of class Relational_operators public static void main(String[] args)//execution begins here { //local variables int x = 5, y = 7; boolean Relational_Equal=false, Relational_NotEqual=false; boolean Relational_LessThan=false, Relational_LessThanOrEqualTo=false; boolean Relational_GreaterThan=false; boolean Relational_GreaterThanOrEqualTo=false;
  • 78. The Relational_operators program (Continued) //evaluate expressions Relational_Equal= x==y; Relational_NotEqual= x!=y; Relational_LessThan= x<y; Relational_LessThanOrEqualTo= x<=y; Relational_GreaterThan= x>y; Relational_GreaterThanOrEqualTo= x>=y; //print results System.out.println("x=5 y=7"); System.out.println("x==y "+Relational_Equal); System.out.println("x!=y "+Relational_NotEqual); System.out.println("x<y "+Relational_LessThan); System.out.println("x<=y "+Relational_LessThanOrEqualTo); System.out.println("x>y "+Relational_GreaterThan); System.out.println("x>=y "+Relational_GreaterThanOrEqualTo); } }
  • 79. The Relational_operators program output [http://www.techfactors.ph] TechFactors Inc. ©2005
  • 80. Logical Operator Operators Description ! NOT || OR && AND | short-circuit OR & short-circuit AND
  • 81. Logical Operator- Truth Tables The NOT (!) operator Operand1 RESULT ! true false ! false true
  • 82. Logical Operator- Truth Tables The OR (|) operator Operand1 Operand2 RESULT true | true true true | false true false | true true false | false false
  • 83. Logical Operator- Truth Tables The XOR (^) operator Operand1 Operand2 RESULT true ^ true false true ^ false true false ^ true true false ^ false false
  • 84. Logical Operator- Truth Tables The AND (&) operator Operand1 Operand2 RESULT true & true true true & false false false & true false false & false false
  • 85. 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_ShortCircuit= (x<y)| (x++==y); System.out.println("(x<y)| (x++==y) "+Logical_OR_ShortCircuit); Logical_OR= (x<y)||(x++==y); System.out.println("(x<y)| (x++==y) "+Logical_OR);
  • 86. 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); Logical_XOR= (x>y)^ (x++==y); System.out.println("(x>y)^ (x++==y) "+Logical_XOR); System.out.println("!((x>y)^ (x++==y)) "+!Logical_XOR);//NEGATE }
  • 87. The Logical_operators program output [http://www.techfactors.ph] TechFactors Inc. ©2005
  • 88. REVIEW RECALL: How do you get the equivalent of a certain number in bits? ANSWER: You divide the number by 2 until you reach 0. Jot down the remainder for each division operation and that‟s the equivalent. RECALL: How do you convert a bit sequence to integer? ANSWER: You multiply each bit by powers of 2. Then, add all the products to get the equivalent. RECALL: How many bits does an integer have? ANSWER: 16 bits Try converting 16 and 27 to bits. Hope you got these answers: 16=0000000000010000 27=0000000000011011
  • 89. REVIEW If you have a negative number, you still have to convert the same way you would if it were a positive number. Then, get the complement and add 1. That‟s it! Example: 4=0000000000000100 -4=1111111111111100
  • 90. Bitwise Operator Operators Description ~ Complement & AND | OR ^ XOR (Exclusive OR) << Left Shift >> Right Shift >>> Unsigned Right Shift
  • 91. Bitwise Operator - Truth Tables The BITWISE COMPLEMENT Operand1 RESULT ~ 1 0 ~ 0 1
  • 92. Bitwise Operator - Truth Tables The BITWISE OR (|) Operand1 Operand2 RESULT 1 | 1 1 1 | 0 1 0 | 1 1 0 | 0 0
  • 93. Bitwise Operator - Truth Tables The BITWISE XOR (^) Operand1 Operand2 RESULT 1 ^ 1 0 1 ^ 0 1 0 ^ 1 1 0 ^ 0 0
  • 94. Bitwise Operator - Truth Tables The BITWISE AND (&) Operand1 Operand2 RESULT 1 & 1 1 1 & 0 0 0 & 1 0 0 & 0 0
  • 95. 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= 1111111111111111 x= 0000000000010000 Right_shift= -1 y= 0000000000011011 And= 0000000000010000 Negative=1111111111111100 Negative=0011111111111111 x= 0000000000010000 Negative= 1073741823 y= 0000000000011011 Xor= 0000000000001011
  • 96. The Bitwise_operators program package Group.Lesson4.Bitwise; public class Bitwise_operators { //Constructor for objects of class Bitwise_operators public Bitwise_operators() { } public static void main(String[] args)//execution begins here { //local variables int x = 16 , y = 27, z=-4, Negative=-4; int Complement=0,Or=0,And=0,Xor=0,Left_shift=0; int Right_shift=0, Unsigned_Right_shift=0; //operations Complement = ~x; Or = x|y; And = x&y; Xor = x^y; Left_shift = x<<3; Right_shift = z>>2; Unsigned_Right_shift= Negative>>>2;
  • 97. The Bitwise_operators program (continued) //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); } }
  • 99. Shorthand Operator with Assignment Operators Description += Assignment With Addition -= Assignment With Subtraction *= Assignment With Multiplication /= Assignment With Division %= Assignment With Modulo &= Assignment With Bitwise And |= Assignment With Bitwise Or ^= Assignment With Bitwise XOR <<= Assignment With Left Shift >>= Assignment With Right Shift >>>= Assignment With Unsigned Right Shift
  • 100. The Shorthand_operators program package Group.Lesson4.Shorthand; public class Shorthand_operators { //Constructor for objects of class Shorthand_operators public Shorthand_operators(){ } public static void main(String[] args)//execution begins here { //local variables int Assign_With_Addition=4, Assign_With_Subtraction=4, Assign_With_Multiplication=4; double Assign_With_Division=7; int Assign_With_Modulo=7, Assign_With_Bitwise_And=7; int Assign_With_Bitwise_Or=23, Assign_With_Bitwise_XOR=23, Assign_With_LeftShift=23; int Assign_With_RightShift=10, Assign_With_UnsignedRightShift=10; Assign_With_Addition +=2; Assign_With_Subtraction -=2; Assign_With_Multiplication *=2; Assign_With_Division /=2; Assign_With_Modulo %=2; Assign_With_Bitwise_And &=2; Assign_With_Bitwise_Or |=2; Assign_With_Bitwise_XOR ^=2; Assign_With_LeftShift <<=2; Assign_With_RightShift >>=2; Assign_With_UnsignedRightShift >>>=2; System.out.println(" Results");
  • 101. The Shorthand_operators program (continued) 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); } }
  • 104. Word Bank  expression  boolean expressions  truth value  truth table  shorthand operators  bit  sign bit
  • 105. End of Lesson 4 Summary…
  • 106. Self-check Evaluate the given expressions/statements. Write the result on the blanks provided before each number. Given that a=3, b=4,c=6. 1.x=a++; 2.y=--b; 3.!((++a)!=4)&&(--b==4)) 4.(c++!=b)|(a++==b) 5.t=a+b*c/3-2;
  • 107. Lesson 5 Decisions
  • 108. Decision making In life we make decisions. Many times our decision are based on how we evaluate the situation. Certain situation need to be evaluated carefully in order to make the correct results or decision.
  • 109. In Java , decisions are made using statements like if, if else, nested-if and switch. In this lesson , we will examine hot these conditional statements are applied to simple programming problems.
  • 110. Decision Statements If Statement: public class If_Statement { public static void main (String [] args) { int x = 0; System.out.println ("Value is:" + x); if(x%2==0) { System.out.println ("VAlue is an even number."); } if (x%2 ==1) { System.out.println ("Value is an odd number."); } } • }
  • 111. Wrapper Class Primitive Data Wrapper Class Type boolean Boolean char Character byte Byte short Short int Integer long Long float Float double Double
  • 112. if Statement Syntax: if (<boolean condition is true>) { <statement/s> } Example: if(x!=0){ x=(int)x/2; }
  • 113. The If_Statement program package Lesson5.If; import java.io.*; public class If_Statement { //Constructor for objects of class If_Statement public If_Statement(){ } public static void main(String[] args) throws IOException { BufferedReader dataIn=new BufferedReader(new InputStreamReader(System.in)); int x=0; String Str_1; System.out.print("Enter an integer value: "); Str_1=dataIn.readLine(); x=Integer.parseInt(Str_1); if(x!=0){ x=(int)x/2; } System.out.println("x= "+x); } }
  • 114. if-else Statement 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> }
  • 115. The IfElse program package Lesson5.If_Else; import java.io.*; public class IfElse { public IfElse() { } public static void main(String[] args)throws IOException { BufferedReader dataIn=new BufferedReader(new InputStreamReader(System.in)); //declare local variables int A=0; String Str_A; //input System.out.print("Enter an integer value for A: "); Str_A=dataIn.readLine(); A=Integer.parseInt(Str_A); //determine if input is odd or even and print if (A%2==0) { System.out.println (A+" is an EVEN number"); } else { System.out.println (A+" is an ODD number"); } } }
  • 116. nested-if Statement Syntax: if (<boolean condition is true>){ <statement/s> } else if (<boolean condition is true>) { <statement/s> } else { <statement/s> }
  • 117. nested-if Statement 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); }
  • 118. The NestedIf program and output public class NestedIf { public NestedIf() { } public static void main(String[] args)throws IOException { BufferedReader dataIn=new BufferedReader(new InputStreamReader(System.in)); //declare local variables double number1=0.0,number2=0.0; String Str_number1,Str_number2; //input Str_number1 and convert it to an integer (number1) System.out.print("Enter a number: "); Str_number1=dataIn.readLine(); number1=Double.parseDouble(Str_number1); //input Str_number2 and convert it to an integer (number2) System.out.print("Enter another number: "); Str_number2=dataIn.readLine(); number2=Double.parseDouble(Str_number2); //determine if number1 is greater than, less than or equal to number2 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); } } }
  • 119. switch Statement Syntax: switch(<expression>) { case <constant1>: <statements> break; case <constant2>: <statements> break; : : default: <statements> break; }
  • 120. 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; }
  • 121. The Switch_case program public Switch_case(){ }//Constructor for objects of class Switch_case public static void main(String[] args) throws IOException{ BufferedReader dataIn=new BufferedReader(new InputStreamReader(System.in)); int month=0; String Str_month; System.out.print("Enter month [1-12]: "); Str_month=dataIn.readLine(); month=Integer.parseInt(Str_month); 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"); break; case 4:System.out.println("April has 30 days"); break; case 5:System.out.println("May has 31 days"); break;
  • 122. The Switch_case program (continued) and output case 6:System.out.println("June has 30 days"); break; case 7:System.out.println("July has 31 days"); break; case 8:System.out.println("August has 31 days"); break; case 9:System.out.println("September has 30 days"); break; case 10:System.out.println("October has 31 days"); break; case 11:System.out.println("November has 30 days"); break; case 12:System.out.println("December has 31 days"); break; default:System.out.println("Sorry that is not a valid month!"); break; }}}
  • 123. Word Bank  Wrapper class
  • 124. End of Lesson 5 Summary…
  • 125. End of Lesson 10 LABORATORY EXERCISE
  • 126. Syntax Review SYNTAX EXAMPLE/S if (<boolean condition is if(x!=0){ true>) { x=(int)x/2; <statement/s> } } if (<boolean condition is if (A%2==0) { true>){ System.out.println (A+" is EVEN"); <statement/s> } } else else { { System.out.println (A+" is ODD "); <statement/s> } }
  • 127. SYNTAX EXAMPLE/S Syntax Review if (<boolean condition is true>){ if (number1>number2) { <statement/s> System.out.println (number1+" is greater than "+number2); } } else if (number1<number2){ else if (<boolean condition is true>) { System.out.println (number1+" is less than "+number2); <statement/s> } else {//number1==number2 } System.out.println (number1+" is equal to "+number2); else{ } <statement/s> } 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; }
  • 128. Self-check In the next slide is a simple Java program that will determine if a number is zero, positive or negative then print the appropriate message on the screen. Fill the missing portions with the correct code. Type the program, then compile and run it.
  • 129. Self-check public class NestedIf { public NestedIf() { }//constructor public static void main(String[] args) { int number=3; if (__________) // FILL-IN THE BLANK { System.out.println (number+” is ZERO!”); } else if (___________) //FILL-IN THE BLANK { System.out.println (number+" is a POSITIVE number!”); } else { System.out.println (number+" is a NEGATIVE number!”); } } }
  • 130. Lesson 6 Loops
  • 131. General Topics • for structure • while structure • do-while structure
  • 132. loop A loop is a structure in Java that permits a set of instructions to be repeated
  • 133.  The for loop is usually used when the number of iterations that needs to be done is already known.  The while loop checks whether the prerequisite condition to execute the code within the loop is true or not. If it is true, then the code loop is executed.  The do-while loop executes the code within it first regardless of whether the condition is true or not before testing the given condition.
  • 134. 3 Main Parts of for loop Initialization - initial values of variables that will be used in the loop. Test condition - a boolean expression that should be satisfied for the loop to continue executing the statements within the loop’s scope; as long as the condition is true. Increment/Operations- dictates the change in value of the loop control variable everytime the loop is repeated.
  • 135. for loop Example: for(int Ctr=1;Ctr<=5;Ctr++){ System.out.println(Ctr); } Syntax: for (<initialization>;<condition>;<increment>) { <statement/s> }
  • 136. 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); } } }
  • 137. while loop Example: int Ctr=1; while(Ctr<=5){ System.out.println(Ctr); Ctr++; } Syntax: while (boolean condition is true) { <statement/s> }
  • 138. Sample Code and output public class While_Loop { //Constructor for objects of class While_loop public While_Loop() { } public static void main(String[] args) { int Ctr=1; while(Ctr<=5){ System.out.println(Ctr); Ctr++; } } }
  • 139. do-while loop Example: int Ctr=1; do{ System.out.println(Ctr); Ctr++; }while(Ctr<=5); Syntax: do { <statement/s> } while (<boolean condition is true>);
  • 140. Sample Code public class DoWhile { public DoWhile() { } public static void main(String[] args) { int Ctr=1; do{ System.out.println(Ctr); Ctr++; }while(Ctr<=5); } }
  • 141. End of Lesson 6 Summary…
  • 142. Self-check In the next slides are three simple Java programs. Fill the missing portions with the correct code. Type the programs, compile and run them.
  • 143. Self-check (For_loop2) public class For_loop2 { //Constructor for objects of class For_loop2 public For_loop2() { } /** * main()-prints all even numbers from 1-10 automatically using a for loop * * @param String[] args * @return nothing */ public static void main(String[] args) { for(int Ctr=____;Ctr<=_____;Ctr____){ System.out.println(Ctr); } } }
  • 144. Self-check (DoWhile2) public class DoWhile2 { //Constructor for objects of class DoWhile2 public DoWhile2() { } /** * main()-prints the numbers 1-10 automatically using a do_while loop * * @param String[] args * @return nothing */ public static void main(String[] args) { int Ctr=________; do{ System.out.println(Ctr); Ctr______; }while(Ctr<=_________); } }
  • 145. Self-check (While_Loop2) public class While_Loop2 { //Constructor for objects of class While_loop2 public While_Loop2() { } /** * main()-prints odd numbers from 2 to 20 automatically using a while loop * * @param String[] args * @return nothing */ public static void main(String[] args) { int Ctr=____________; while(Ctr<=__________){ System.out.println(Ctr); Ctr_______________; } } }
  • 146. End of Lesson LABORATORY EXERCISE
  • 148. General Topics • Nested loops • continue • break
  • 149. Nested_For loops The Nested_For program prints the multiplication table. To do this, it has two loops. One loop is inside the other. This is why it is called a nested loop.
  • 150. Nested_For loops public class Nested_For { // Constructor for objects of class Nested_For public Nested_For(){ } public static void main(String [] args) { for(int Row=1;Row<=10;Row++){ for(int Column=1;Column<=10;Column++){ System.out.print(Row*Column+"t"); } System.out.println(); } } }
  • 151. Nested_For loops – how it behaves To see how this program behaves at any given time, we need to set breakpoints. To do that, just click on line number. Click on line 15.
  • 152. Nested_For loops – how it behaves Run the program by right-clicking on the Nested_For icon, click on void main(String [] args). Then, click on the Ok button.
  • 153. Nested_For loops – how it behaves – how it behaves
  • 154. Nested_For loops – how it behaves
  • 156. Continue_Loop The difference is the inclusion of the if statement on line 17 and the continue statement on line 18.
  • 157. Continue_Loop public class Continue_Loop { // Constructor for objects of class Continue_Loop public Continue_Loop(){ } public static void main(String [] args) { for(int Row=1;Row<=10;Row++){ for(int Column=1;Column<=10;Column++){ if(Column==4){ continue; } System.out.print(Row*Column+"t"); } System.out.println(); } } }
  • 158. Continue_Loop - Output The column containing the multiples of 4 is not included.
  • 159. Loop_Break This program is again similar to the previous programs in this lesson, except for the inclusion of the if and break statements. The output shows 3 columns only.
  • 160. Loop_Break public class Loop_Break { //Constructor for objects of class Loop_Break public Loop_Break(){ } public static void main(String [] args) { for(int Row=1;Row<=10;Row++){ for(int Column=1;Column<=10;Column++){ if(Column==4){ break; } System.out.print(Row*Column+"t"); } System.out.println(); } } }
  • 161. Labels public class Labels { //Constructor for objects of class Labels public Labels() { } public static void main(String [] args) { here: for(int Row=1;Row<=10;Row++){ for(int Column=1;Column<=10;Column++){ System.out.print(Row*Column+"t"); if(Column==4){ break here; } } System.out.println(); } } }
  • 162. Word Bank Nested loops
  • 163. Self-check I. A Java program that prints the multiplication table is given using nested while loops. Fill-in the missing portions. public class Multiplication_Table { // Constructor for objects of class Multiplication_Table public Multiplication_Table (){ } public static void main(String [] args) { int Row=_______; //indicate the initial value while(Row<____){ Row++; int Column=_____; //indicate the initial value while(Column<_____){ Column++; System.out.print(Row*Column+"t"); } System.out.println(); } } }
  • 164. Self-check II. A Java program that prints the given output using nested do-while loops. Fill-in the missing portions.
  • 165. Self-check public class Table{ // Constructor for objects of class Table public Table(){ } public static void main(String [] args) { int Row=_______; //indicate the initial value do{ Row++; int Column=_____; //indicate the initial value do{ Column++; if(_______){ continue; } System.out.print(Row*Column+"t"); } while(Column<_____); System.out.println(); } while(Row<____); } }
  • 167. Exceptions  Unexpected errors or events within our program
  • 168. import java.io.*; public class Exception1{ public static void main(String[] args){ BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); int x=0; String Str_1; System.out.print(“Enter an integer value:”); try{ Str_1 = dataIn.readLine(); x = Integer.parseInt(Str_1); } catch(Exception e){ System.out.println(“Error reported”); } x = (int)x/2; System.out.println(“x= ”+x); } }
  • 169. import java.io.*; public class Exception2{ public static void main(String[] args){ BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); int x=0, y=0; String Str_1, Str_2; System.out.print(“Enter an integer value: ”); try{ Str_1 = dataIn.readLine(); System.out.print(“Enter another value: ”); Str_2 = dataIn.readLine(); x = Integer.parseInt(Str_1); y = Integer.parseInt(Str_2); x = x/y; }
  • 170. catch(ArithmeticException e){ System.out.println(“Divide by zero error.”); } catch(NumberFormatException e){ System.out.println(“Invalid number entered.”); } catch(Exception e){ System.out.println(“Invalid number entered.”); } finally{ System.out.println(“x= ”+x); } } }
  • 171. Exceptions  Exception classes  try  catch  finally
  • 172. Exception classes  Help handle errors  Included within Java installation package
  • 173. try-catch  At least one catch for every try  catch statements should catch different exceptions  try-catch order  catch immediately after a try
  • 174. End of Lesson LABORATORY EXERCISE
  • 175. Lesson 8 Classes
  • 176. General Topics • Classes • Inheritance • Interface • Objects • Constructors • Overloading Methods • Overriding Methods
  • 179. Syntax <modifier> class <class_name> [extends <superclass>] { <declaration/s> } Example: public class Student extends Person
  • 180. Syntax <modifier> class <name> [extends <superclass>] [implements <interfaces>] { <declaration/s> } Example: public class Teacher extends Person implements Employee
  • 181. Syntax <modifiers> class <class_name>{ [<attribute_declarations>] [<constructor_declarations>] [<method_declarations>] }
  • 182. The Person program package Lesson8; public class Person extends Object { private String name; private int age; private Date birthday; // class constructor public Person() { name = "secret"; age = 0; birthday = new Date(7,7); } //overloaded constructor public Person(String name, int age, Date birthday){ this.name = name; this.age = age; this.birthday = birthday; }
  • 183. The Person program (continued) //accessor methods - setters public void setName(String X){ name= X; } public void setAge(int X) { age=X; } public void setBirthday(Date X){ birthday=X; } public void setDetails(String X, int Y, Date Z){ name= X; age=Y; birthday = Z; } //accessor methods - getters public String getName(){ return name; }
  • 184. The Person program (continued) public int getAge(){ return age; } //this method greets you on your bday and increments age public void happyBirthday(Date date){ System.out.println("Today is "+date.month+"/"+date.month+"/2005."); if (birthday.day == date.day && birthday.month == date.month){ System.out.println("Happy birthday, "+ this.name + "."); age++; System.out.println("You are now "+age+" years old."); } else { System.out.println( "It's not " + this.name + "'s birthday today."); } } }
  • 185. The Someone program package Lesson8; public class Someone { public static void main (String args[]){ Date dateToday = new Date(3,7); Date bdayLesley= new Date(23,10); Person Angelina=new Person(); Student Stevenson = new Student("Stevenson",20,new Date(22,10),4); Student Allan =new Student(3); Teacher Lesley= new Teacher("Lesley",28,bdayLesley,14000.25); 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)); }
  • 186. 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; }
  • 187. The Date program (continued) //Constructor for objects of class Date with day & month as parameters public Date(int this_Day,int this_Month) { // initialise instance variables if((this_Month>=1)&&(this_Month<=12)){ month=this_Month; switch(month){ case 1: case 3: case 5: case 7: case 8: case 10: case 12:if((this_Day>=1)&&(this_Day<=31)){day = this_Day;} else {day=1;} break; case 4: case 6: case 9: case 11:if((this_Day>=1)&&(this_Day<=30)){ day = this_Day;} else {day=1;} break; case 2:if((this_Day>=1)&&(this_Day<=28)){day = this_Day;} else {day=1;} break; } } else { month=1; } year=2005; }
  • 188. The Date program (continued) public void print_Date(){//prints the date mm/dd/yyyy System.out.println(month+"/"+day+"/"+year); } }
  • 189. The Student program package Lesson8; public class Student extends Person { private int yearlvl; //constructors public Student(){ super(); yearlvl=1; } public Student(int yearlvl) { super(); if((yearlvl<=4)&&(yearlvl>=1)){ this.yearlvl=yearlvl; } else { this.yearlvl=1; } }
  • 190. The Student program (continued) public Student(String name, int age, Date birthday, int yearlvl){ super(name, age, birthday); if((yearlvl<=4)&&(yearlvl>=1)){ this.yearlvl=yearlvl; } else { this.yearlvl=1; } System.out.print("Hi, "+name+". "); System.out.print(“Your birthday this year is on "); birthday.print_Date(); System.out.println("You are "+age+" years old."); System.out.println(); }
  • 191. The Student program (continued) //accessor methods public void setYearlvl(int yearlvl){ if((yearlvl<=4)&&(yearlvl>=1)){ this.yearlvl=yearlvl; } else { this.yearlvl=1; } } public void setDetails(String name, int age, Date birthday){ super.setDetails(name,age,birthday); System.out.print("Hello, "+name+". "); System.out.print("Your birthday this year is on "); birthday.print_Date(); System.out.println("You are "+age+" years old."); System.out.println(); }
  • 192. The Student program (continued) public void setDetails(String name, int age, Date birthday, int yearlvl){ super.setDetails(name,age,birthday); if((yearlvl<=4)&&(yearlvl>=1)){ this.yearlvl=yearlvl; } else { this.yearlvl=1; } System.out.print("Hello, "+name+". "); System.out.print(" Your birthday this year is on "); birthday.print_Date(); System.out.println("You are "+age+" years old."); System.out.println(); } public int getYearlvl(){ return yearlvl; } }
  • 193. The Teacher program 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; }
  • 194. The Teacher program (continued) public Teacher(String name, int age, Date birthday, double salary){ super(name, age, birthday); this.salary= salary; System.out.println("Good morning, "+name+". Your salary is "+salary+"."); System.out.println(" Your birthday this year is on "); birthday.print_Date(); System.out.println("You are "+age+" years old."); System.out.println(); } //accessor methods public void setSalary(double salary) { this.salary = salary; }
  • 195. The Teacher program (continued) 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; } }
  • 196. The Employee program package Lesson8; public interface Employee { public void setSalary(double salary); public void setDetails(String name, int age, Date birthday, double salary); public double getSalary(); }
  • 197. Word Bank Superclass Subclass Inheritance Interface Method Signature Overloading Constructor Overriding Method
  • 198. End of Lesson 8 SUMMARY
  • 199. Syntax Review  The constructor of the superclass that has no parameters can be called this way:  super ( );  The constructor of the superclass that has parameters can be called this way:  super (<argument list> );  The syntax to call a method of the superclass is:  super.<method_name> (<argument list> );
  • 200. Syntax Review SYNTAX EXAMPLE/S <modifier> class <class_name> public class Student [extends <superclass>] extends Person <modifier> class <name> public class Teacher [extends <superclass>] extends Person [implements <interfaces>] implements Employee
  • 201. Syntax Review (continued) SYNTAX EXAMPLE/S <modifiers> class <class_name>{ public class Person extends Object{ [<attribute_declarations>] //attribute declarations private String name; [<constructor_declarations>] private int age; [<method_declarations>] private Date birthday; } // class constructor public Person() { name = "secret"; age = 0; birthday = new Date(7,7); } //accessor methods - setters public void setName(String X){ name= X; } }
  • 202. Self-check 1 I. Use the applications given on our lesson for exercise A and B. A. Supply all the method signatures of Student to the interface Learner, except for the constructors. public interface Learner{ } B. Create a constructor for Person with name and age as parameters. Make sure that you assign values to all the attributes of the class Person.
  • 203. Self-check 2 II. Use this diagram in answering the next exercises.
  • 204. Self-check A. Supply all the method signatures of Plane to the interface FlyingObject, except for the constructors. public interface FlyingObject{ }
  • 205. End of Lesson LABORATORY EXERCISE
  • 206. Lesson 9 Arrays
  • 207. General Topics • Single-dimensional arrays • Array of Objects • Multidimensional arrays
  • 208. The Single_Array program public class Single_Array { //Constructor for objects of class Single_Array public Single_Array() { } public static void main(String[] args){ int [] GradeLevel=new int [6]; int [] YearLevel={1,2,3,4}; System.out.print("The contents of the YearLevel array: "); print_Single_Array(YearLevel); System.out.print("The contents of the GradeLevel array: "); print_Single_Array(GradeLevel); System.arraycopy(YearLevel,0,GradeLevel,1,YearLevel.length); System.out.print("The contents of the GradeLevel array after copying: "); print_Single_Array(GradeLevel); for(int Index=1;Index<GradeLevel.length;Index++){ GradeLevel[Index]=Index*2; } System.out.print("The contents of the GradeLevel array after assigning values: "); print_Single_Array(GradeLevel); }
  • 209. The Single_Array program (continued) and output public static void print_Single_Array(int[] Array){ for(int subscript=0;subscript<Array.length;subscript++){ System.out.print(Array[subscript]); //prints the array element if((subscript+1)<Array.length){ //prints a comma in- between elements System.out.print(", "); } } System.out.println(); } }
  • 210. Single Dimensional Array SYNTAX: <data_type> [ ] <array_identifier> = new <data_type>[<no_of_elements>]; <data_type> <array_identifier> [ ] = new <data_type>[<no_of_elements>]; Example: First Element Last Element [0] [1] [2] [3] YearLevel 1 2 3 4
  • 211. System.arraycopy SYNTAX: System.arraycopy(<Array_source>, <Array_sourcePosition>, <Array_destination>, <Array_destinationPosition>, <numberOfElements>);
  • 212. The Date program package Group.Lesson9.Array_Object; /** * @author Lesley Abe * @version 1 */ public class Date { // instance variables - replace the example below with your own private int day, month, year; //Constructor for objects of class Date with no parameters public Date() { // initialize instance variables day = 1; month=1; year=2005; } //Constructor for objects of class Date with day & month as parameters
  • 213. The Date program (continued) public Date(int this_Day,int this_Month) { // initialise instance variables if((this_Month>=1)&&(this_Month<=12)){ month=this_Month; switch(month){ case 1: case 3: case 5: case 7: case 8: case 10: case 12:if((this_Day>=1)&&(this_Day<=31)){day = this_Day;} else {day=1;} break; case 4: case 6: case 9: case 11:if((this_Day>=1)&&(this_Day<=30)){ day = this_Day;} else {day=1;} break; case 2:if((this_Day>=1)&&(this_Day<=28)){day = this_Day;} else {day=1;} break; } } else { month=1; } year=2005; }
  • 214. The Date program (continued) public static void main(String[] args) { Date[] Birthdays={ new Date(23,10), new Date(22,3) }; Date[] Holidays=new Date[4]; Holidays[0]=new Date(25,12); Holidays[1]=new Date(1,5); Holidays[2]=new Date(1,11); Holidays[3]=new Date(1,1); } }
  • 215. The Two_Dimensional_Array program public class Two_Dimensional_Array { //Constructor for objects of class Two_Dimensional_Array public Two_Dimensional_Array() { } public static void main(String[] args) { final int YearLevel=4; // this is a constant final int Section=2; //this is a constant String TeacherName [] [] = new String [YearLevel] [Section]; String Student [] [] = new String [YearLevel] [ ]; //non-rectangular array //String Student [] [] = new String [] [YearLevel]; //this is illegal! //assign teachers to all the classes in high school TeacherName [0] [0] = "Lesley Abe"; TeacherName [0] [1] = "Arturo Jacinto Jr."; TeacherName [1] [0] = "Olive Hernandez"; TeacherName [1] [1] = "Alvin Ramirez"; TeacherName [2] [0] = "Christopher Ramos"; TeacherName [2] [1] = "Gabriela Alejandra Dans-Lee"; TeacherName [3] [0] = "Joyce Cayamanda"; TeacherName [3] [1] = "Ana Lisa Galinato";
  • 216. The Two_Dimensional_Array program (continued) //indicate how many student assistants per year level Student [0]=new String [2]; Student [1]=new String [2]; Student [2]=new String [1]; Student [3]=new String [1]; //assign student assistants per year level Student [0] [0]= "Stevenson Lee"; Student [0] [1]= "Brian Loya"; Student [1] [0]= "Joselino Luna"; Student [1] [1]= "Allan Valdez"; Student [2] [0]= "John Dionisio"; Student [3] [0]= "Geoffrey Chua"; } }
  • 217. The Two_Dimensional_Array program (continued) public static void main(String[] args) { Date[] Birthdays={ new Date(23,10), new Date(22,3) }; Date[] Holidays=new Date[4]; Holidays[0]=new Date(25,12); Holidays[1]=new Date(1,5); Holidays[2]=new Date(1,11); Holidays[3]=new Date(1,1); } }
  • 218. Multi-Dimensional Array SYNTAX: <data_type> [ ][ ] <array_identifier> = new <data_type>[<size1>][<size2>]; <data_type> <array_identifier> [ ] [ ] = new <data_type>[<size1>][<size2>];
  • 220. End of Lesson 9 SUMMARY
  • 221. Syntax Review SYNTAX EXAMPLE/S <data_type> [ ] <array_identifier> = new int [ ] GradeLevel=new int [6]; <data_type>[<no_of_elements>]; <data_type> < array_identifier> [ ] = new int GradeLevel [ ] =new int [6]; <data_type>[<no_of_elements>]; <data_type> [ ] < array_identifier> = {< elements int [ ] YearLevel={1,2,3,4}; separated by commas>}; < array_identifier> [<Index>] = <value>; GradeLevel[Index]=Index*2; <data_type> [ ][ ] <array_identifier> = new String [ ] [ ] TeacherName = new String <data_type>[<size1>][<size2>]; [YearLevel] [ ]; <data_type> <array_identifier> [ ] [ ] = new String TeacherName [ ] [ ] = new String <data_type>[<size1>][<size2>]; [YearLevel] [Section]; < array_identifier> [<Index1>] [<Index2>] = TeacherName [0] [0] = "Lesley Abe"; <value>; System.arraycopy(<Array_source>, System.arraycopy(YearLevel,0,GradeLev <Array_sourcePosition>, <Array_destination>, el,1,YearLevel.length); <Array_destinationPosition>, <numberOfElements>);
  • 222. Self-check 1 public class Array1 { //Constructor for objects of class Array1 public Array1() { } public static void main(String[] args){ String [] __________={“Math”,”Science”,_________ }; String [] MyTeachers={______________ }; System.out.print("Here are my subjects: "); print_Array1(MySubjects); System.out.print("My favorite subject is: "+________); System.out.print("My favorite teacher is: "+________); } //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(); } }
  • 223. 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; } } } }
  • 224. Self-check 2 (continued) What are the values of the following: Table[0][0]= ___________ Table[2][1]= ___________ Table[1][3]= ___________ Table[4][4]= ___________ Table[3][2]= ___________
  • 225. End of Lesson LABORATORY EXERCISE
  • 226. Lesson 10 GUI
  • 227. General Topics • Abstract Window Toolkit (AWT) - java.awt package - components • Containers • Layout Managers
  • 228. Layout SYNTAX: FlowLayout( ) FlowLayout(int align) FlowLayout(int align, int hgap, int vgap) Examples: setLayout(FlowLayout()); setLayout(FlowLayout(FlowLayout.LEF T)); setLayout(FlowLayout(FlowLayout.RIG HT,23,10));
  • 229. 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));
  • 230. Layout SYNTAX: BorderLayout( ); Examples: setLayout(new BorderLayout());
  • 233. The DrawTest program package Group.Lesson10; import java.awt.event.*; import java.awt.*; public class DrawTest { DrawPanel panel; DrawControls controls; public static void main(String args[]) { Frame Shapes = new Frame("Basic Shapes"); DrawPanel panel = new DrawPanel(); DrawControls controls = new DrawControls(panel); Shapes.add("Center", panel); Shapes.add("West",controls); Shapes.setSize(400,300); Shapes.setVisible(true); Shapes.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } } ); } }
  • 234. The DrawPanel program package Group.Lesson10; import java.awt.event.*; import java.awt.*; public class DrawPanel extends Panel { public static final int NONE = 0; public static final int RECTANGLE = 1; public static final int CIRCLE = 2; public static final int SQUARE = 3; public static final int TRIANGLE = 4; int mode = NONE; public DrawPanel() { setBackground(Color.white); }
  • 235. The DrawPanel program (continued) public void setDrawMode(int mode) { switch (mode) { case NONE: case RECTANGLE: this.mode = mode; case SQUARE: this.mode = mode; break; case CIRCLE: this.mode = mode; break; case TRIANGLE: this.mode = mode; break; } repaint(); }
  • 236. The DrawPanel program (continued) public void paint(Graphics g) { if (mode == RECTANGLE) { g.fillRect(100, 60, 100,150); } if (mode == CIRCLE) { g.fillOval(100, 90, 100, 100); } if (mode == SQUARE) { g.fillRect(100, 90, 100, 100); } if (mode == TRIANGLE) { int xpoints[] = {90, 150, 210}; int ypoints[] = {90, 200, 90}; int points = 3; g.fillPolygon(xpoints, ypoints, points); } } }
  • 237. Methods Used fillRect(int x, int y, int width, int height) fillOval(int x, int y, int width, int height) fillPolygon(Polygon p)
  • 238. The DrawControl program (continued) package Group.Lesson10; import java.awt.event.*; import java.awt.*; class DrawControls extends Panel implements ItemListener { DrawPanel target; Panel NorthPanel = new Panel(); Panel CenterPanel = new Panel(); Panel SouthPanel = new Panel(); private static int Shape = 0; private static Color targetColor = Color.red; public DrawControls(DrawPanel target) { this.target = target; setLayout(new BorderLayout()); setBackground(Color.lightGray); target.setForeground(Color.red); NorthPanel.setBackground(Color.lightGray ); NorthPanel.setLayout(new GridLayout(6,1));
  • 239. The DrawControl program (continued) 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)); b.addItemListener(this);
  • 240. 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); CenterPanel.add(colors);
  • 241. 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); }
  • 242. The DrawControl program (continued) private void onCommand(int btnNUMBER) { switch(btnNUMBER){ case 1: target.setForeground(Color.white); target.setDrawMode(0); break; case 2: target.setForeground(targetColor); target.setDrawMode(Shape); break; } }
  • 243. The DrawControl program (continued) public void itemStateChanged(ItemEvent e) { if (e.getSource() instanceof Checkbox) { Checkbox b = new Checkbox(); b = (Checkbox)e.getSource(); if ( b.getLabel().equals("Rectangle") ){ Shape = 1; } else if ( b.getLabel().equals("Circle") ){ Shape = 2; } else if ( b.getLabel().equals("Square") ){ Shape = 3; } else if ( b.getLabel().equals("Triangle") ){ Shape = 4; } }
  • 244. The DrawControl program (continued) if (e.getSource() instanceof Choice) { String choice = (String) e.getItem(); if (choice.equals("red")) { targetColor=Color.red; } else if (choice.equals("green")) { targetColor=Color.green; } else if (choice.equals("blue")) { targetColor=Color.blue; } else if (choice.equals("pink")) { targetColor=Color.pink; } else if (choice.equals("orange")) { targetColor=Color.orange; } else if (choice.equals("black")) { targetColor=Color.black; } } } }
  • 245. Some Features of AWT • Frames • Checkbox • Checkbox Group: Radio Button • Choice • Button
  • 246. Word Bank • Abstract Class • Component • Frame • Dialog • Panel • Layout Manager
  • 247. End of Lesson 10 SUMMARY
  • 248. Self-check package Lesson10; import java.awt.event.*; import java.awt.*; public class MyPanel { public static void main(String args[]) { Panel WestPanel = new ________; // initialize the panels Panel CenterPanel = new ________; Panel EastPanel = new ________; Panel MainPanel = new ________; Frame f = new Frame(); WestPanel.setLayout(new ________); // set panel layout ________.____(new Label(" 1 ")); // add item to west panel ________.____(new Label(" 2 ")); ________.____(new Label(" 3 ")); ________.____(new Label(" 4 ")); ________.____(new Label(" 5 ")); ________.____(new Label(" 6 ")); CenterPanel.add(new Label(" 1 ")); CenterPanel.add(new Label(" 2 ")); CenterPanel.add(new Label(" 3 ")); CenterPanel.add(new Label(" 4 ")); CenterPanel.add(new Label(" 5 ")); CenterPanel.add(new Label(" 6 ")); f.add(WestPanel,___________.______); f.add(CenterPanel,BorderLayout.CENTER); f.add(new Label("East"),BorderLayout.EAST); f.add(new Label("North"),BorderLayout.NORTH); f.add(new Label("South"),BorderLayout.SOUTH); f.________(250,250);//set the window size f.________(true); //allows the panel to be visible f._______________(new _____________(){// listen for an event in the window public void windowClosing(WindowEvent e) { System.exit(0); } } ); } }
  • 249. End of Lesson 10 LABORATORY EXERCISE