Introduc{On to Java, Etc
Total Page:16
File Type:pdf, Size:1020Kb
Introduc)on to Java, etc. August 2012 Connec)ng to the class server • Class server : bio5495-work.wustl.edu • Username = first ini)al last name for eg : aeinstein • Password = <username>123 for eg : aeinstein123 • Mac Users : Applicaons àUli)es à Terminal ssh [email protected] • Windows Users : ssh client like PuTTy/ WinSCP Hostname = bio5495-work.wustl.edu (Last year the class server was Warlord, incase you no)ce it in the notes, read as class server) SSH and SFTP • Login : use secure shell – ssh [email protected] • Transfer files : use secure file transfer protocol – sp [email protected] Quick Unix Overview ls list files ls -l list files (long format) ls –a list all files (hidden too) man (command) help cd change directory mkdir make directory cp source folder copy source to folder mv source folder mover source to folder rm filename remove filename rmdir folder remove empty directory rm -rf folder remove directory and all its contents Need more? Search ‘unix commands cheat sheet’ Sp commands • cd folder: change current locaon to folder on the server • lcd folder :change current locaon to folder on the local machine • ls : list files in the current folder on the server • lls : list files in the current folder on the local machine • Once you are in the correct folders on both ends : – get file : download a file (accepts wildcards like "*") – put file : upload a file (accepts wildcards like "*") Java Development Environment • IDE (Integrated Development Environment) – Eclipse • hp://www.eclipse.org/downloads/ • Download Eclipse Classic 3.7 • Tutorials available on our website – Netbeans – DrJava • Text Editor – Emacs – VIM • Get Eclipse and ssh clients • Create Helloworld.java in Eclipse public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } Run program using: • Upload Helloworld.java on your account on the server using sp/puy • Stfp [email protected] • $ lls, lcd to the local folder con)aning helloworld.java • $ put helloworld.java • Login via ssh • Compile and run the program on the Server $ javac HelloWorld.java (Java Program à Compiler à Java Bytecode) $ java HelloWorld (Java Bytecode à Java Virtual Machine à Output) Comments - Comment your code! // Single Line Comments /* Multi Line Comments */ Object Oriented Programming • Objects : States and Behavior • Classes : Blueprint for objects • Methods : Operaons class Bicycle { class BicycleDemo { public stac void main(String[] args) { int speed = 0; int gear = 1; // Create two different Bicycle objects Bicycle bike1 = new Bicycle(); void changeGear(int newValue) { Bicycle bike2 = new Bicycle(); gear = newValue; } // Invoke methods on those objects void speedUp(int increment) { bike1.speedUp(10); speed = speed + increment; bike1.changeGear(2); } bike1.printStates(); void applyBrakes(int decrement) { bike2.speedUp(15); speed = speed - decrement; bike2.changeGear(5); } bike2.printStates(); } void printStates() { } System.out.println(" speed:" + speed + " gear:" + gear); Speed : 10 Gear 2 } Speed : 15 Gear 5 } Methods Every method in java must be defined within some class. <modifiers> <return-type> <name> ( <params> ) { <statements> } // Example method: main public static void main(String[] args) { System.out.println("Hello, World!"); } Method Parameters args contains an command-line arguments Example: public class TestArgs { public static void main(String[] args) { System.out.println("First Argument: " + args[0]); System.out.println("Second Argument: " + args[1]); } } If you run this: $ java TestArgs comp bio First Argument: comp Second Argument: bio Class Example 1 - Math Math.abs(x) Math.sin(x), Math.cos(x), Math.tan(x) Math.exp(x) // number e raised to the power x Math.log(x) // logarithm of x in the base e Math.pow(x, y) // x raised to y Math.floor(x) Math.random() Class Example 2 - Sequence public class Sequence { // class variables static int maxLength = 1000; // member variables private String name; private String seq; // member methods public Sequence reverseComplement() { ... } public Sequence getSubsequence(int_sta, int_end, boolean_pos) { ... } } Constructors • Special block of code to ini)alize an object • Every class has a default constructor • Define your own constructor: // constructor public Sequence(String n, String s) { name = n; seq = s; } ... Sequence gene1 = new Sequence(“gene1", "ATCG"); Geeers and Seeers • Declare variables of classes private • Private variables can only be used by the class where it is defined public String getName() { return name; } public void setName( String newName ) { name = newName; } gene1.setName(“TP53”); Packages and Imports Java classes can be grouped together in packages. • Example: Java.util To use a package’s classes inside a Java source file, import the classes from the package with animport declaraon: • import java.util.*; – import java.util.Random; – import java.util.Scanner; – import java.util.Vector; – import java.util.Collections; – import java.util.ArrayList; – import java.util.LinkedList; – import java.util.List; • import java.io.*; – import java.io.File; Control Structures while ( <boolean expression> ) { <statements> } ... if ( <boolean expression> ) { <statements> } else { <statements> } Control Structures, cont. do { <statements> } while ( <boolean expression> ); ... for ( <initialization>; <continuation- condition>; <update> ) { <statements> } For eg : for (i = 0; i <5; i++) Arrays • An array is a data structure consis)ng of a numbered list of items, where all the items are of the same type. • Example: – int[] list = new int[5]; – list is an array of five integers Important Notes about Arrays int[] list = new int[5]; • The array “knows” how long it is (list.length) • The length of the array cannot be changed aer it has been Ini)alized • Array indexing starts with zero • Newly created arrays are automacally filled with zeros (numbers), false (boolean values), Unicode number zero (char), or null (objects) Mul)-dimensional Arrays There are no limit on the number of dimensions that an array type can have: int[][] A = new int[3][4]; for (int row = 0; row < 3; row++} { for (int column = 0; column < 4; column++) { A[row][column] = 1; } } ArrayLists An ArrayList is like a regular array, however, the size can be increased at will • java.util.ArrayList Example: – ArrayList<Sequence> seqs = new ArrayList<Sequence>(); – seqs.add(newSequence); – seqs.remove(sequence); – seqs.size(); – seqs.get(N); – seqs.set(N, sequence); – seqs.indexOf(sequence); Relaonal and Boolean Operators A == B A != B A < B A > B A <= B A >= B A || B A && B !A Strings String s1, s2; s1.equals(s2); s1.equalsIgnoreCase(s2); s1.length(); s1.charAt(N); s1.substring(N,M); s1.indexOf(s2); s1.compareTo(S2); s1.toUpperCase(); s1.trim(); Random Numbers import java.util.Random; // Uses time in milliseconds as the seed Random r = new Random(); // Uses the provided seed for testing purposes Random r = new Random(long seed); // All methods return a uniform distribution of values, // except nextGaussian(). Assume r is a Random object. int i = r.nextInt(int n) int i = r.nextInt() long l = r.nextLong() float f = r.nextFloat() double d = r.nextDouble() boolean b = r.nextBoolean() double d = r.nextGaussian() Common mistakes • Naming the Class Differently from its File Name • Comparing Strings/Objects with == • Neglec)ng Import Statements • Null pointers • Accessing non-stac member variables from stac methods • Forgeng java is zero-indexed • Type mismatch/invalid cast • Case sensi)vity • Treang Strings as In/Out parameters Underflow/Overflow - How to Deal • Problem: underflow – can occur when the true result of a floang point operaon is smaller in magnitude (that is, closer to zero) than the smallest value representable as a normal floang point number in the target datatype • Soluon: calculate in log space – very small numbers can be represented Logarithm Review y x = b à y = logbx Basic Rules of Logarithms: 1. logb(xy) = logbx + logby 2. logb(x/y) = logbx - logby n 3. logb(x ) = n*logbx 4. logbx = logax/logab • Be careful : if x = zero, try and set x to a very small value .