-
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
-
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
-
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
}
-
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.
-
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";
-
final
final meaning once it's been set, it can't be changed.
-
null
dereference variables using the keyword null, all lower case. No matter what the scope
-
stack vs heap
- stack faster
- heap more dynamic
- complex objects are stored on heap
-
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
-
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"
-
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
-
connection to db
- import java.sql.Connection;
- import java.sql.DriverManager;
- Connection connection;
- connection = DriverManager.getConnection(
- "jdbd:mysql://localhost:3306/dbname"
- ,"root","mysql");
-
Statement
import java.sql.Statement;
Statement stmt = connection.createStatement();
-
create a result set
- import java.sql.ResultSet;
- ResultSet rs
- = statement.executeQuery(
- "SELECT * FROM person");
- while (rs.next())
- {
- int personId = rs.getInt("personid");
- ...
-
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);
- }
-
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);
- }
-
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);
- }
-
create file tripinfo.html in folder html
import java.io.File;
File file = new File("srchtmltripinfo.html");
-
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();
-
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;
- }
-
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;
- }
- ...
- }
-
Person class has properties personid(int) and name(String).
Write toString method
- @Override
- public String toString()
- {
- return personid + ", " + name;
- }
-
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));
-
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);
- }
-
Person person=tripObj.getPersonRef();
first = ?
last = ?
- String last = person.getName().split(",")[0];
- String first = person.getName().split(",")[1].trim();
-
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);
- }
-
basic structure of try-catch block
- try { }
- catch (Exception e) { }
-
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());
-
Create a string from an array of characters.
- char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
- String helloString = new String(helloArray);
- System.out.println(helloString);
-
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);
-
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);
-
Converting Numbers to Strings
- int i = 5;
- String s2 = String.valueOf(i);
- double d = 858.48;
- String s = Double.toString(d);
-
Converting Strings to Numbers
- float a = Float.parseFloat(args[0]);
- float b = Float.parseFloat(args[1]);
-
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));
|
|