viernes, 10 de junio de 2016

Java Resume Repaso

CHAPTER 0 An Overview of Computers and Programming Languages

public class MyFirstJavaProgram
{
    public static main(String[] args)
    {
        System.out.println("My first java program.");
    }
}

MyFirstJavaProgram.java  --> MyFirstJavaProgram.class

CHAPTER 1 Basic Elements of JAVA

public class SimpleJavaProgram
{
    public static main(String[] args)
    {
        System.out.println("My first java program");
        System.out.println("La suma de 5 + 8 = " + 13 );
        System.out.println("7 + 8 = " + (7 + 8));
    }
}

Primitive Data types
Boolean
Floating-point
      float    -3.4E+38 @ 3.4E+38
            double   -1.7E+308 @ 1.7E+308
Integral
        Integral Data types
            char        2 bytes (16bits)    0 a 65536 ( 2^16 - 1)
            byte        1 byte    (8 bits)    -128 a 127 ( -2^7 @ 2^7 -1 )
            short        2 bytes (16 bits) -32768 a 32767 ( -2^15 @ 2^15 - 1)
            int            4 bytes (32 bits) -2147483648 a 2147483647 (-2^31 @ 2^31 - 1)
            long        8 bytes (64 bits)
           
casting
(int)(7.9)                7.9
(int)(3.3)                3.3
(double)(25)            25.0
(double)(5 + 3)        8.0
(double)(15) / 2  15.0 / 2
                                    15.0 / 2.0 = 7.5
(double)(15 / 2)  (double) (7) because 15/2 = 7
                                    7.0
                                   
CLASS String
"The sum = "  + 12 + 24

Named Constants, Variables, and Assigment Statements

Named Constants
  [static] final datatype IDENTIFIER = value;
   
    final specifies that the value stored in the identifier is fixed and cannot be changed
   
final double CENTIMETERS_PER_INCH = 2.54;
final int NO_OF_STUDENTS = 20;
final char BLANK = ' ';

int first = 13;
char ch = ' ';
double x = 12.23;

count++;   ++count;
count--;     --count;

Creating a Java Program

public class ClassName
{
    classMembers;
}

public static void main(String[] args)
{
    statment1
    ..
    statemenn
}
                   
public class MyProgram
{
   static final int NUM_CONST = 12;
   
     public static void main(String[] args)
     {
             int firstNum;
            int secNum;
           
            firstNum = 12;
            thirtNum = firstNum + NUM_CONST;
           
CHAPTER 2 INPUT/OUTPUT   

Input Read Statement

class Scanner

[static] Scanner console = new Scanner(System.in);

console.nextInt();          as integer
console.nextDouble();                as floating-point
console.next();                            as string
console.nextLine();                    as string, until EOL also reads /n, but not                                                                     retained

//This programilustrates how to read strings and numeric data

import java.util.*;

public class Example2_3
{
  static Scanner console = new Scanner(System.in);
   
    public static void main(String[] args)
    {
        String firstName;
        String SecondName;
       
        int age;
        double weight;
       
        System.out.println("Enter first name, last"
                                            +"name, age, and weight, "
                                            +"separated by spaces.");
        firstName = console.next();
        LastName = console.next();
       
        age = console.nextInt();
        weight = console.nextDouble();
       
        System.out.println("NAme: " + firstName + " " + last Name);
        System.out.println("age: " +  age);
        System.out.println("weight:" + weight);
    }
}

reading a Single Character

ch = console.next().charAt(0);
    }
}

     }
}

\n newline  \t   tab   \b Backspace  \r  return  \\ Backslash \' single quotation  \" double quotation

formating Output with printf

System.out.printf( formatString);
System.out.printf( formatString, argumentList);

System.out.printf("There are %.2f inches in %d centimeters.%n",centimeters / 2.54, centimeters);

%[argument_index$][flags][width][.precision]conversion

    argument_index - is a (decimal) integer indicating the position of the                                                 argument in the argument list, fisrt is referenced as "1$",                                     second "2$" etc...

    flags - is a set of characters that modifies the output format, depends on                     conversion.
   
    width - (decimal) integer indicating the minimum number of characters to be
                    written to the output device.
                   
    precision - (decimal) integer used to restrict the number of characters.
   
    conversion - character indicating the format.
   
        's'    - general     the result as string
        'c' - character the result in a Unicode Character
        'd' - integral    "        "  formatted as a (decimal) integer.
        'e' - floating point  the result formatted as a decimal number in
                    computerized scientific notation
        'f' - floating poing  the result is formatted as a decimal number
        '%' - percent   the result in '%'
        'n' - line separator  platfrom-specific line separator
       
import java.util.*;
public class LabJava
{
    static final int NUMBER = 12;
    static Scanner console = new Scanner(System.in);
   
    public static void main(String[] args){
      int firstnum;
        int secNum;
       
        ...
    }
}
       
File Input/Output

Scanner console = new Scanner(System.in);

class FileReader  in package java.io     //to read a file
class PrintWriter in package java.io     //to write to a file

Scanner inFile = new Scanner(new FileReader("texto.dat"));

file employeeData.txt with: Beto Martinez 45 120.43

import java.util.*;
import java.io.*;

Scanner inFile = new Scanner(new FileReader("employeeData.txt"));

String firstName;
String lastName;

double hoursWorked;
double payRate;
double wages;

firstName = inFile.next();
lastName = inFile.next();

hoursWorked = inFile.nextDouble();
payRate = inFile.nextDouble();

wages = hoursWorked * payRate;

inFile.close();

Storing (Writing) Output to a File

PrintWriter outFile = new PrintWriter("prog.out");

Parsing Numeric Strings

Integer.parseInt(strExpression);
Float.parseFloat(strExpression);
Double.parseDouble(strExpression);

Integer.parseInt("2343");
Integer.parseInt("-832");
Float.parseFloat("34.34");
Float.parseFloat("-532.34");
Double.parseDouble("34.3434342");
Double.parseDouble("-743.323443");

Using Dialog Boxes for Input/Output

package javax.swing;
class JOptionPane;

str = JOptionPane.showInputDialog("Dame tu nombre y presion OK");

JOptionPane.showMessageDialog(parentComponent,
                                                          messageStringExpression,
                                                            boxTitleString, messageType);
           
            messageType:  JOptionPane.ERROR_MESSAGE,
                                        JOptionPane.INFORMATION_MESSAGE,
                                        JOptionPane.PLAIN_MESSAGE,
                                        JOptionPane.QUESTION_MESSAGE,
                                        JOptionPane.WARNING_MESSAGE
                                       
JOptionPane.showMessageDialog( null, "Hola Cabezones!", "Aqui el Titulo",
                                        JOptionPane.INFORMATION_MESSAGE);
                                       
JOptionPane.showMessageDialog( null, "Cantidad = $" + 500.43, "A Cobrar",
                                        JOptionPane.PLAIN_MESSAGE);
                                       
import javax.swing.JOptionPane;
o
import javax.swing.*;

System.exit(0);

String Format Method

String.format(formatString, argumentList)

double x = 15.674;
double y = 235.73;
double z = 9525.9864;

int num = 83;

String str;

String.format("%.2f", x)                                            "15.67"
String.format("%.3f", y)                                            "235.730"
String.format("%.2f", z)                                            "9525.99"
String.format("%7s", "Hello")                                    "   Hello"
String.format("%5d%7.2f", num, x)                            "   83  15.67"
String.format("The value of num = %5d", num)  "The value of num =   83"
str = String.format("%.2f", z)                                "9525.99"

String.format("%.2f", x)
                                       


CHAPTER 3 Introduction to Objects and Classes

int x;
String str;
x = 45;
str = "Java Programming";
str = new String("Java Programmin");

system.gc();  //garbage collector

Modificadores de metodos
public, private, protected, static, abstract

import java.lang.Math.*
Math.pow(2,3)
import static java.lang.Math.*
pow(2,3)

import static java.lang.Math.*;
public class PredefinedMathMethods
{
    public static void main(String[] args)
    {
        System.out.println("2 al cubo" + pow(2,3));
        System.out.println("el mayor de 12.35 y 54.23 = " + max(12.35,54.23) );
        System.out.println("el absouluto de -67 =" + abs(-67));
        System.out.println("floor(43.23) = " + Math.floor(43.32));
        System.out.println("floor(43.23) = " + floor(43.32));
        System.out.println("sin(PI/2) = %2.f %n", sin(PI/2) );
    }
}

Primitive Data Types and Wrapper Classes

class String

StringVarible.StringMethodName(parameters);

name.length();

String sentence;
sentence = "Programming with Java";
                                                                                                    returns
charAt(index)                        sentence.charAt(3)        'g'
indexOf(ch)                            sentence.indexOf('J')         17
                                                sentence.indexOf('a')            5
                                                sentence.indexOf('x')            -1
indexOf(ch, pos)                sentence.indexOf('a', 10)    18
indexOf(str)                        sentence.indexOf("with")    12
                                                sentence.indexOf("ing")        8
indexOf(str, pos)                sentence.indexOf("a", 10)    18
                                                sentence.indexOf("Pr",10) -1
concat(str)                            sentence.concat(" is fun.")
length()                                sentence.lenght()                    21
replace(
charToBeReplaced,
charReplacedWith)                sentence.replace('a','*') "Progr*aming with J*v*"
substring(beginIndex)        sentence.substring(12)        "with Java"
substring(
beginIndex,
endIndex)                                sentence.substring(0,11)    "Programming"
toLowerCase()
toUpperCase()

class Integer

Integer intObj = new Integer(32);
Integer intObj = new Integer("32");

compareTo(anotherInteger)            Integer num1 = new Integer(32);
                                                            Integer num2 = new Integer(12);
                                                            num1.compareTo(num2)
intValue()                                        num1.intValue()                    32                                            doubleValue()                                    num1.doubleValue()            32.0
equals(obj)                                        num1.equals(num2)      value false
parseInt(str)
toString()

class Character            java.lang;
isDigit()
isLetter()
isLowerCase()
isUpperCase()
isSpaceChar()
isWhiteSpace(ch)
toLowerCase(ch)
toUpperCase(ch)

Methods

method modifiers public, private, protected, static, abstract, final

static methods cannot call another nonstatic methods of the class.

Classes
  modifier(s) class ClassIdentifier modifier(s)
    {
      classMembers
    }

Variable Declaration and Object Instantiation

myTemp and yourTemp as reference variables of type Thermometer

Thermometer myTemp;
Thermometer yourTemp;

These statements do not allocate memory spaces to store data.

new className();
or
new className( arg1, arg2, arg3, ..., argN);

myTemp = new Thermometer();
yourTemp = new Thermometer(35);

GUI JFrame, JLabel, Colors, Fonts, JButton, and Handling an Event(Optional)

JFrame
...
JLabel
...
class Color
...
class Font
...
JButton
public JButton(Icon c)
public JButton(String Str)
public JButton(String str, Icon c)
public void setText(String str)
public String getText()
public void addActionListener(ActionListener obj)
        method to register a listener object to the button object
       
private JButton colorB, fontB;

colorB = new JButton("Color");
fontB = new JButton("Font");

pane.add(colorB);
pane.add(fontB);
       
...
Handlig an Event

Clicking a JButton generates an event, known as action event, which sends messages to another object, known as an action listener

public interface ActionListener
{
    public void actionPerformed( ActionEvent e);
}

private class ColorButtonHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e){
       //code to be performed ...
    }
}

  To Create a listener object of type ColorButtonHandler
   
    ColorButtonHandler cHandler;
   
    cHandler = new ColorButtonHandler; //instatiate the object
    colorB.addActionListener(cHandler);
   
Now For JButton fontB   
   
private class FontButtonHandler implements ActionListener
{
  public void actionPerformed(ActionEvent e)
    {
      javaL.setFont(new Font("Arial", Font.BOLD, 24));
        programmingL.setFont(new Font("Arial", Font.BOLD, 24));
    }
}

FontButtonHandler fHandler;
fHandler = new FontButtonHander();
fontB.addActionListener(fHandler);

Listener Class
private class ColorButtonHandler implements ActionListener
{
    public void actionPreforment(ActionEvent e)
    {
      ...
    }
}

Component Object
colorB = new JButton("Color");                                                                                               
cHandler = new ColorButtonHandler();
colorB.addActionListener(cHandler);


CHAPTER 4 Control Structures I: Selection

a.Sequence     b.Selection       c.Repetition

String str1 = "Hello";
String str2 = "Hi";

str1.compareTo(str2)

if (logical expression)
    statement
   
if (logical expression)
  statement1
else
  statement2

Conditional Operator (? : )
testExpression ? expresionIfTrue : expressionIfFalse

System.out.println("Se compraron " + (numero == 1) ? "Articulo" : "Articulos");

switch Structures

switch (expression)
{
    case value1:
        statement1
        break;
    case value2:
        statement2
        break;
    case value3:
        statement
        break;
       
    default:
        statements
}

GUI JTextFields and JPanel
JTextFields
...
    handling the events
...
JPanel
...
    handling the events
...


CHAPTER 5 Control Structures II: Repetition

while (logical expression)
    statement
   
for (initial exp; logical exp; update expression)
  statement
   
do
  statement
while (logical exp);

break statement;

GUI Graphics ans JTextAreas
class Graphics
...

}


class StringBuffer can append() or delete(), use it class instead of String
                                        if you need to change the value of a passed as parameter
                                       
Method Overloading

public void methodXYZ()
public void methodXYZ( int x, double y)
public void methodXYZ( double one, int y)
public void methodXYZ( int x, double y, char ch)

CHAPTER 6 User-Defined Methods and Classes

        Clock
-hr: int
-min: int
-sec: int
+Clock()
+Clock(int, int, int)
+setTime(int, int ,int): void
+setHours(int): void
+setMinutes(int): void
+setSeconds(int): void
+getHours(): int
+getMinutes(): int
+getSeconds(): int
+printTime(): void
+incrementSeconds(): int
+incrementMinutes(): int
+incrementHours(): int
+equals(Clock): boolean
+makeCopy(Clock): void
+getCopy(): Clock


copy constructor

public ClassName(ClassName otherObject)

public Clock(Clock otherClock)
{
  hr = otherClock.hr;
    min = otherClock.min;
    sec = otherClock.sec;
}

static Variables (data members) of a Class

 When you instantiate the object of type MyClass, only the non static data members of the class MyClass become the data members of each object, What about the memory for the static data members of MyClass? For each static data member of the class java allocate memory space only once. All MyClass reference variables refer to the same memory space. In fact, static data members of a class exist before any object of the class type is instantiated, even when no object of the class tyoe is instantiated. Also , static variables are initialized to their default value.

 Accessor and Mutator Methods

 Reference this (optional) used implicit

 Inner Classes - classes defined within other classes are called inner classes

 CHAPTER 7 ARRAYS

 dataType[] arrayName;

 arrayName = new dataType[intExp];

 dataType[] arrayName = new dataType[intExp];

 int[] num = new int[5];

     num[0]   0
         num[1]        0
         num[2]        0
         num[3]        0
         num[4]        0

int[] list = new int[10]
       
         list[0]    0
         list[1]    0
         list[2]    0
         ...
         list[10]    0
       
final int ARRAY_SIZE = 10;
int[] list = new int[ARRAY_SIZE];

Specifying Array Size During Program Execution
int arraysize;
System.out.println("Enter the size of the array");
arraySize = console.nextInt();
System.out.println();

int[] list = new int[arraysize];

double[] sales = {12.35, 32.50, 16.90, 23, 45.68};

int[] list = {10, 20, 30, 40, 50, 60};

 int   alpha[], beta;   //only alpha is array reference variable, beta is int
 int[] gamma, delta;    //array reference variables, both.

 list.length;
sales.length;

for ( int i = 0, i < list.length; i++){
    list[i] = 0;
}

Array Index Out of Bounds Exception
ArrayIndexOutOfBoundException

public static void ArrayAsFormalParameter(int[] listA,
                                                                                    double[] listB,
                                                                                   int num)
{
  //..
}

int[] listA = {5, 10, 15, 20, 25, 30, 35};
int[] listB = new int[listA.length];

listA --> {5, 10, 15, 20, 25, 30, 35}
listB --> {0,  0,  0,  0,  0,  0,  0}

listB = listA;     listB point to listA data

boolean areEqualArrays(int[] firstArray, int[] secondArray)
{
  //..
}

Arrays and Variable Length Parameter List  (dataType ... identifier)

public static double largest(double x, double y)
public static double largest(double x, double y, double z)
public static double largest(double x, double y, double z, double u)
public static double largest(double x, double y ......)

public static double largest(double ... list)
{
  double max = 0.0;
    if (list.length != 0){
      max = list[0];
        for(int i = 1; i < list.lenght; i++){
        if (max < list[i])
            max = list[i];
        }
    }
    return max;
}

Two-Dimensional Arrays

  dataType[][] arrayName;
   
    arrayName = new dataType[intExp1][intExp2];
   
    dataType[][] arrayName = new dataType[intExp1][intExp2];
   
Instance Varialbe length

int[][] matrix = new int[20][15];

matrix.length    is  20

matrix[0].length  is 15

board = new int[5][];
board[0] = new int[6];
board[1] = new int[2];
board[2] = new int[5];
board[3] = new int[7];
board[4] = new int[2];

Initialization During Declaration

int[][] board = { {2,3,1},
                                  {15,25,13},
                                    {20,4,7},
                                    {11,18,14} };
int[][] board = { {2,3,1,5},
                                  {15,25},
                                    {11,18,14} };

public static void printMatrix( int[][] matrix)
{
 ...
}

dataType[][]..[] arrayName = new dataType[intExp1][intExp2] ... [intExpn];

GUI JCheckBoxes, JRadioButtons, JComboBoxes, and JList

JCheckBox
...
JRadioButton
...
JComboBox
...
JList
...

CHAPTER 8 Applications of Arrays

...

class Vector

 Vector can grow and shrink during program execution.

public Vector();
public Vector(int size);
public void addElement(Object insertObj)
     //add element at end
public void insertElementAt(Object insertObj, int index)
  // insert the object at index
    //ArrayIndexOutOfBoundsException
public boolean contains(Object obj)
  //returns true if the Vector object contains the element specified
public Object elementAt(int index)
public Object lastElement()
  //if empty, throws NoSuchElementException
public int indexOf(Object obj)
  // return index of first occurrence
    //if not return -1
public int indexOf(Object obj, int index)
public boolean isEmpty()
  //return true or false
public int lastIndexOf(Object obj)
  //starting at the last element, using backeard search
public int lastIndexOf(Object obj, int index)
public void removeAllElements()
public boolean removeElement(Object obj)
public void removeElementAt(int index)
public void setElementAt(Object obj, int index)
public void setElementAt(Object obj, int index)
public int size()
public String toString()

Vector<String> stringList = new Vector<String>();

stringList.addElement("spring");
stringList.addElement("Summer");
stringList.addElement("Fall");
stringList.addElement("winter");

System.out.println(stringList);

[spring, Summer, Fall, winter]

stringList.addElement("cool", 1);

[spring, cool ,Summer, Fall, winter]

Primitive Data Types and the class Vector

Vector<Integer> list = new Vector<Integer>();

list.addElement(13);
list.addElement(25);
   is similar to
list.addElement(new Integer(13));
list.addElement(new Integer(25));

Vector Objects and the foreach loop

for (type identifier : vectorObject)
  statements
   
Vector<String> stringList = new Vector<String>();

stringList.addElement("one");
stringList.addElement("two");
stringList.addElement("three");
stringList.addElement("four");
stringList.addElement("five");
stringList.addElement("six");

System.out.println( stringList);

for (String str : stringList)
{
    System.out.println(str.toUpperCase());
}

GUI Layout Managers, Menus, and Applets

layout Managers
FlowLayout

Container pane = getContentpane();

pane.setLayout(new FlowLayout());
or
FlowLayout flowLayoutMgr = new FlowLayout();
pane.setLayout( flowLayoutMgr);

flowLayoutMgr.setAlignment(FlowLayout.RIGHT);

BorderLayout
...
Menus
...

Applets   class JApplet  (package javax.swing)

   refers to little aplication
   
public void init()
  //called by the browser of applet viewer to inform this applet that is has
    // been loaded into the systme

public void start()
  //.......that it should start its execution
   
public void stop()
  // .......that it should stop its execution
   
public void destroy()
  //..... that it is being reclaimed and that it should destroy any resources
   
public void showStatus( String msg)
  // display the String msg in the status bar
   
public Container getContentPane()
  // returns the ContentPane object for this applet

public void update(Graphics g)
  // Call the paint() method
   
protected String paramString()
  // Return a string representation of this JApplet; used mainly for debugging
   
import java.awt.Graphics;
import javax.swing.JApplet;

public class WelcomeApplet extends JApplet
{
  public void paint( Grapics g)
    {
        super.paint(g);
        g.drawString("Welcome to Java Programming", 30, 30);
    }
}

<html>
<head>
    <title>Welvome Applet</title>
</head>
<body>
    <object code = "WelcomeApplet.class" width = "250" height = "60">
    </object>
</body>
</html>

appletviewer WelcomeApplet.html

CHAPTER 9  Inheritance and PolyMorphism

Inheritance

modifier(s) class className extends ExistingClassName modifier(s)
{
    memberList
}

public class circle externds shape
{
 ...
}

Using methods of the SuperClass in a Subclass (super)

public void setDimension(double l, double w, double h)
{
  super.setDimension( l, w);
   
    if( h >= 0)
        height = h;
    else
        height = 0;
}

Contructor of the Superclass and Subclass

public Box()
{
    super();
    height = 0;
}

if super is not included in subclass, by default the dafault constructor of the superclass (if any) will be called

Protected Members of a Class -
members of a class that can be accessed by subclass members

class Object

 include method toString() returns the class name followed by the hash code of the Object

public class Clock extends Object
{
  ...
}

Some methods of Object
public Object()   //Constructor
public String toString()
public boolean equals(Object obj)
  // if same memory space
protected Object clone()
  // reference to a copy of the object
protected void finalize()
  // is invoked when the object goes out of scope
   
Java Stream Classes

  Object
            Scanner
            Reader
                    InputStreamReader   FileReader
            Writer
                    PrintWriter
                   
Polymorphism via Inheritance

Java allow us to treat an object of a subclass as an object of its superclass. In Other words, a reference variable of a superclass type can point to an object of its subclass. In some situations, this feature of java can be used to develop generic code for a variety of applictions.

Person name, nameRef;
PartTimeEmployee employee, employeeRef;

name = new Person( "John", "Blair");
employee = new PartTimeEmployee("Susan", "Johnson", 12.50, 45);

nameRef = employee;
System.out.prinrln("nameRef: " + nameRef);

nameRef: Susan Johnson's wages are: $562.5

IF a method of a class is declared final, it cannot be overriden with a new definition in a derived class.

  public final void doSomeThing()
    {
      // this method can not be overriden
    }

Operator instanceOf

p instanceOf BoxShape     returns true if p points to an object of the class                                                         BoxShape

Abstract Methods and Clases

  An Abstract method is a method that has only a heading but no body. The heading of an abstract method contains the reserved word abstract and ends with a semicolon
   
    public void abstract print();
    public abstract object larger(object, object);
    void abstract insert(int insertItem);
   
  An Abstract Class is a class that id declared with the reserved word abstract in its heading.
     - An abstract class can contain instance variables, constructors, and non         abstract methods
     - An abstract class can contain one or more abstract methods.
     - If a class contains an abstract method, the class must be declared                 abstract.
     - You cannot instantiate an object  of an abstract class; you can only
             declare a reference variable of an abstract class type.
     - You can instantiate an object of a subclass of an abstract class, but only
             if the subclass gives the definitions of all the abstract methods of the
            superclass.
           
public abstract class AbstractClassExample
{
  protected int x;
    public abstract void print();
    public void setX(int a)
    {
        x = a;
    }
    public AbstractClassExample()
    {
        x = 0;
    }
}

Interfaces

Java does not support multiple inheritance; a class can extend the definition of only one class. The events are handled by implementing separete interfaces.

An Interface is a type of class that contains only abstract methods and/or named constants. Interfaces are defined using the reserved word interface in place of the reserved word class.

public interface WindowListener
{
    public void windowOpened(WindowEvent e);
    public void windowClosing(WindowEvent e);
    public void windowClosed(WindowEvent e);
    public void windowIconified(WindowEvent e);
    public void windowDeiconified(WindowEvent e);
    public void windowActivated(WindowEvent e);
    public void windowDeactivated(WindowEvent e);
}

public interface ActionListener
{
    public void actionPerformed(ActionEvent e);
}

public class ExampleInterfaceImp implements ActionListener,
                                                                                        WindowListener
{
        // Definitions of each method requierd by interfaces ActionListener
        // and WindowListener
}

Polymorphism via Interfaces

  public interface Employyee
  {
      public double wage();
        public String department();
    }

  Employee newEmployee;
   
    newEmployee = new Employee();  //ilegal
   
    class FullTimeEmployee that implements the interface Employee.
  you can use the reference variable newEmployee to create an object of the class FullTimeEmployee.
   
    newEmployee = new FullTimeEmployee();
   
    double salary = newEmploye.wages();
   
    newEmployee = new PartTimeEmployee();
   
    class FullTimeEmployee contains the method
     public void upDatePayRate(double increment)
     {
       ...
     }
   
    newEmployee.upDatePayRate(23);  //causes compiler error

  ((FullTimeEmployee)newEmployee).upDatePayRate(25);


Composition (Aggregation)
  One or more members of a class are objects of one or more other classes.
    "has-a" relation;for example, "every person has a date of birth"
   
CHAPTER 10 EXception Handling and Events

try/catch/finally block

try
{
  //statements
}
catch (ExceptionClassName objRef1)
{
  // exception handler code
}
catch (ExceptionClassName objRef1)
{
  // exception handler code
}
...
catch (ExceptionClassName objRef1)
{
  // exception handler code
}
finally
{
    // statemets
}

Java Exception Hierarchy

Object - Throwable - Exception

public static void exceptionMethod()
                        throws InputMismatchException, FileNotFoundException
{
 //statements
}

Rethrowing and Throwing an Exception

throw exceptionReference;

throw new ExceptionClassName(MessageString);

import java.util.*;

public class RethrowExceptionExample
{
    static Scanner console = new Scanner(System.in);
   
    public static void main(String[] args)
    {
      int number;
       
        try{
            number = getNumber();
            System.out.println("Line11: number = " + number);
        }
        catch (InputMistmatchException imeRef)
        {
            System.out.println("Line15: Exception " + imeRef);
        }
    }
   
    public static int getNumber()
                            throws InputMismatchException
    {
      int num;
        try
        {
           System.out.println("Line 23: enter an " + "integer:");
             num = console.nextInt();
             return num;
        }
        catch (InputMismatchException imeRef)
        {
           throw imeRef;
             or
             throw new InputMismatchException("getNumber");
        }
    }
}

CHAPTER 12 Generics, Dynamic Representations and Collections


public static void print(int ... list)
{
  for (int elem : list)
        System.out.print(elem + " ");
    System.out.println();
}

public static void print(double ... list)
{
  for (double elem : list)
        System.out.print(elem + " ");
    System.out.println();
}

public static void print(String ... list)
{
  for (String elem : list)
        System.out.print(elem + " ");
    System.out.println();
}

modifier(s) <T> returnType methodName(formal parameter list)
{
  ...
}

T ref;  //ok
ref = new T();  //illegal

public static void print( T ... list)
{
    for ( T elem : list)
        System.out.print(elem + " ");
    System.out.println();
}

Generic Classes

 modifier(s) className<T> modifier(s)
 {
   //class members
 }

 The interface Comparable

 public class Clock implements Comparable


    public int compareTo(Object otherClock)
        {
           Clock temp = (Clock) otherClock;
           
             int hrDiff = hr - temp.hr;
           
             if (hrDiff != 0)
                     return hrDiff;
                   
             int minDiff = min - temp.min;
           
             if ( minDiff != 0)
                     return minDiff;
                   
             return sec - temp.sec;
        }

Generic Methods and Bounded Type Parameters

public static <T> void print(T ... list)
{
   for ( T elem : list)
     {
             System.out.print(elem + " ");
     }
}

 public static <T extends Comparable<T> > T larger(T x, T y)
 {
   if (x.compareTo(y) >= 0)
       return x;
    else
       return y;
 }

 Collections

 class LinkedList

 public class LinkedList<E> extends AbstractSequentialList<E>
 constructors
 public LinkedList();
 public LinkedList(Collection<? extends E> coll)
 methods
 public add(E obj)
 public void add(int index, E elem)
 public void addFirst(E obj)
 public void addLast(E obj)
 public void clear()
 public Object clone()
 public boolean contains(Object obj)
 public E get(int index)
 public E getFisrt()
 public E getLast()
 public int indexOf(Object obj)
 public int lastIndexOf(Objedt obj)
 public ListIterator<E> listIterator(int index)
 public E peek()
 public E poll()
 public E remove(int index)
 public E remove()
 public boolean remove(Object obj)
 public E removeFirst()
 public E removeLast()
 public int size()




 Iterators

 public ListIterator<E> listIterator(int index)
   //return a list of iterator of the elemnts in this list,
     // starting at the position specified by index.
     // IndexOutOfBoundsException
   
public interface Iterator<E>
methods
boolean hasNext()
E    next()
void remove()
  // remove the last element
   
public interface ListIterator<E> extends Iterator<E>
methods
void add(E obj)
boolean hasNext()
boolean hasPrevious()
E next()
int nextIndex()
E previous()
int previousIndex()
void remove()
void set(E obj)

//iterator works with a LinkedList object
import java.util.*;

public class LinkedListAndIterator
{
    public static void main(String[] args)
    {
        LinkedList<Integer> intLList = new LinkedList<Integer>();
       
        Integer[] intArray = { 23, 12, 33, 89, 54, 9 ,77, 55, 8, 19, 30
                                                    ,15,62};
                                                   
        for(Integer num : intArray)
                intLList.add(num);
               
        System.out.println("line 10: intLList:\n" + "   ");
   
      print(intLList);
       
        ListIterator<Integer> listIt = intLList.ListIterator(0);
       
        System.out.println("line13: listIt points " + "to: " + listIt.next());
       
        System.out.println("line14: listIt points " + "to: " + listIt.next());
       
        listIt.set(999);
       
        System.out.println("line16: intLList " + "    ");
       
        print(intLList);
       
        listIt.add(1111);
       
        System.out.println("line19: after adding" + "1111 intLList:\n");
       
        print(intLList);
    }
   
    public static <T> void print(Collection<T> c)
    {
        for (T obj: c)
            System.out.print(obj + " ");
           
    }
}

LinkedList<Integer> intList = new LinkedList<Integer>();

Integer[] intArray = {23, 12, 33, 89, 54, 9 ,77,
                                            55, 8, 19, 30, 15, 62};
                                           
for (Integer num: intArray)
  intList.add(num);
   
ListIterator<Integer> listIt = intList.listIterator<0>

System.out.println(listIt.next());

listIt.set(999);

intList = {23, 999, 33, 89, 54, 9 ,77,
                                            55, 8, 19, 30, 15, 62};

listIt.add(1111);

intList = {23, 999, 1111, 33, 89, 54, 9 ,77,
                                            55, 8, 19, 30, 15, 62};


JAVA SERVER PROGRAMMING

Servlet container
init()
service()
destroy()

The Servlet API
javax.servlet and javax.servlet.http

Servlet Interface
public interface Servlet

javax.servlet.Servlet

when implementing Servlet interface, the following five methods must be implemented

init() method
service() method
destroy() method
getServletConfig() method
getServletInfo() method

public void init(ServlerConfig config) throws ServletException

public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException

public void destroy()

public ServletConfig gerServletConfig()

public String getServerInfo()

HttpServlet Class
HttpServlet class extends GenericServlet

service() method

  protected void service(HttpServletRequest req, HttpServletResponse res)                     throws ServletException, IOException
    public void service(ServletRequest req, ServletResponse res)
                throws ServletException, IOException
               
getLastModified() method

  protected long getLastModified(httpServletRequest req)

HttpServletRequest Interface

  public interface HttpServeltRequest extends ServletRequest
   
getParameter() method
  public String getParemeter(String key)

getParameterValues() method
    public String[] getParemeterValues(String key)
   
getParemetrNames() method
    public Enumeration getParameterNames()
   
HttpServletResponse Interface
    public interface HttpServletResponse extends ServletResponse
   
setContentType() method
    public void setConentType(String type)
   
getWriter() method
    public PrintWriter getWriter() throws IOException

getOutputSteam() method
    public ServletOutputStream getOutputStream() throws IOException
   
setHeader() method
    public void setHeader(String name String value)
   
//Import Servlet libraries
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet
{
    public void doGet(HttpServletRequest req, HttpServletResponse res)
                                trhows ServletException, IOException
    {
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
       
        out.println("<HTML>");
        out.println("<HEAD>");
        out.println("<TITLE>Hello World Sample Servlet</TITLE>");
        out.println("</HEAD>");
        out.println("<BODY>");
        out.println("CENTER><H1>Hello World!</H1></CENTER>");
        out.println("</BODY>");
        out.ptintln("</HTML>");
       
        out.close();
    }
}

Processig Form Data and Sending Email

Gathering Form Data

String message, msgForm, msgTo, msgSubject;

private void getParemeters(HttpServletRequest req)
        throws ServletException, IOException
{
    StringBuffer tempStringBuffer = new StringBuffer(1024);
   
    msgSubject = "Tech Support Request";
    msgTo = "tech@mail.com";
   
    msgFrom = req.getParameter("txtEmail");
    tempStringBuffer.append("From: ");
    tempStringBuffer.append("req.getParameter("txtFirst"));
    tempStringBuffer.append(" ");
    tempStringBuffer.append("req.getParameter("txtLast"));
    tempStringBuffer.append("\n");
    tempStringBuffer.append("Phone: ");
    tempStringBuffer.append("req.getParameter("txtPhone"));
    tempStringBuffer.append("\n");
    tempStringBuffer.append("Email:");
    tempStringBuffer.append("req.getParameter("txtEmail"));
    tempStringBuffer.append("\n\n");
    tempStringBuffer.append("Software: ");
    tempStringBuffer.append("reg.getParameter("ddlb_software"));
    tempStringBuffer.append("\n");
    tempStringBuffer.append("OS :");
    tempStringBuffer.append("reg.getParameter("ddlb_os"));
    tempStringBuffer.append("\n\n");
    tempStringBuffer.append("Problem: ");
    tempStringBuffer.append("req.getParameter("txtProblem"));
    tempStringBuffer.append("\n");
   
    message = tempStringBuffer.toString();
}

Send email using SmtpClient

private boolean sendMail()
{
  PrintStream out;
    SmtpClient send;
   
    try
    {
        send = new SmptClient("mail.xyz.com");
        send.from(msgForm);
        send.to(msgTo);
       
        out = send.startMessage();
       
        out.println("From : " + msgForm);
        out.println("To: " + msgTo);
        out.println("Subject: " + msgSubject);
       
        out.println("\n--------------\n");
        out.println(message);
        out.println("\n--------------\n");
        out.flush();
        out.close();
        send.closeServer();
    }
    catch (IOException e) {
      log("Error occurred while sending email", e);
        return false;
    }
    return true;
}

put all this together

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.util.*;

import sun.net.smtp.SmtpClient;

import com.wrox.util.*;

public class techsupport extends HttpServlet
{
    String message, msgForm, msgTo, msgSubject;
   
    public void doPost(HttpServletRequest req, HttpSerlvetResponse res)
        throws ServletException, IOException
    {
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        getParameters(req);
       
        if(!sendMail())
        {
            res.sendError(res.SC_INTERNAL_SERVER_ERROR, "An error ocurred while attemptiong to access the mail server.");
            return;
        }
        //Send acknowledgemenbt to the browser
        HTML h = new HTML("XYZ Corporation IT Department");
        h.add(HTML.HEADING, "your request has been submitted", false);
        out.println(h.getPage());
        out.close();
    }
   
    private void getParameters(HttpServletRequest req)
            throws ServletException, IOException
    {
        StringBuffer tempStringBuffer = new StringBuffer(1024);
        ....
    }
   
    private boolean sendMail()
    {
      PrintStream out;
        SmtpClient  send;
       
        try{
        ...
        }
        ...
    }
}

No hay comentarios:

Publicar un comentario