comp305 test1

  1. how to compile and run HelloApp
    • write file
    • public class HelloApp
    • {
    •    public static void main(String[] args)
    •    {
    •       System.out.println("Hello");
    •    }
    • }
    • save file as HelloApp.java
    •    same name as class but add .java
    • in terminal
    • $ javac HelloApp.java  //compiles code
    •    HelloApp.class file created
    • $java HelloApp  // runs app
  2. principles
    • portable
    • interpreted --> portable
    • compiles to bytecode instead of machine lang.

    • custom-compiled bytecode
    • Core runtime and additional libraries(JDK JRE)
    • JVM
    • OS

    better memory management
  3. basic package, class, main structure
    • package comp301a1;
    • imports
    • public class COMP305A1 {
    •    public static void main(String[] args) {
    •       //code
    •       try {
    •      
    •       } catch (SQLException ex) {
    •          Logger.getLogger(....
    •       } catch (IOException ex) {
    •          Logger.getLogger(....
    •       } // end try-catch
    •    } // end main

    }
  4. A console application always has:
    • a  main method.
    • It always has the three keywords, public, static, and void.
    • Public=method is available to the entire application.
    • Static=method can be called directly from the class definition rather than from an instance of the class.
    • void=method doesn't return any value.
    • also receive an array of strings as an argument or parameter.
  5. identifiers must
    • identifier conventions
    • identifiers must start with alpha char or _
    • conventions:
    • class: start with Uppercase
    • variables, methods: start with lowercase
    • constants: all Uppercase
    •    public static final String FIRST = "David";
  6. final
    final meaning once it's been set, it can't be changed.
  7. null
    dereference variables using the keyword null, all lower case. No matter what the scope
  8. stack vs heap
    • stack faster
    • heap more dynamic
    • complex objects are stored on heap
  9. static.
    That's a keyword that means that this is a member of the class that can be called from the class itself, as opposed to an instance of the class
  10. run and compile if main is in
    package com.example.java;      Main.java is in Ch3_Packages
    • Ch3_Packages$ javac ./com/example/java/Main.java
    • Ch3_Packages$ java com.example.java.Main Hello "My Friend"
  11. why packages and how
    • Java developers typically organize their classes in packages.
    • A package is a unique identifier
    • that goes at the top of the class declaration.
    • But it actually matches a folder hierarchy
  12. connection to db
    • import java.sql.Connection;
    • import java.sql.DriverManager;
    • Connection connection;
    • connection = DriverManager.getConnection(
    •      "jdbd:mysql://localhost:3306/dbname"
    •    ,"root","mysql");
  13. Statement
    import java.sql.Statement;

    Statement stmt =  connection.createStatement();
  14. create a result set
    • import java.sql.ResultSet;
    • ResultSet rs
    •     = statement.executeQuery(
    •     "SELECT * FROM person");

    • while (rs.next())
    • {
    •    int personId = rs.getInt("personid");
    • ...
  15. create an arrayList called personList of Person objects from person table in db
    • import java.util.ArrayList;
    • import model.Person;

    • ArrayList<Person> personList = new
    •     ArrayList<>();

    • ResultSet rs = statement.excuteQuery(
    •    "select * form person");
    • while(rs.next())
    • {
    •    Person personObj =new Person(
    •       rs.getInt("personid"),
    •       rs.getString("name"),
    •       rs.getString("jobtitle"));
    •    personList.add(personObj);
    • }
  16. create personMap HashMap from personList ArrayList where key is personid and value is Person object
    • import model.Person;
    • import java.util.HashMap;

    • HashMap<Integer,Person> personMap =
    •       new HashMap<>();

    • for (Person perObj : personList)
    • {
    •    personMap.put(perObj.getPersonid(),
    •                         perObj);
    • }
  17. create tripTypeMap HashMap from db where key is triptypeid and value is TripType object
    • import java.sql.ResultSet;
    • import java.util.HashMap;
    • import model.TripType;

    • HashMap<Integer, TripType> tripTypeMap
    •        = new HashMap<>();

    • rs = statement.executeQuery(
    •       "select * from triptype");
    • while (rs.next())
    • {
    •    TripType ttObj = new TripType(
    •                    rs.getTripTypeId("triptypeid"),
    •                    rs.getString("name"),
    •                    rs.getDesc("description"));
    •    tripTypeMap.put(ttObj.getTripTypeId(),
    •                         ttObj);
    • }
  18. create file tripinfo.html in folder html
    import java.io.File;

    File file = new File("srchtmltripinfo.html");
  19. write data to fileName
    • import java.io.FileWriter;
    • import java.io.BufferedWriter;

    • FileWriter fw
    •       = new FileWriter(fileName);
    • BufferedWriter bw
    •       = new BufferedWriter(fw);
    • String fileData = "some info";
    • bw.write(fileData);
    • bw.close();
  20. create beginning of Person class with properties personid, name
    Person is part of model package, include constructor
    • package model;
    • public class Person {
    •    private int personid;
    •    private String name;
    •    public Person(int personid, String name)
    •    {
    •       this.personid = personid;
    •       this.name = name;
    •    }
  21. Person class has property name as String. Write get and set for name.
    • package model;
    • public class Person
    • {
    •    ...
    •    public String getName() {return name;}

    •    public void setName(String name)
    •    {
    •       this.name = name;
    •    }
    •    ...
    • }
  22. Person class has properties personid(int) and name(String).
    Write toString method
    • @Override
    • public String toString()
    • {
    •    return personid + ", " + name;
    • }
  23. get date from ResultSet rs
    • import javal.text.SimpleDateFormat;
    • import java.util.Date;

    • Date depdate = rs.getDate("depdate");
    • SimpleDateFormat df
    •    =new SimpleDateFormat("MMM d, yyyy");
    • System.out.println(df.formate(date));
  24. try catch
    • import java.io.IOException;
    • import java.sql.SQLException;
    • import java.util.logging.Level;
    • import java.util.logging.Logger;

    • catch (SQLException ex)
    • {            Logger.getLogger(COMP305A1.class.getName()) .log(Level.SEVERE, null, ex);
    • }
    • catch (IOException ex)
    • {            Logger.getLogger(COMP305A1.class.getName())                    .log(Level.SEVERE, null, ex);       
    • }
  25. Person person=tripObj.getPersonRef();
    first = ?
    last = ?
    • String last = person.getName().split(",")[0];
    • String first = person.getName().split(",")[1].trim();
  26. split "This is a sentence." into words.
    • String sentence = "This is a sentence.";
    • String[] wordArray = sentence.split(" ");
    • for ( String word : wordArray)
    • {
    •             System.out.println(word);
    • }
  27. basic structure of try-catch block
    • try {                    }
    • catch (Exception e) {        }
  28. Two numbers are enter in one line separated by a comma. Save the first number as a double.
    • Scanner scanner = new Scanner(System.in);
    • input =scanner.nextLine();
    • Double hours = Double.parseDouble(input.split(",")[0].trim());
  29. Create a string from an array of characters.
    • char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
    • String helloString = new String(helloArray);
    • System.out.println(helloString);
  30. palindrom
    • String palindrome = "Dot saw I was Tod";
    • int len = palindrome.length();
    • char[] tempCharArray = new char[len];
    • char[] charArray = new char[len];
    • for (int i = 0; i < len; i++)
    • {
    •     tempCharArray[i] = palindrome.charAt(i);
    • }
    • for (int j = 0; j < len; j++)
    • {
    •     charArray[j] =tempCharArray[len - 1 - j];
    • }
    • String reversePalindrome
    •    = new String(charArray);
    • System.out.println(reversePalindrome);
  31. formatted string output
    • String fs;
    • fs = String.format(
    •    "The value of the float "
    •    + "variable is %f, while "
    •    + "the value of the "
    •    + "integer variable is %d, "
    •    + " and the string is %s",
    •     floatVar, intVar, stringVar);
    • System.out.println(fs);
  32. Converting Numbers to Strings
    • int i = 5;
    • String s2 = String.valueOf(i);

    • double d = 858.48;
    • String s = Double.toString(d);
  33. Converting Strings to Numbers
    • float a = Float.parseFloat(args[0]);
    • float b = Float.parseFloat(args[1]);
  34. how to output todays date:
    format Jan 1, 2017
    format 01/01/2017 09:10:12
    • import java.text.SimpleDateFormat;
    • import java.util.Date;
    • Date date = new Date();
    • SimpleDateFormat df
    •      = new SimpleDateFormat(
    •        "MMM d, yyyy");
    • System.out.println(df.format(date));

    • SimpleDateFormat df2
    •    = new SimpleDateFormat(
    •     "MM/dd/yyyy hh:mm:ss");        System.out.println(df2.format(date));
Author
slc53
ID
328376
Card Set
comp305 test1
Description
comp305 test1
Updated