Download Quick Intro to Java - UNL CSE - University of Nebraska–Lincoln

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Quick Introduction to Java
Dr. Chris Bourke
Department of Computer Science & Engineering
University of Nebraska—Lincoln
Lincoln, NE 68588, USA
Email: [email protected]
2016/12/07 22:21:58
Abstract
These are lecture notes used in CSCE 155 and CSCE 156 (Computer Science I &
II) at the University of Nebraska—Lincoln. They represent a short introduction to the
Java programming language for students who already have a strong foundation in at
least one high-level programming language.
Contents
1 Overview
1
1.1
History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1
1.2
Key Aspects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2
1.3
Hello World Demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3
2 Variables
4
2.1
Primitives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4
2.2
Assignments & Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5
2.3
Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6
3 Operators
7
4 Strings
7
5 Arrays
9
1
6 Conditionals
9
7 Loops
10
8 Input & Output
11
8.1
Command Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11
8.2
Standard I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12
8.3
File Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13
9 Searching & Sorting
14
10 Classes
15
11 Exceptions
18
List of Code Samples
1
Overview
1.1
History
• Developed by James Gosling, Sun Microsystems (1995)
• Designed with 5 basic principles
– Simple, Object-oriented, familiar
– Robust and secure
– Architecture-neutral and portable
– High performance
– Interpreted, threaded and dynamic
• Version History
– 1.0 1996
– 1.1 1997 introduced JDBC, inner classes, reflection
– 1.2 1998 Collections framework
– 1.3 2000 JNDI, HotSpot JVM
– 1.4 2002 Library improvements
2
– 1.5 2004 Generics introduced, enhanced-for loop (foreach loop), concurrency utilities
– SE6 2006 JVM improvements (synch, compiler, garbage collection), Update 26
(June 7, 2011)
– 1.7 July 2011
• 2009–2010: Oracle purchases Sun
• Summer 2012: Oracle loses lawsuit to Google (APIs, interfaces cannot be copyrighted)
1.2
Key Aspects
• C-style syntax: semicolons, bracketed code blocks, identifiers
• Objected-oriented: everything is a class or belongs to a class
• No memory management
– Built-in garbage collection
– When no valid references to an object exist, it is eligible for garbage collection
– JVM uses sophisticated algorithms to determine when it is optimal to perform
garbage collection
– Little or no control on when or how this occurs
• Portable
– Write once, compile once, run anywhere
– Compiled code is run within a Java Virtual Machine
1.3
Hello World Demo
• Packages
– Packages allow you to organize code into a tree-like structure
– Period delimits packages-subpackages
– Naming convention: all lower case, underscores; should go from general to specific
– Actual code is stored in a directory tree corresponding to the package names
• Class declarations
– Java: everything is a class or belongs to a class
– Code must be in a file with the same name as the class, HelloWorld.java
3
– Naming convention: UpperCamelCase
• Comments follow C-style comments
– //single line comments
– /* multi line comments */
– Javadoc style comments
• Main method declaration
• Standard output ( System.out.println )
• JDK Libraries
– http://download.oracle.com/javase/6/docs/api/
– java.lang , java.util , java.io , java.sql , java.net , java.math , java.security
– Collections: List, ArrayList, Set, HashSet, Map, HashMap
1
package unl.cse;
//package declaration
2
3
//imports would go here
4
5
6
7
8
/**
* A basic hello world program in Java
*/
public class HelloWorld {
9
//static main method
public static void main(String args[]) {
System.out.println("Hello World!");
}
10
11
12
13
14
15
}
• Command line demo
– Editing
– Compiling: javac HelloWorld.java
– Produces a .class file (Java Bytecode)
– Running: java HelloWorld
4
• IDE (Eclipse) demo
– Create a project, package, class
– Compiling: automatic; running
2
Variables
2.1
Primitives
• A primitive is a type that is built-in to a language
• Java defines 8 primitives (see Table 1)
• Java does define default values for variables: zero for numeric types, false for
boolean types
Type
byte
short
int
long
float
double
boolean
char
Details
8-bit signed 2s complement integer
16-bit signed 2s complement integer
32-bit signed 2s complement integer
64-bit signed 2s complement integer
32-bit IEEE 754 floating point number
64-bit floating point number
may be set to true or false
16-bit unicode character
Wrapper Class
Byte
Short
Integer
Long
Float
Double
Boolean
Character
Table 1: Primitive types in Java
• Wrapper classes provide an object-equivalent version for each primitive type
• Wrapper classes have many utility functions for conversion, parsing, etc.
• Instances can be null , may need to make null pointer checks
• Instances of such classes are immutable: once created, they cannot be changed; only
new instances can be created
5
1
2
3
4
5
6
7
2.2
//convert a string to an integer:
String s = "1234"
int a = Integer.parseInt(s);
String a_bin = Integer.toString(a, 2);
System.out.println(a + " in binary is " + a_bin);
Integer b;
a += b; //would result in a NullPointerException
Assignments & Literals
• The standard assignment operator, =
• Standard numerical literals integers, floats (f), longs (l); scientific notation supported,
4.2e1 or 4.2E1
• Different bases supported (see Code Sample ??)
• Character literals delimited by single quotes, char a = ’C’ or unicode (hex) escape:
char a = ’\u4FFA’
• String literals delimited by double quotes, String s = "hello";
• Standard escape sequences
Sequence Meaning
1
2
3
4
5
int
n =
n =
n =
n =
\b
backspace
\t
tab
\n
line feed
\f
form feed
\r
carriage return
\"
double quote
\’
single quote
\\
backslash
n;
0b0010_1010; //binary, Java 7 only
052; //octal, leading zero
42; //decimal
0x2A; //hex
6
2.3
Declaration
• Java is strongly typed ; every variable must be declared to have a particular type and
will always be that type (aka statically typed )
• Identifier rules:
– Identifiers can include characters A-Z, a-z, 0-9, _, $ but cannot begin with
a digit
– Identifiers are case sensitive
– Naming convention: lowerCamelCase
– Naming convention: CAPS_FOR_STATIC_CONSTANTS
– Cannot be a reserved word (see http://download.oracle.com/javase/tutorial/
java/nutsandbolts/_keywords.html)
• Scoping rules: variables are only valid within the block in which they are declared
• Casting: java does not allow implicit type casting when downcasting, does allow explicit; see Code Sample ??
1
2
3
4
5
6
7
8
9
10
3
Double x = 10; //compile error
double y = 10; //okay (!)
Integer z = 10.0; //compile error
int a = 10.0; //compile error
//explicit type casting is required:
int a = 10;
double b = 10.5;
double x = a + b; //okay
int c = a + b; //compile error
int d = (int) (a+b); //explicit cast ok, truncation occurs
Operators
• Unary operators: increment/decrement, ++, -• Arithmetic: * / + - %
• Relational
– <, <=, >, >=
– Equality: ==, != : careful when used with objects: reference comparison
• Logical: !, &&, (can only be applied to boolean expressions or variables, not integers!)
7
4
Strings
• Strings are a class provided as standard by the language
• Immutable; mutable version: StringBuilder
• Concatenation operator: +
• Comparison
– Using == is a reference operator, not a content comparison
– Strings are naturally ordered (lexicographically) by the language
– Meaning: they implement the Comparable interface
– They have a method: a.compareTo(b) which returns:
∗ 0 if a , b have the same content
∗ < 0 if a precedes b ( a comes before b )
∗ > 0 if a succeeds b ( b comes before a )
• Various other member and static methods exist:
– public char charAt(int) - returns the character at the specified position
– public String substring(int, int) - returns the substring between the indices (inclusive/exclusive)
– public String replaceAll(String, String) - replaces all matches to the
(first) regular expression with the second
– More: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
8
a
foo
bar
foo
aaa
b
bar
baz
foo
aaaa
Result
positive
negative
zero
negative
Table 2: Examples results of a.compareTo(b)
1
2
String s1 = "Hello" + " " + "World!";
System.out.println(s1);
3
4
5
6
7
8
StringBuilder sb = new StringBuilder();
sb.append("Goodbye");
sb.append(" ").append("World!");
String s2 = sb.toString();
System.out.println(s2);
9
10
11
12
13
14
15
16
if(s1.compareTo(s2) > 0) {
System.out.println("Goodbye World! comes second");
else if(s1.compareTo(s2) < 0) {
System.out.println("Hello World! comes second");
} else {
System.out.println("They are equal somehow");
}
17
18
19
5
//replace all whitespace with underscores:
String s3 = s1.replaceAll("\s", "_");
Arrays
• All arrays are statically typed
• Implicit size declaration:
String myStrings[] = {"Hello", "world", "how", "are", "you"};
• Dynamic declaration using the new operator:
String myStrings[] = new String[10];
int myIds[] = new String[20];
• Arrays are zero-indexed and contiguous; size is kept track through a .length property:
• Multidimensional arrays supported
9
• Dynamic Collections alternative: ArrayList
1
2
3
int myIds[] = new int[10];
myIds[0] = 10;
System.out.println("myIds is an array of size " + myIds.length + ", and the first el
4
5
6
int myMatrix[][] = new int[5][5];
myMatrix[0][4] = 10; //first row, last column
7
8
9
10
11
12
6
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(10);
myList.add(20);
myList.add(30);
System.out.println("myList is an array list of size " + myList.size() + ", and the f
Conditionals
• All the basic if-statements are supported
• Switch statements supported for integers
• Switch statements supported for Strings as of Java 7
10
1
2
3
if(a > b) {
System.out.println("foo");
}
4
5
6
7
8
9
if(a > b) {
System.out.println("foo");
} else {
System.out.println("bar");
}
10
11
12
13
14
15
16
17
if(a > b) {
System.out.println("foo");
} else if (a == b) {
System.out.println("bar");
} else {
System.out.println("baz");
}
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
7
int month = ...;
switch(month) {
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
default:
System.out.println("Smarch");
break;
}
Loops
• Basic loops supported: for, while, do-while
• Enhanced for-loop for collections (arrays or any class that implements the Iterable
interface)
11
1
2
3
for(int i=0; i<10; i++) {
System.out.println("i = " + i);
}
4
5
6
7
8
9
int j = 0;
while(j < 10) {
System.out.println("j = " + j);
j++;
}
10
11
12
13
14
15
j = 0;
do {
System.out.println("j = " + j);
j++;
} while(j <10);
16
17
18
19
20
String myStrings[] = {"hello", "world", "foo", "bar", "baz"};
for(String s : myStrings) {
System.out.println(s);
}
21
22
23
24
25
//older idiom for Iterable collections:
while(c.hasNext()) {
System.out.println(c.next());
}
8
Input & Output
8.1
Command Line Arguments
Most programs do not involve a user interface or even involve human interaction. Instead,
programs executed from the command line can be configured by specifying command line
arguments which are passed to the program when invoking it. For example:
~>./programName argument1 argument2
When a Java class is executed through the JVM via the command line, arguments can be
passed to the class in a similar manner:
~>java JavaClass arg1 arg2 arg3
Note:
• Arguments are accessible in the main method through the args array:
12
public static void main(String args[])
• In most languages, the first argument is the name of the executable file. However, for
Java, the first argument is not the class
• In the example above, arg[0] would hold the string arg1 , etc.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
8.2
/**
* This program demonstrates command line argument usage
* by printing out all the arguments passed to it when invoked.
*/
public class CommandLineArgumentDemo {
public static void main(String args[]) {
if(args.length == 0) {
System.out.println("No command line arguments provided");
} else {
for(int i=0; i<args.length; i++) {
System.out.println("args[" + i + "] = " + args[i]);
}
}
}
}
Standard I/O
• Standard Output: System.out (methods: print, println, printf )
• Printf-style formatting: String.format or System.out.printf
• Object-oriented formatting: java.util.Formatter class
• Several classes exist BufferedReader, BufferedWriter, InputStream, OutputStream
• Better alternative: Scanner
13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1
2
3
4
try {
String line = null;
//create a BufferedReader from a FileReader
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
//read the first line
line = br.readLine();
//while the line read is not null (end of file)
while(line != null) {
//process the line
System.out.println(line);
//read the next line
line = br.readLine();
}
} catch(Exception e) {
...
}
//read from the standard input:
Scanner s = new Scanner(System.in);
System.out.println("Enter an integer: ");
int n = s.nextInt();
5
6
7
8
9
10
11
12
13
14
//read from a file
Scanner s = new Scanner(new File("input.txt"));
int x = s.nextInt();
double y = s.nextDouble();
String s = s.next();
String line = s.nextLine();
while(s.hasNext()) {
line = s.nextLine();
}
15
16
17
18
8.3
//by default, Scanner tokenizes on whitespace,
//you can reset this to any regular expression:
s.useDelimiter(",");
File Output
• Buffered text output: BufferedWriter and FileWriter
• Binary output: FileOutputStream
14
• Non-buffered text output: PrintWriter
1
2
3
4
5
//Buffered text output:
File f = new File("outfile.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
//can write string or character data
bw.write("Hello World\n");
6
7
8
9
10
11
//Binary data output:
byte bArray[] = ...;
File f = new File("outfile.bin");
FileOutputStream fos = new FileOutputStream(f);
fos.write(bArray);
12
13
14
15
16
17
18
19
20
9
//Non-buffered text output (easier, but fails silently):
File f = new File("outfile02.txt");
PrintWriter pw = new PrintWriter(f);
pw.print("Hello");
pw.print(10);
pw.print(3.14);
//or:
pw.printf("%s, %d, %.4f\n", "Hello", 10, 3.14);
Searching & Sorting
• The Arrays class provides two sort methods for arrays
– Arrays.sort(...)
– Arrays.sort(T a[], Comparator<? super T> c)
• The Collections class provides two sort methods for lists
– Collections.sort(List<T> list)
– Collections.sort(List<T> list, Comparator<? super T> c)
• First version is for anything that is naturally ordered : any class that implements the
Comparable interface
• Second version is for any type, but you must provide a Comparator for it
• Searching: binarySearch methods, collections have contains , indexOf methods
15
1
2
int ids[] = ...;
Arrays.sort(ids);
3
4
5
6
7
8
9
10
11
12
13
14
Comparator<Student> c = new Comparator<Student>() {
public int compare(Student s1, Student s2) {
if(s1.getGPA() > s2.getGPA()) {
return -1;
} else if (s1.getGPA() < s2.getGPA()) {
return 1;
} else {
return 0;
}
}
};
15
16
17
Student roster[] = ...;
Arrays.sort(roster, c);
18
19
20
10
ArrayList<Student> roster = new ArrayList<Student>();
Collections.sort(roster, c);
Classes
Object-oriented programming involves the interaction of complex, abstract data types (ADTs),
often realized in programming languages as classes. Java is a class-based OOP language.
Classes can be viewed as a “blueprint” for creating (called instantiating) instances which
provide both state and behavior.
• Declaration
• Member variables: visibility-level type name;
• Visibility keywords (cf. Table 3), accessors/mutators: getters and setters
• Member methods: declared inside a class
• Constructors: same name as the class, no return type, multiple constructors can be
defined; default one provided if none are defined
• Instantiation ( new keyword invokes a constructor)
• Usage: dot operator
• Other modifiers
16
– static can be used with a method or variable to make it a member of the class
instead of instances of the class. Access would then be through the class rather
than an instance: BankAccount.foo()
– final can be used with a variable to make it a constant; attempts to modify a
final variable are a compiler error
– final can also be used on methods (to make them non-virtual); and classes (to
make them non-derivable)
17
1
public class BankAccount {
2
public static final String BANK_NAME = "First International Bank Co.";
3
4
private
private
private
private
5
6
7
8
int bankAccountId;
String label;
double balance;
double apr;
9
public BankAccount(int bankAccountId, String label, double balance, double apr) {
this.bankAccountId = bankAccountId;
this.label = label;
this.balance = balance;
this.apr = apr;
}
10
11
12
13
14
15
16
public BankAccount(int bankAccountId, String label) {
this(bankAccountId, label, 0.0, 0.0);
}
17
18
19
20
public int getBankAccountId() {
return this.id;
}
21
22
23
24
public void setBalance(double balance) {
this.balance = balance;
}
25
26
27
28
//more getters and setters as desired here
29
30
public void deposit(double deposit) {
this.balance += deposit;
}
31
32
33
34
public double getMonthlyInterestEarned() {
return this.balance * this.apr / 12.0;
}
35
36
37
38
private double getAPY() {
return Math.exp(this.apr) - 1;
}
39
40
41
42
@Override
public String toString() {
return this.label + " (" + this.bankAccountId
+ ") $" + this.balance;
18
}
43
44
45
46
47
}
48
49
50
...
Keyword
public
protected
public
private
Class Package
Y
Y
Y
Y
Y
Y
Y
N
Subclass(es)
Y
Y
N
N
World
Y
N
N
N
Table 3: Visibility Keywords and Access Levels
11
Exceptions
• Run-time errors occur when something goes wrong and your program cannot handle
it (or by design shouldn’t)
• We may be able to recover from some errors by handling them
• An Exception is an error that is not usual, but could be anticipated ( FileNotFoundException )
• Exceptions can be thrown or caught and handled
• Handling can be done in a try-catch-finally block
• Many predefined standard exceptions
• Uncaught exceptions will bubble up until caught or it kills the JVM process
19
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
String s = ...;
int n;
try {
//potentially unsafe code:
n = Integer.parseInt(s);
} catch(NumberFormatException nfe) {
System.out.println("String does not contain a valid numeric representation");
} catch(NullPointerException npe) {
System.out.println("String is null!");
} catch(Exception e) {
System.out.println("Some other exception occurred, stack track follows...");
e.printStackTrace();
} finally {
//this code block will be executed whether or not an exception is thrown
//could be used to clean up any outstanding resources
}
17
18
19
20
21
//throwing:
if(n == 0) {
throw new RuntimeException("cannot divide by zero!");
}
20