comp 034 advanced programming language - prelim

Upload: psywar

Post on 02-Jun-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    1/88

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    2/88

    Name: Mr. Lodelio R. MilloEducational Background

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    3/88

    This course provides the students withfundamental understanding of structured

    programming using Java. It introduces thedifferent concepts that are commonlyassociated with structured programming. Thecourse is design to provide students an in-depth look at Java Programming using thestructured approached in a business problem-solving environment

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    4/88

    This course aims to enhance students knowledge in advanceJAVA programming.

    At the end of the course, the students are expected to:

    Appreciate the use of existing java classes such as Math,String, StringBuffer, Wrapper, Process, Runtime andSystem classes.Learn how to use to streams to get input from user,

    manipulate it and display the result.Understand the role of the Java programming language asa front-end for database applications.Understand two-tier and three-tier architectures fordistributed computing.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    5/88

    Tour of java.lang PackageIntroduction to java.langMath Class

    The Character, String and Buffer ClassesWrapper ClassesThe Process of Runtime ClassesThe System Classes

    Basic Formatting ClassesFormatting Number, Currencies and Percentages NumberFormat Class DecimalFormat Class

    Formatting Date and TimeScanner Class

    Introduction to File Handling and StreamConsole I/OWriting the Standard OutputReading from the Standard InputFile and File I/OCreating New File ObjectFile Methods and FacilitiesFile Stream I/O

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    6/88

    Advance I/O StreamI/O FundamentalsData within StreamByte StreamThe InputStream MethodsThe OutputStream Methods

    Character StreamsThe Reader MethodsThe Writer MethodsString Tokenizer

    Basics Byte Stream ClassesThe FileInputStream and the FileOutputStream ClassesThe BufferedInputStream and the BufferedOutputStream Classes

    The DataInputStream and the DataOutputStream ClassesBasic Character Stream Classes

    The InputStreamReader and the OutputStreamWriter MethodsByte and Character ConversionUsing Other Character EncodingThe FileReader and the FileWriter ClassesThe BufferedReader and the BufferedWriter Classes

    The RandomAccessFile Class

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    7/88

    Database Access and MySQL Using JDBCWhat is JDBCConnecting to the databases

    Basic Database Access and MySQLThe JDBC Support ClassesBack-up and Restore MySQL Database

    Swing GUI ComponentUsing JFrame, JInternalFrame, JTextbox, JTextAreaUsing JMenu, JMenuItem, JComboBox, JListUsing Basic Controls

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    8/88

    ThreadsThe Three part of a ThreadCreating a ThreadStarting a ThreadThread Scheduling

    Basics Controls of ThreadsTerminating a ThreadsTesting a ThreadsAccessing Thread PriorityPutting Threads on HoldOther Way to Create Thread

    Selecting a Way to Create a ThreadsUsing Synchronized in Java Technology

    The Object Lock FlagReleasing the Lock FlagThread StatesDeadLock

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    9/88

    Come to class prepared and ready to share. Always come to schoolearlier or on time. (Check your schedule)Respect peoples idea and opinion. Wear proper uniform

    Eating and using cellular phone or any electronic gadget which is notrequired to use is not allowed during class encounter/lesson.Read in advance.Listen to the direction of your instructor.Late submission will not be accepted.Be responsible for the things that you missed. Excuse absences are the

    one with medical certificate and death of the immediate familymembers. Other than those you are considered absent.Observe cleanliness and orderliness.Obey your professor. Do your very best.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    10/88

    Class Standing (60%) :Quizzes/Seatworks 25%

    Long Quiz/Project 15%Attendance 10%Assignments/Oral Participation 10%

    Major Exam (40%)

    TOTAL (100%)

    FINAL GRADE = (PRELIM + MIDTERM + PRE-FINAL + FINAL)/4

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    11/88

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    12/88

    After the completing the lesson, you shouldbe able to appreciate and use the followingclasses

    MathStringStringBuffer

    WrapperProcessSystem

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    13/88

    It is a collection of predefined constants andmethods for performing different

    mathematical operations such astrigonometric functions and logarithm.Most of its methods are defined as static

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    14/88

    public static double abs(double a)Returns the positive value of the parameter. An overloaded method. Can also take in afloat or an integer or a long integer as a parameter, in which case the return type iseither a float or an integer or a long integer, respectively.

    public static double random()Returns a random positive value greater than or equal to 0.0 but less than 1.0.public static double max(double a, double b)Returns the larger value between two double values, a and b. An overloaded method. Canalso take in float or integer or long integer values as parameters, in which case thereturn type is either a float or an integer or a long integer, respectively.

    public static double min(double a, double b)Returns the smaller value between two double values, a and b. An overloaded method.Can also take in float or integer or long integer values as parameters, in which case thereturn type is either a float or an integer or a long integer, respectively.

    public static double ceil(double a)Returns the smallest integer greater than or equal to the specified parameter a.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    15/88

    public static double floor(double a)Returns the largest integer that is lesser than or equal to the specified parameter a.

    public static double exp(double a)Returns Euler's number e raised to the power of the passed argument a.

    public static double log(double a)Returns the natural logarithm (base e) of a, the double value parameter.

    public static double pow(double a, double b)Returns the double value of a raised to the double value of b.

    public static long round(double a)

    Returns the nearest long to the given argument. An overloaded method. Can also take in a float as an argument and returns the nearest int in this case.public static double sqrt(double a)

    Returns the square root of the argument a..

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    16/88

    public static double rint(double a)Returns the closest integers, the even integer is returned

    public static double sin(double a)Returns the trigonometric sine of the given angle a.

    public static double cos(double a)

    Returns the trigonometric cosine of the given angle a.public static double tan(double a)Returns the trigonometric tangent of the given angle a.

    public static double asin(double a)Returns the trigonometric arcsine of the given angle a.

    public static double acos(double a)Returns the trigonometric arccosine of the given angle a.

    public static double atan(double a)Returns the trigonometric arctangent of the given angle apublic static double toDegrees(double angrad)

    Returns the degree value approximately equivalent to the given radian value.public static double toRadians(double angdeg)

    Returns the radian value approximately equivalent to the given degree value

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    17/88

    class MathDemo {public static void main(String args[]) {

    System.out.println("absolute value of -5: " + Math.abs(-5));System.out.println("absolute value of 5: " +Math.abs(-5));System.out.println("random number(max value is 10): " + Math.random()*10);System.out.println("max of 3.5 and 1.2: " + Math.max(3.5, 1.2));System.out.println("min of 3.5 and 1.2: " + Math.min(3.5, 1.2));

    System.out.println("ceiling of 3.5: " + Math.ceil(3.5));System.out.println("floor of 3.5: " + Math.floor(3.5));System.out.println("e raised to 1: " + Math.exp(1));System.out.println("log 10: " + Math.log(10));System.out.println("10 raised to 3: " + Math.pow(10,3));System.out.println("rounded off value of pi: " + Math.round(Math.PI));System.out.println("square root of 5 = " + Math.sqrt(5));System.out.println("10 radian = " + Math.toDegrees(10) + " degrees");System.out.println("sin(90): " + Math.sin(Math.toRadians(90)));

    }}

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    18/88

    absolute value of -5: 5absolute value of 5: 5random number(max value is 10): 4.0855332335477605max of 3.5 and 1.2: 3.5min of 3.5 and 1.2: 1.2

    ceiling of 3.5: 4.0floor of 3.5: 3.0e raised to 1: 2.7182818284590455log 10: 2.30258509299404610 raised to 3: 1000.0rounded off value of pi: 3square root of 5 = 2.2360679774997910 radian = 572.9577951308232 degreessin(90): 1.0Introduction

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    19/88

    Problem: Write a program that determines the time ittakes a ball to hit the ground after it has been droppedfrom an 800-foot tower. The mathematical formula to

    calculate the time in seconds that it takes to fall agiven distance in feet is:

    Where g is the gravitational constant equal to 32.2ft/sec 2 .

    OutputIt will take 7.049073768502414 seconds to fall 800 feet.

    g height time /*2

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    20/88

    public class FallTime {

    public static void main (String[]args){int height;double time;

    height = 800;time = Math.sqrt(2*height/32.2);

    System.out.println("It will take " + time + " seconds to fall " + height + " feet.");}

    }

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    21/88

    Problem: Write a program that accepts therectangular coordinates of two points (x 1, y1)

    and (x2, y2) and calculates and returns thedistance between two points. The distance, d,between two points is given by the formula

    212

    212 )()( y y x xd

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    22/88

    import java.util.*;public class DistanceTwoPoints {

    public static void main(String[]args){Scanner sc = new Scanner(System.in);System.out.print("Enter the value of x1: ");int x1 = sc.nextInt();System.out.print("Enter the value of x2: ");int x2 = sc.nextInt();double a = Math.pow(x2-x1,2);System.out.print("Enter the value of y1: ");int y1 = sc.nextInt();

    System.out.print("Enter the value of y2: ");int y2 = sc.nextInt();double b = Math.pow(y2-y1,2);double d = Math.sqrt(a+b);System.out.println("Distance between two points is: "+d);

    }

    }

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    23/88

    Problem: Write a Java program that convertthe rectangular (x,y) coordinates of a point

    into polar form. That is, given an x and yposition on a Cartesian coordinate system.Calculate the distance from the origin, d, andthe angle from the x axis, , specified by thepoint. The values of d and are referred to asthe points polar coordinates.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    24/88

    Formula:

    AlgorithmGet the x and y coordinates valuesCalculate the polar (r and ) coordinates valuesDisplay the polar coordinates values

    22 y xd

    0),/(tan 1 x x y

    (X, Y)r

    X - axis

    Y - axis

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    25/88

    public class ConvertXY {public static void main(String[] args) {

    double x =3.0; double y = 4.0; double distance, angle;//convert to Polar coordinatesdistance = getDistance(x,y);angle = getAngle(x,y);

    System.out.println("The polar coordinates are: ");System.out.println("Distance from the origin: " + distance);System.out.println("Angle (in degrees) from the x-axis: "+ angle);

    }

    public static double getDistance(double x, double y){return Math.sqrt(Math.pow(x,2)+ Math.pow(y,2));

    }public static double getAngle(double x, double y){

    return Math.toDegrees(Math.atan(y/x));}

    }

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    26/88

    Write a program that simulates the roll of 2six sided dice and then outputs the value of

    each die, and the total sum of the dice. Saveas DiceRoll.java.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    27/88

    public class PairOfDice { private int die1; // Number showing on the first die. private int die2; // Number showing on the second die. public PairOfDice() { // Constructor. Rolls the dice, so that they initially // show some random values. roll(); // Call the roll() method to roll the dice. } public void roll() { // Roll the dice by setting each of the dice to be // a random number between 1 and 6. die1 = (int)(Math.random()*6) + 1; die2 = (int)(Math.random()*6) + 1; } public int getDie1() { // Return the number showing on the first die. return die1;

    } public int getDie2() { // Return the number showing on the second die. return die2; } public int getTotal() { // Return the total showing on the two dice. return die1 + die2; } } // end class PairOfDice

    The Main Program

    public class Main { public static void main(String[] args) { PairOfDice dice; // A variable that will refer to the dice. int rollCount; // Number of times the dice have been rolled. dice = new PairOfDice(); // Create the PairOfDice object. rollCount = 0; /* Roll the dice until they come up snake eyes. */ do { dice.roll(); System.out.println("The dice come up " + dice.getDie1()

    + " and " + dice.getDie2()); rollCount++; } while (dice.getTotal() != 2); /* Report the number of rolls. */ System.out.println("\nIt took " + rollCount + " rolls to get a 2."); } } // end class RollFor2

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    28/88

    A quantity known as the body mass index(MBI) is used to calculate the risk of weight-related health problems. BMI is computed bythe formula of

    Where w is weight in kilograms and h is

    height in centimeters. A BMI of 20 to 25 isconsidered normal. Write an applicationthat accepts weight and height (bothintegers) and output the BMI.

    20.100/hw

    BMI

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    29/88

    If you invest P peso at R percent interest ratecompounded annually in N years, yourinvestment will grow to

    pesos. Write an application that accepts P, R,N and computes the amount of moneyearned each years.

    100/1

    100/1 1

    R R P N

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    30/88

    Write a loan calculator program thatcomputes both monthly and total payments

    for a given loan amount, annual interest rate,loan period.The formula for computing the monthlypayment

    Where L is the loan amount, R is the monthlyinterest rate and N is the number of payment

    N R LR

    ment monthlypay ]1/1[1

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    31/88

    AlgorithmGet three input values: loanAmount, interestRate,

    and loanPeriodCompute the monthly and total paymentsOutput the result

    Input OutputLoan

    AmountAnnualInterest

    Rate

    Loan Period(in years)

    MonthlyPayment

    TotalPayment

    10000 10 10 132.151 15858.088

    15000 7 15 134.824 24268.363

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    32/88

    In this problem, you will complete the codefor a program that computes the surface area

    and volume of a solid cone given the radius ofits base and height. The relevant equationsare:

    V = r2 h / 3A = r2 + r (r2+h2)

    public class Cone { public static void main(String[] args){ //1. declare double variables: h, r, V, and A.// 2. assign a value for h and r// 3. compute volume, V, and surface area, A// 4. display the results } }

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    33/88

    StringCombination of character literals

    Can be represented by array of characters orsimply by using String classString object is immutable or cannot be change

    StringBufferObject of StringBuffer is similar to a String object,except for the fact that the StringBuffer object ismutable or can be modified

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    34/88

    public char charAt(int index)Returns the character located in the specified index.

    public int compareTo(String anotherString)Compares this string with the specified parameter. Returns a negative value ifthis string comes lexicographically before the other string, 0 if both of the

    strings have the same value and a positive value if this string comes after theother string lexicographically.public int compareToIgnoreCase(String str)

    Like compareTo but ignores the case used in this string and the specifiedstring.

    public boolean equals(Object anObject)Returns true if this string has the same sequence of characters as that of theObject specified, which should be a String object. Otherwise, if the specified parameter is not a String object or if it doesn't match the sequence of symbols inthis string, the method will return false.

    public boolean equalsIgnoreCase(String anotherString)Like equals but ignores the case used in this string and the specified string.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    35/88

    public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)Gets the characters from this string starting at the srcBegin index up to the srcEnd index andcopies these characters to the dst array starting at the dstBegin index.

    public int length()Returns the length of this string.

    public String replace(char oldChar, char newChar)Returns the string wherein all occurrences of the oldChar in this string is replaced withnewChar.

    public String substring(int beginIndex, int endIndex)Returns the substring of this string starting at the specified beginIndex index up to theendIndex index.

    public char[] toCharArray()Returns the character array equivalent of this string.

    public String trim()Returns a modified copy of this string wherein the leading and trailing white space areremoved.

    public static String valueOf(-)Takes in a simple data type such as boolean, integer or character, or it takes in an object as aparameter and returns the String equivalent of the specified parameter.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    36/88

    public String toLowerCase()Returns a new string with all characters in lowercase.

    public String toUpperCase()Returns a new string with all characters in upper case.

    public String concat(String anotherString)Concatenates str to the end of a string.

    public boolean endsWith(String suffix)Test if the string ends with the specified string

    public int hashCode()Returns an integer number derived from the string

    public int indexOf(int ch)Returns the position of the first occurrence of the specified character

    public int lastIndexOf(int ch)Returns the position of the last occurrence of the specified character.

    public boolean startsWith(String prefix)Test if the string begins with the specified string

    public boolean startsWith(String prefix, int startPos)Test if the string begins with the specified string, starting at the specified position.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    37/88

    String name = new String ("Jonathan");System.out.println(name = " + name); System.out.println("Jonathan compared to jonathan : " +name.compareTo ("jonathan"));System.out.println("Jonathan compared to jonathan (ignore case): "name.compareToIgnoreCase("jonathan"));System.out.println("Is Jonathan equal to Jonathan? " + name.equals("Jonathan"));

    System.out.println("Is Jonathan equal to jonathan? " + name.equals("jonathan"));System.out.println("Is Jonathan equal to jonathan (ignore case)? " +ame.equalsIgnoreCase("jonathan"));char charArr[] = "Hi XX".toCharArray();"Jonathan".getChars(0, 2, charArr, 3);System.out.print("getChars method: "); System.out.println(charArr);System.out.println("Length of name: " + name.length());System.out.println("Replace a's with e's in name: " + name.replace('a', 'e'));System.out.println("A substring of name: " + name.substring(0, 2));System.out.println("Trim \" a b c d e f \": \"" + " a b c d e f ".trim() + "\"");System.out.println("String representation of boolean expression 10>10: " + String.valueOf(10>10));System.out.println("String representation of boolean expression 10

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    38/88

    name: Jonathan3rd character of name: nJonathan compared to Solomon: -9Solomon compared to Jonathan: 9Jonathan compared to jonathan: -32Jonathan compared to jonathan (ignore case): 0Is Jonathan equal to Jonathan? trueIs Jonathan equal to jonathan? falseIs Jonathan equal to jonathan (ignore case)? truecontent of charArr after getChars method: Hi JoLength of name: 8Replace a's with e's in name: JonethenA substring of name: JoTrim " a b c d e f ": "a b c d e f"String representation of boolean expression 10>10: falseString representation of boolean expression 10

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    39/88

    class Sample2

    public static void main(String[]args){

    String name, first, middle , last, space, monogram;space= ; name = JOptionPane.showInputDialog (Enter your full name (first, middle, last): ); first = name.substring(0, name.indexOf(space));name = name.substring(name.indexOf(space)+1, name.length());middle = name.substring(0,name.indexOf(space));last = name.substring(name.indexOf(space)+1, name.length());

    monogram = first.substring(0,1) + middle.substring(0,1) + last.substring(0,1);

    JOptionPane.showMessageDialog (null, Your monogram is + monogram);

    }}

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    40/88

    public int capacity()Returns the current capacity of this StringBuffer object.

    public StringBuffer append(-)Appends the string representation of the argument to this StringBuffer object. Takes in single parameter which may be of thesedata types: boolean, char, char [], double, float, int, long, Object, String and StringBuffer. Still has another overloaded version.

    public char charAt(int index)Returns the character located in the specified index.

    public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)Gets the characters from this object starting at the srcBegin index up to the srcEnd index and copies these characters to the dstarray starting at the dstBegin index.

    public StringBuffer delete(int start, int end)Deletes the characters within the specified range.

    public StringBuffer insert(int offset, -)Inserts the string representation of the second argument at the specified offset. A overloaded method. Possible data types forthe second argument: boolean, char, char [], double, float, int, long, Object and String. Still has another overloaded version.

    public int length()Returns the number of characters in this StringBuffer object.

    public StringBuffer replace(int start, int end, String str)Replaces part of this object, as specified by the first two arguments, with the specified string str.

    public String substring(int start, int end)Returns the substring of this string starting at the specified start index up to the end index.

    public String toString()Converts this object to its string representation.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    41/88

    class StringBufferDemo {public static void main(String args[]) {StringBuffer sb = new StringBuffer("Jonathan");System.out.println("sb = " + sb);/* initial capacity is 16 */System.out.println("capacity of sb: " + sb.capacity());System.out.println("append \'O\' to sb: " + sb.append("O"));System.out.println("sb = " + sb);System.out.println("3rd character of sb: " + sb.charAt(2));char charArr[] = "Hi XX".toCharArray();/* Need to add 1 to the endSrc index of getChars */sb.getChars(0, 2, charArr, 3);System.out.print("getChars method: ");

    System.out.println(charArr);System.out.println("Insert \'jo\' at the 3rd cell: " + sb.insert(2, "jo"));System.out.println("Delete \'jo\' at the 3rd cell: " + sb.delete(2,4));System.out.println("length of sb: " + sb.length());System.out.println("replace: " + sb.replace(3, 9, " Ong"));/* Need to add 1 to the endIndex parameter of substring*/System.out.println("substring (1st two characters): " + sb.substring(0, 3));System.out.println("implicit toString(): " + sb);}}

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    42/88

    sb = Jonathancapacity of sb: 24append 'O' to sb: JonathanOsb = JonathanO3rd character of sb: ngetChars method: Hi JoInsert 'jo' at the 3rd cell: JojonathanODelete 'jo' at the 3rd cell: JonathanOlength of sb: 9replace: Jon Ongsubstring (1st two characters): Jonimplicit toString(): Jon Ong

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    43/88

    Curve Plotting 38 2 x yimport java.io.*;public class Sample1 {

    public static void main(String[] args) throws IOException{int x,y;//71 spacesStringBuffer line = new StringBuffer ("| ");for (x=1;x

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    44/88

    | *| *| *| *

    | *| *| *| *| *| *

    | *| *| *| *| *

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    45/88

    object representations of simple non-objectvariables

    Can use to declare reference data typeCan access methods of the Object Classunlike the primitive data types

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    46/88

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    47/88

    class Test {static void Swap(Integer j, Integer k) {

    int tmp = k.intValue();k = new Integer(j.intValue()); j = new Integer(tmp);

    }

    public static void main(String[] args) {Integer n = new Integer(5), m = new Integer(6);Swap(n, m);System.out.println("n = " + n + "; m = " + m);

    }}

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    48/88

    Character class offers a number of usefulclass (i.e., static) methods for manipulating

    characters. You can create a Character objectwith the Character constructor:

    Character ch = new Character('a');

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    49/88

    public static boolean isDigit(char ch)Returns true if ch is a digit; otherwise, it returns a false

    public static boolean isLetter(char ch)Returns true if ch is a letter; otherwise, it returns a false

    public static boolean isLowerCase(char ch)Returns true if ch is a lowercase letter; otherwise, it returns a false

    public static boolean isUpperCase(char ch)Returns true if ch is a uppercase letter; otherwise, it returns a false

    public static boolean isSpaceChar(char ch)Returns true if ch is a space character; otherwise, it returns a false

    public static boolean isWhiteSpace(char ch)Returns true if ch is a Java-defined whitespace; otherwise, it returns a false

    public static char toLowerCase(char ch)Returns the lowercase equivalent of chpublic static char toUpperCase(char ch)Returns the uppercase equivalent of ch

    public static char toString(char ch)Returns the String representation of ch

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    50/88

    Character c1 = new Character ('A');Character c2 = new Character ('B');Character c3 = new Character ('A');System.out.println ("c1.compareTo (c2): " + c1.compareTo (c2));System.out.println ("c1.equals (c2): " + c1.equals (c2));System.out.println ("c1.equals (c3): " + c1.equals (c3));System.out.println (Character.isDigit ('4')); // Output: trueSystem.out.println (Character.isLetter (';')); // Output: falseSystem.out.println (Character.isUpperCase ('X')); // Output: trueSystem.out.println (Character.toLowerCase ('B')); // Output: bSystem.out.println (Character.toUpperCase ('a')); // Output: A

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    51/88

    class BooleanWrapper {public static void main(String args[]) {boolean booleanVar = 1>2;Boolean booleanObj = new Boolean("TRue");/* primitive to object; can also use valueOf method */

    Boolean booleanObj2 = new Boolean(booleanVar);System.out.println("booleanVar = " + booleanVar);System.out.println("booleanObj = " + booleanObj);System.out.println("booleanObj2 = " + booleanObj2);System.out.println("compare 2 wrapper objects: " +booleanObj.equals(booleanObj2));/* object to primitive */booleanVar = booleanObj.booleanValue();System.out.println("booleanVar = " + booleanVar);}}

    Sample OutputbooleanVar = falsebooleanObj = truebooleanObj2 = falsecompare 2 wrapper objects: falsebooleanVar = true

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    52/88

    Process Classprovides methods for manipulating processessuch as killing the process, running the processand checking the status of the process.This class represents running programs

    Runtime Classrepresents the runtime environment.Two important methods in the class are the getRuntime and the exec method

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    53/88

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    54/88

    class RuntimeDemo {public static void main(String args[]) {Runtime rt = Runtime.getRuntime();Process proc;try {

    proc = rt.exec("regedit");proc.waitFor(); //try removing this line} catch (Exception e) {System.out.println("regedit is an unknown command.");}}

    }

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    55/88

    provides many useful fields and methodssuch as the standard input, the standard

    output and a utility method for fast copyingof a part of an array. Here are someinteresting methods from the class. Note thatall the class's methods are static.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    56/88

    public static void arraycopy(Object src, int srcPos, Object dest, int destPos, intlength)

    Copies length items from the source array src starting at srcPos to dest starting at index destPos.Faster than manually programming the code for this yourself.

    public static long currentTimeMillis()Returns the difference between the current time and January 1, 1970 UTC. Time returned is

    measured in milliseconds.public static void exit(int status)Kills the Java Virtual Machine (JVM) running currently. A non-zero value for status byconvention indicates an abnormal exit.

    public static void gc()Runs the garbage collector, which reclaims unused memory space for recycling.

    public static void setIn(InputStream in)Changes the stream associated with System.in, which by default refers to the keyboard.

    public static void setOut(PrintStream out)Changes the stream associated with System.out, which by default refers to the console.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    57/88

    import java.io.*;class SystemDemo {public static void main(String args[]) throws IOException {int arr1[] = new int[5000000];int arr2[] = new int[5000000];long startTime, endTime;/* initialize arr1 */for (int i = 0; i < arr1.length; i++) {arr1[i] = i + 1;}/* copying manually */startTime = System.currentTimeMillis();for (int i = 0; i < arr1.length; i++) {arr2[i] = arr1[i];}endTime = System.currentTimeMillis();System.out.println("Time for manual copy: " +(endTime-startTime) + " ms.");/* using the copy utility provided by java thearraycopy method */startTime = System.currentTimeMillis();System.arraycopy(arr1, 0, arr2, 0, arr1.length);endTime = System.currentTimeMillis();System.out.println("Time w/the use of arraycopy: " + (endTime-startTime) + " ms.");System.gc(); //force garbage collector to workSystem.setIn(new FileInputStream("temp.txt"));/* in NetBeans, temp.txt should be locate in the project folder */System.exit(0);}

    }

    Sample Output

    Time for manual copy: 32 ms.Time w/the use of arraycopy: 31 ms.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    58/88

    The format Method

    The format method formats multiple arguments based on a formatstring. The format string consists of static text embedded with format

    specifiers; except for the format specifiers, the format string is outputunchanged. All format specifiers begin with a % and end with a 1- or 2-character conversion that specifies the kind of formatted output beinggenerated.

    Conversion formats:d - formats an integer value as a decimal value.f - formats a floating point value as a decimal value.n - outputs a platform-specific line terminator.x - formats an integer as a hexadecimal value.s - formats any value as a string.tB - formats an integer as a locale-specific month name.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    59/88

    Code Segment:int i = 2;double r = Math.sqrt(i);System.out.println("The square root of "+ i + " is "+ r);

    System.out.format("The square root of %d is %.2f", i, r);

    Output:

    The square root of 2 is 1.4142135623730951The square root of 2 is 1.41

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    60/88

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    61/88

    Using Predefined FormatsNumberFormat Class-

    an abstract base class for all number formatsprovides method to format numbers, currencies, and percentages according to Locale.

    To format a number for the current Locale, use one of the factory class methods:

    myString = NumberFormat.getInstance().format(myNumber);If you are formatting multiple numbers, it is more efficient to get the format and use it multiple times

    so that the system doesn't have to fetch the information about the local language and countryconventions multiple times.

    NumberFormat nf = NumberFormat.getInstance();for (int i = 0; i < myNumber.length; ++i){ output.println(nf.format(myNumber[i]) + "; "); }

    To format a number for a different Locale, specify it in the call to getInstance.

    NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);

    You can also use a NumberFormat to parse numbers:

    myNumber = nf.parse(myString);

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    62/88

    Currencies

    If you are writing business applications, you will probably need to format and displaycurrencies. You format currencies in the same manner as numbers, except that youcall getCurrencyInstance to create a formatter. When you invoke the format method, itreturns a String that includes the formatted number and the appropriate currency sign.

    Double currencyAmount = new Double(9876543.21);Currency currentCurrency = Currency.getInstance(currentLocale);NumberFormat currencyFormatter =NumberFormat.getCurrencyInstance(currentLocale);

    System.out.println(currentLocale.getDisplayName()+ ", " + currentCurrency.getDisplayName()+ ": " + currencyFormatter.format(currencyAmount));

    Use getInstance or getNumberInstance to get the normal number format.Use getIntegerInstance to get an integer number format. Use getCurrencyInstance to getthe currency number format. And use getPercentInstance to get a format for displayingpercentages.

    http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.htmlhttp://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.htmlhttp://docs.oracle.com/javase/7/docs/api/java/lang/String.htmlhttp://docs.oracle.com/javase/7/docs/api/java/lang/String.htmlhttp://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.htmlhttp://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    63/88

    Integer quantity = new Integer(123456);Double amount = new Double(345987.246);NumberFormat numberFormatter;String quantityOut;String amountOut;

    numberFormatter = NumberFormat.getNumberInstance(currentLocale);quantityOut = numberFormatter.format(quantity);amountOut = numberFormatter.format(amount);System.out.println(quantityOut + " " + currentLocale.toString());System.out.println(amountOut + " " + currentLocale.toString());

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    64/88

    DecimalFormat Classa concrete subclass of NumberFormat that formats decimal numbers.It has a variety of features designed to make it possible to parse andformat numbers in any locale, including support for Western, Arabic,and Indic digits. It also supports different kinds of numbers, including

    integers (123), fixed-point numbers (123.4), scientific notation(1.23E4), percentages (12%), and currency amounts ($123). All of thesecan be localized.

    Constructing PatternsYou specify the formatting properties of DecimalFormat with a

    pattern String.

    DecimalFormat myFormatter = new DecimalFormat(pattern);String output = myFormatter.format(value);System.out.println(value + " " + pattern + " " + output);

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    65/88

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    66/88

    import java.text.DecimalFormat;

    public class DecimalFormatExample {

    public static void main(String args[]) {

    //formatting numbers upto 2 decimal places in Java DecimalFormat df = new DecimalFormat("#,###,##0.00");System.out.println(df.format(364565.14));System.out.println(df.format(364565.1454));

    //formatting numbers upto 3 decimal places in Java df = new DecimalFormat("#,###,##0.000");System.out.println(df.format(364565.14));System.out.println(df.format(364565.1454));

    }

    }

    Output:364,565.14364,565.15364,565.140364,565.145

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    67/88

    Date ClassA wrapper for a date.This class lets you manipulate dates in a system independentway.

    To print today's date use:

    Date d = new Date();System.out.println("today = " + d);

    To find out what day corresponds to a particular date:

    Date d = new Date(63, 0, 16); // January 16, 1963System.out.println("Day of the week: " + d.getDay());

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    68/88

    Date ()Creates today's date/time.

    Date (long date)Date (int year, int month, int date)Date (int year, int month, int date, int hour, int minutes )Date (int year, int month, int date, int hour, int minutes, int seconds )

    Date (String date)Creates a date from a string according to the syntaxaccepted by parse().

    http://www.geom.uiuc.edu/~daeron/docs/apidocs/java.util.Date.htmlhttp://www.geom.uiuc.edu/~daeron/docs/apidocs/java.util.Date.htmlhttp://www.geom.uiuc.edu/~daeron/docs/apidocs/java.util.Date.htmlhttp://www.geom.uiuc.edu/~daeron/docs/apidocs/java.util.Date.htmlhttp://www.geom.uiuc.edu/~daeron/docs/apidocs/java.util.Date.htmlhttp://www.geom.uiuc.edu/~daeron/docs/apidocs/java.util.Date.htmlhttp://www.geom.uiuc.edu/~daeron/docs/apidocs/java.util.Date.htmlhttp://www.geom.uiuc.edu/~daeron/docs/apidocs/java.util.Date.htmlhttp://www.geom.uiuc.edu/~daeron/docs/apidocs/java.util.Date.htmlhttp://www.geom.uiuc.edu/~daeron/docs/apidocs/java.util.Date.htmlhttp://www.geom.uiuc.edu/~daeron/docs/apidocs/java.util.Date.htmlhttp://www.geom.uiuc.edu/~daeron/docs/apidocs/java.util.Date.html
  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    69/88

    UTC(int, int, int, int, int, int) Calculates aUTC value from YMDHMS. after(Date) Checks whether this datecomes after the specified date. before(Date) Checks whether this datecomes before the specified date. equals(Object) Compares this objectagainst the specified object. getDate() Returns the day of the month. getDay() Returns the day of the week. getHours() Returns the hour. getMinutes() Returns the minute.

    getMonth() Returns the month. getSeconds() Returns the second. getTime() Returns the time inmilliseconds since the epoch. getTimezoneOffset() Return the timezone offset in minutes for the current

    locale that is appropriate for this time. getYear() Returns the year after 1900.parse(String) Given a string representing atime, parse it and return the time value. setDate(int) Sets the date. setDay(int) Sets the day of the week. setHours(int) Sets the hours. setMinutes(int) Sets the minutes. setMonth(int) Sets the month. setSeconds(int) Sets the seconds. setTime(long) Sets the time. setYear(int) Sets the year.

    toString() Converts a date to a String,using the UNIX ctime conventions.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    70/88

    DateFormat an abstract class for date/time formatting subclasseswhich formats and parses dates or time in a language-independent manner.provides many class methods for obtaining defaultdate/time formatters based on the default or a givenloacle and a number of formatting styles. Theformatting styles include FULL, LONG, MEDIUM, andSHORT.To format a date for the current Locale, use one of thestatic factory methods:

    myString = DateFormat.getDateInstance().format(myDate);

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    71/88

    Use getDateInstance to get the normal date format forthat country. There are other static factory methodsavailable. Use getTimeInstance to get the time format forthat country. Use getDateTimeInstance to get a date and

    time format. You can pass in different options to thesefactory methods to control the length of the result; fromSHORT to MEDIUM to LONG to FULL. The exact resultdepends on the locale, but generally:

    SHORT is completely numeric, such as 12.13.52 or 3:30pmMEDIUM is longer, such as Jan 12, 1952LONG is longer, such as January 12, 1952 or 3:30:32pmFULL is pretty completely specified, such as Tuesday, April12, 1952 AD or 3:30:42pm PST.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    72/88

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    73/88

    SimpleDateFormata concrete class for formatting and parsing datesin a locale-sensitive manner. It allows forformatting (date -> text), parsing (text -> date),and normalization.allows you to start by choosing any user-defined

    patterns for date-time formatting

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    74/88

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    75/88

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    76/88

    public class SimpleDateFormatExample {

    public static void main(String[] args) {

    Date now = new Date();String datetimeStr = now.toString();System.out.println("1. " + datetimeStr);SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");System.out.println("2. " + format.format(now));}

    }

    The output is 1. Fri Jun 27 21:28:16 EDT 20082. Fri Jun 27 21:28:16 EDT 2008

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    77/88

    import java.text.SimpleDateFormat;import java.util.Date;public class DateFormatExample {

    public static void main(String args[]) {

    Date today = new Date (); // This is how to get today's date in Java System .out.println("Today is : " + today); //If you print Date, you will get un formatted output

    //formatting date in Java using SimpleDateFormat

    SimpleDateFormat DATE_FORMAT =new SimpleDateFormat ("dd-MM-yyyy");String date = DATE_FORMAT.format(today);System .out.println("Today in dd-MM-yyyy format : " + date);

    //Another Example of formatting Date in Java using SimpleDateFormat DATE_FORMAT =new SimpleDateFormat ("dd/MM/yy");date = DATE_FORMAT.format(today);System .out.println("Today in dd/MM/yy pattern : " + date);

    //formatting Date with time information

    DATE_FORMAT =new SimpleDateFormat ("dd-MM-yy:HH:mm:SS");date = DATE_FORMAT.format(today);System .out.println("Today in dd-MM-yy:HH:mm:SS : " + date);

    //SimpleDateFormat example - Date with timezone information DATE_FORMAT =new SimpleDateFormat ("dd-MM-yy:HH:mm:SS Z");date = DATE_FORMAT.format(today);System .out.println("Today in dd-MM-yy:HH:mm:SSZ : " + date);} }

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    78/88

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    79/88

    The most important method in Calendar is get(int calendarField), which producesan int. The calendarField are defined as static constant and includes:

    get(Calendar.DAY_OF_WEEK): returns 1 (Calendar.SUNDAY) to 7 (Calendar.SATURDAY).get(Calendar.YEAR): yearget(Calendar.MONTH): returns 0 (Calendar.JANUARY) to 11 (Calendar.DECEMBER).

    get(Calendar.DAY_OF_MONTH), get(Calendar.DATE): 1 to 31get(Calendar.HOUR_OF_DAY): 0 to 23get(Calendar.MINUTE): 0 to 59get(Calendar.SECOND): 0 to 59get(Calendar.MILLISECOND): 0 to 999get(Calendar.HOUR): 0 to 11, to be used together with Calendar.AM_PM.get(Calendar.AM_PM): returns 0 (Calendar.AM) or 1 (Calendar.PM).

    get(Calendar.DAY_OF_WEEK_IN_MONTH): DAY_OF_MONTH 1 through 7 alwayscorrespond to DAY_OF_WEEK_IN_MONTH 1; 8 through 14 correspondto DAY_OF_WEEK_IN_MONTH 2, and so on.get(Calendar.DAY_OF_YEAR): 1 to 366get(Calendar.ZONE_OFFSET): GMT offset value of the time zone.get(Calendar.ERA): Indicate AD (GregorianCalendar.AD), BC (GregorianCalendar.BC).

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    80/88

    Calendar has these setters and operations:void set(int calendarField, int value)void set(int year, int month, int date)void set(int year, int month, int date, int hour, int minute, int second)void add(int field, int amount): Adds or subtracts the specified amount of time

    to the given calendar field, based on the calendar's rules.void roll(int calendarField, boolean up): Adds or subtracts (up/down) a singleunit of time on the given time field without changing larger fields.void roll(int calendarField, int amount): Adds the specified (signed) amount tothe specified calendar field without changing larger fields.

    Other frequently-used methods are:Date getTime(): return a Date object based on this Calendar's value.void setTime(Date date)long getTimeInMills(): Returns this Calendar's time value in milliseconds.void setTimeInMillis(long millis)void setTimeZone(TimeZone value)

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    81/88

    import java.util.Calendar; public class GetYMDHMS {

    public static void main(String[] args) { Calendar cal = Calendar.getInstance(); // You cannot use Date class to extract individual Date fields

    int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); // 0 to 11 int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND);

    System.out.printf("Now is %4d/%02d/%02d %02d:%02d:%02d\n", // Pad withzero

    year, month+1, day, hour, minute, second); }

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    82/88

    The calendar that we use today, called Gregorian calendar , cameinto effect in October 15, 1582 in some countries and later in othercountries. It replaces the Julian calendar . 10 days were removedfrom the calendar, i.e., October 4, 1582 (Julian) was followed byOctober 15, 1582 (Gregorian).

    The only difference between the Gregorian and the Julian calendaris the "leap-year rule".In Julian calendar, every four years is a leap year. In Gregoriancalendar, a leap year is a year that is divisible by 4 but not divisibleby 100, or it is divisible by 400, i.e., the Gregorian calendar omitscentury years which are not divisible by 400 (removing 3 leap years(or 3 days) for every 400 years).Furthermore, Julian calendar considers the first day of the year asmarch 25th, instead of January 1st.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    83/88

    java.util.Calendar is an abstract class.Calendar.getInstance() returns an implementationclass java.util.GregorianCalendar (except locales of "th" and "jp"). In Java, thisGregorianCalendar handles both the Gregorian calendar as well asthe Julian calendar, including the cut over.

    GregorianCalendar has the following constructors:GregorianCalendar(): using the current time, with the default time zone and locale.GregorianCalendar(int year, int month, int dayOfMonth): with the default time zone andlocale.GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, intsecond)GregorianCalendar(TimeZone zone, Locale aLocale): using current time.GregorianCalendar(TimeZone zone)GregorianCalendar(Locale aLocale)

    For example,Calendar cal1 = new GregorianCalendar(); // allocate an instance and upcast to CalendarCalendar cal2 = new GregorianCalendar(2010, 9, 26); // allocate with the specified datecal2.get(Calendar.DAY_OF_WEEK);

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    84/88

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    85/88

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    86/88

    Numeric and String Methods

    int nextInt()Returns the next token as an int. If the next token is not an integer,InputMismatchException is thrown.

    long nextLong()Returns the next token as a long. If the next token is not an integer,InputMismatchException is thrown.

    float nextFloat()Returns the next token as a float. If the next token is not a float or is out ofrange, InputMismatchException is thrown.

    double nextDouble()Returns the next token as a long. If the next token is not a float or is out of range, InputMismatchException isthrown.

    String next()Finds and returns the next complete token from this scanner and returns it as a string; a token is usually

    ended by whitespace such as a blank or line break. If not token exists,NoSuchElementException is thrown.String nextLine()Returns the rest of the current line, excluding any line separator at the end.

    void close()Closes the scanner.

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    87/88

    For example, given the following codesegment and data

    int number = in.nextInt();float real = in.nextFloat();long number2 = in.nextLong();double real2 = in.nextDouble();String string = in.next();

  • 8/10/2019 Comp 034 Advanced Programming Language - Prelim

    88/88

    import java.util.Scanner;import java.io.*; // Access System.out public class NumericInput{public static void main(String[] args){// Declarations Scanner in = new Scanner(System.in);int integer; long longInteger;float realNumber; double doubleReal;String string1; String string2;

    // Prompts System.out.println( "Enter an integer, a long integer, + "a floating-point " );System.out.println( "number, another floating- point number, + "and a string." );System.out.println( "Separate each with a blank or return." );

    // Read in values integer = in.nextInt();

    longInteger = in.nextLong();realNumber = in.nextFloat();doubleReal = in.nextDouble();string1 = in.nextLine();System.out.println( "Now enter another value." );string2 = in.next();

    l ( h d )