Download Java Input/Output

Document related concepts
no text concepts found
Transcript
Faculty of Food Technology and Biotechnology
Zagreb
Section for Bioinformatics
Programming in bioinformatics
Lecture 1 - Introduction
Literature
Important WEB sites
• Main lecture site
merlin.srce.hr
• Good web tutorials
http://www3.ntu.edu.sg/home/ehchua/programmin
g/index.html
• Oracle Java tutorial
http://www.oracle.com/technetwork/java/index.html
• Eclipse free java IDE
http://eclipse.org
Linux OS
• Open and free
• Popular in academia (bioinformatics)
• Many bioinformatics tools designed for Linux
www.usinglinux.org/biology/
• GPL licence
• Many distributions
• Advantages: secure, configurable, free, various
distributions
Working in the console
• Commands - applications without a graphical interface
• Windows OS does not distinguish between uppercase
•
and lowercase letters
command [/attribute][parameter]
• Commands in the path,% PATH% variable
1. command param1 param2 param3
2. dir /ON
View the contents of the
directory sorted by name
3. help dir
Displaying help of dir command
4. c:\path\perl_program.pl
5. command1 | command2
Result of command 1 as input
command2
Basic commands
• . current directory
• .. parrent directory
• cd path enters into another directory
• partition: (c: or d:) changing the partition
• help command description of the command
• dir display the contents of the directory
Example: dir command
>
Sends out a command to a file or
printer
>> Sends out a command to the end of
existing files, without having to delete the
contents of the existing data
< Takes the input file content
| Redirects the output of one program to the
input of another program
Few console commands
1. help dir show help of dir command
2. cd C:\ move to c:\ directory
3. cd .. move to parrent directory
4. d: change partition
5. help dir | more
6. notepad open notepad program
7. notepad file.txt open file
8. type file.txt show file
9. echo "foobar" print string to console
10. echo "foobar" > file.txt in file
11. echo "foobar" >> file.txt at the end of
file.
• Query as whole sentence
• ″query phrase″ Phrase search - exact
•
•
•
words in that exact order without any change
-query Terms you want to exclude
+query Terms you want to include
site:biojava.org query Search
within a specific website
What is Programming?
• Sequence of commands to a computer to
achieve an objective
• Specific syntax
• Memory , disk , processor
• Writing source code
• Compiling to a native machine code
• Execute machine code
• Variables - save data in memory
• Loops (for, while) - execution of a group of
commands a certain number of times
• Conditionals (if-else) - decide the control
flow of the program
• Input/Output - read/write data from disk or
network
• Classes and methods - organize blocks of code
into methods, and methods to classes
• Classes - represent new own data type
Java
• Very popular programming language
• Java Virtual Machine (JVM) - runs java
programs
• Compiling MyClass.java source code to
MyClass.class bytecode
• JVM runtime translates bytecode to machine
code
• API - java libraries - useful java code
JRE - Java Runtime Environment
• Contains two tools:
- Application Programming Interface API
- Java virtual machine JVM
• With the JRE, you can run existing Java
programs. That's all. You can't create new Java
programs, because you don't have a Java
compiler.
• Exists for many OS (Win., *nix, miscellaneous
mobile OS (java games) )
JDK - Java Development Kit
• Or Java SDK - Java Software Development Kit
• Contain three tools:
- Java compiler
- Java virtual machine
- Application Programming Interface API.
• With the JDK, you can create and run your
own Java programs
Development process
• All source code is first written in plain text files
ending with the .java
• Those source files are then compiled into
.class files by the javac compiler
• A .class file does not contain code that is
native to your processor; it instead contains
bytecodes — the machine language of the
Java Virtual Machine
• IDE - integrated development environment
• Can be used to develop applications in Java
and other languages
• Source code are organized to projects
• Compile and run your new java program
• Eclipse: coloring, formatting, display errors,
compiling, running source code
• Automatically compile java sources
Instalation Elipse and Java
• Download Eclipse + JDK from:
http://proteinreader.bioinfo.pbf.hr/dow/PUBeclipse.zip
• Extract eclipse.zip to C:\Users\[name]\pub on
hard drive
• Run eclipse.exe
Write your first java program
Create new Java project:
File -> New -> Java Project
Create new Java class: File -> New -> Class
Enter Class and Package name
• Open your new class file: MyFirstClass.java
from Package Explorer
Java Hello World Program
class HelloWorld {
public static void main (String args[]) {
System.out.println("Hello World!");
}
}
Program
results
Hello World!
Ignore all outside comments for now
class HelloWorld {
public static void main (String args[]) {
//--------- START HERE --------------------System.out.println("Hello World!");
//--------- END HERE ----------------------}
}
Lecture 2 - Syntax of Java programs
The Simplest Java Program
class HelloWorld {
public static void main (String args[]) {
System.out.println("Hello World!");
}
}
Program
results
Hello World!
The Structure of an Application
• For an application, the first method to run is
the method named main.
Keywords
• Each Java keyword has a specific meaning
• A keyword is a word that has its own special
•
meaning in the Java programming language,
and that meaning doesn't change from one
program to another
class, public, static, int, boolean
 (32 keywords)
Variable
• Variable is a symbolic name given to some
known or unknown quantity or value
• All variables must first be declared before they
can be used
• Default will be zero or null, depending on the
data type
Syntax of variable declaration
• Declare a variable:
dataType variableName;
• The initial value must be of the correct data
type:
•
•
dataType variableName = initialValue;
int gear; // declaration
gear = 1; // initialization
Variable recommendations
• It is important to choose a name that is selfdescriptive and closely reflects the meaning of
the variable, e.g., numberOfStudents or
numStudents.
• Do not use meaningless names like a, b, c, d, i,
j, k, i1, j99.
• Avoid single-alphabet names, which is easier
to type but often meaningless, unless they are
common names like x, y, z for coordinates, i
for index.
Example Program
public static void main(String[] args)
throws Exception {
int variable1;
variable1 = 22;
System.out.println(variable1);
String variable2 = "hello!";
System.out.println(variable2);
}
Primitive Data Types
• Each variable has own data type:
- int (32 bit) [-2^31, 2^31-1]
- double (64 bit) ±[10^-324, 10^308]
- char Treated as a 16-bit unsigned integer in the range of
[0 - 65,535]
- boolean Takes a value of either true or false
Integer types
• Integer is a whole number:
byte 8-bit signed integer
The range is [-2^7, 2^7-1] = [-128, 127]
short 16-bit signed integer
The range is [-2^15, 2^15-1] = [-32768, 32767]
int 32-bit signed integer
The range is [-2^31, 2^31-1]
long 64-bit signed integer
The range is [-2^63, 2^63-1]
Floating-point types
• Floating-point numbers are numbers that have
•
•
fractional parts (float 4-byte, double 8-byte)
double e = 5.10e+6 5.10e6 5100000D
float 32-bit single precision floating-point
±[10^-45, 10^38]
The char type
• Represents a single character
• Is enclosed by a pair of single quotes
• Is not the same as a string!
• char code = 'X';
• Special escape sequences:
\n
Linefeed, new line
\'
Single quote
\\
Backslash
The boolean type
• Can have one of two values: true or false
• Used to perform logical operations
• boolean isBig = true;
Strings
• Special types in Java
• String is actually class
• A string is a sequence of text characters A
• String literal is surrounded by a pair of
•
double quotes, e.g., "Hello, world!"
String message = "Hello world!";
String message = new String();
Combining strings
• Combine two strings by using the plus sign (+)
as a concatenation operator
String hello = "Hello, ";
String world = "World!";
String greeting = hello + world;
String greeting = "Hello, " + "World!";
Useful page
http://www3.ntu.edu.sg/home/ehchua/progr
amming/java/J2_Basics.html
Print string to console
• Use System.out.println
• Convert primitives to strings:
int i = 23;
System.out.println("The value of i is "+i)
• Java automatically converts primitive values to
string
Comments
• The Java language supports three kinds of
•
comments:
/* text */ The compiler ignores
everything from /* to */
•
/** documentation */ This indicates a
•
documentation comment.
// text The compiler ignores everything
from // to the end of the line.
Operators
Java Operators
• % remainder operator (also known as the
modulus)
• The % operator returns the remainder of two
numbers. For instance 10 % 3 is 1 because 10
divided by 3 leaves a remainder of 1.
Increment/decrement Operator
• The increment operator ++ adds one to a
variable (decrement operator --)
• Usually the variable is an integer type, but it
can be a floating point type.
• The two plus signs must not be separated by
any character. (e.g., space)
• Usually they are written immediately adjacent
to the variable (e.g. i++)
Expression
An expression is a combination of literals,
operators, variables, and parentheses used to
calculate a value.
E.g. 49 - x/y
• literal: characters that denote a value, like: 3.456
• operator: a symbol like plus ("+") or times ("*") •
•
variable: a section of memory containing a value
parentheses: "(" and ")"
Understanding Scope (Braces)
• Block is marked by a matching pair of braces
Arrays
• An array is a container object that holds a
fixed number of values of a single type.
Java tutorial Arrays
Array of strings:
String[] names = {"name1", "name2", "name3"};
same as:
String[] names = new String[3];
names[0] = "name1";
names[1] = "name2";
names[2] = "name3";
Standard input and output streams
• All input and output is done by using methods
found in classes within the JDK.
• System.in
Standard input
• System.out Standard output
• System.err Standard error
• The java.io package is the package used for
I/O.
• A package is a collection of classes which may
be used by other programs.
• In Java, a source of input data is called an
input stream and the output data is called an
output stream
• Input data is usually called reading data; and
output data is usually called writing data
public static void main(String args[]) {
Scanner myScanner = new Scanner(System.in);
System.out.println(myScanner.nextLine());
}
Exceptions
• An exception is an object that contains
information about the location and type of
error.
• An exception is an event that occurs during
the execution of a program that disrupts the
normal flow of instructions.
• E.g.
int sum = 4 / 0;
// throw ArithmeticException
// catch
example
try
{
int i = 4 /
0;
} catch(Exception
e) {
System.err.println("Error:
"+ e);
}
// throw
example
int i =
0;
if(i ==
0) {
throw new Exception("Error, i ==
0");
}
Lecture 3 - Control Flow Statements
Control Flow Statements
• Java tutorial Control Flow Statements
www3.ntu.edu.sg/home/ehchua/programming/jav
a/J1a_Introduction.html
if-then
if-then-else
switch
while
do-while
for
if-then statement
• It tells your program to execute a certain
section of code only if a particular test
evaluates to true
• The opening and closing braces are optional,
provided that the "then" clause contains only
one statement
if-then example
// if-then syntax
if ( condition ) {
true-body ;
}
if (mark >= 50) {
System.out.println("Congratulation!");
}
if-then-else statement
• Provides a secondary path of execution when
an "if" clause evaluates to false
if (condition) {
body-code
} else {
else-code
}
if-then-else example
if ( condition ) {
true-body ;
} else {
false-body ;
}
if (mark >= 50) {
System.out.println("Congratulation!");
} else {
System.out.println("Try Harder!");
}
• The if-else class of statements should have the
following form:
if (condition) {
statements;
} else {
statements;
}
if (condition) {
statements_1;
} else if (condition) {
statements_2;
} else {
statements_3;
}
Logical Operators
• A logical operator combines true and false
values into a single true or false value.
• Three types of logical operators:
- AND (&&)
- OR (||)
- NOT (!)
if(x > 5)
if(x >= 5)
// x =[6,7,8 ]
// x =[5,6,7,8 ]
if(x >= 2 && x =< 4)
// x=[2,3,4]
if( (x == 3) || (x == 7) )
// x=[3,7]
if(x == 3 || x == 4 || x == 5) // x[3,4,5]
if(x != 3 && x != 4)
// x=[-2,4]
if((x == 5) && (x == 6))//x =[] Always FALSE
To evaluate X && Y, first evaluate X. If X is false
then stop: the whole expression is false.
switch statement
• allows for any number of possible execution paths
• A switch works with the byte, short, char, and int primitive
data types
int num = 8;
switch (num) {
case 1: System.out.println("1"); break;
case 2: System.out.println("2"); break;
case 3: System.out.println("3"); break;
case 4: System.out.println("4"); break;
case 5: System.out.println("5"); break;

default: System.out.println("Invalid number: "+ num);
break;
}
while statement
• continually executes a block of statements while
a particular condition is true
while (expression) {
statements ;
}
• The while statement evaluates expression, which must
return a boolean value. If the expression evaluates to
true, the while statement executes the statement(s) in
the while block. The while statement continues testing
the expression and executing its block until the
expression evaluates to false.
• You can implement an infinite loop using the
while statement as follows:
while (true){
// your code goes here
}
do-while statement
• The difference between do-while and while
is that do-while evaluates its expression at
the bottom of the loop instead of the top.
Therefore, the statements within the do block
are always executed at least once.
do {
statements ;
} while (expression);
for Statements
• Provides a compact way to iterate over a
range of values
• Programmers often refer to it as the "for loop"
because of the way in which it repeatedly
loops until a particular condition is satisfied
for(int i=1; i<11; i++){
System.out.println("Count is: "+ i);
}
for scheme
for(initialization ; test ; post-processing){
body ;
}
for example
// Example
int sum = 0;
for (int number = 1; number <= 1000; number++) {
sum = sum + number;
}
for (initialization; termination; increment)
{
statement;
}
• When using this version of the for
statement,
keep in mind that: The initialization
expression
initializes the loop; it's executed once, as the
loop begins.
• When the termination expression evaluates
to
false, the loop terminates
• The increment expression is invoked after
each
iteration through the loop; it is perfectly
acceptable for this expression to increment
or
decrement a value
Lecture 4 - Classes and Objects
What is a method?
Java tutorial Defining Methods
Object
• All data in Java falls into one of two categories:
primitive data and objects. There are only
eight primitive data types. Any data type you
create will be an object.
• An object is a structured block of data. An
object may use many bytes of memory
• An object can contain methods and data
(field)
• Many classes are already defined as API
• An object is a self-contained entity which has
its own private collection of properties (ie.
data) and methods (ie. operations) that
encapsulate functionality into a reusable and
dynamically loaded structure.
Class
• A group of objects with similar properties and
behaviors is described by a class
• A class contains fields and methods that define
the behavior of the object
• A class is a description of a kind of object.
• A programmer may define a class using Java,
or may use predefined classes that come in
class libraries such as the JDK (API).
• When a programmer wants to create an
object the new operator is used with the
name of the class
• Creating an object is called instantiation
• When it is executed (as the program is
running), the line
File someFile = new File("c:/myfile.txt");
creates an object by following the file path in
class File. The class File is defined in the
package java.io that comes with the Java
system.

public static void main(String[] args){
Student stud1 = new Student();
stud1.age = 2;
Student stud2 = new Student();
stud2.age = 3;
}

class Student {
int age ;
}
Objected-oriented Programming
• Many programs are written to model
problems of the real world.
• It is convenient to have "software objects"
that are similar to "real world objects." This
makes the program and its computation
easier to think about.
• Object-oriented programming solve a
problem by creating objects that solve the
problem.
Packages
A package is a grouping of related types
providing access protection and name space
management.
Note that types refers to classes,
interfaces, enumerations, and
annotation types.
Enumerations and
annotation types are special kinds of classes
and interfaces.
Include your jars in program
Java Tutorial Classes and Objects
http://docs.oracle.com/javase/tutorial/java/javaOO/index.html
Data Structures Collection & Iterator
• http://www3.ntu.edu.sg/home/ehchua/progr
amming/java/J5c_Collection.html
Java Input/Output
http://www3.ntu.edu.sg/home/ehchua/programming/java/J5b_IO.html
Cool library
BioJava biojava.org
Commons Lang commons.apache.org/lang/
Commons IO commons.apache.org/io/
input/output