Professional Documents
Culture Documents
Java Basics I
What is Java?
Who developed Java?
Java is developed at Sun under the direction of James Gosling.
Why Java?
Architecture neutral (or portable) Object-oriented Simple, compiled, and statically typed Multi-threaded Garbage collected Robust (exception handling is a must) Really easy to implement because everything is there (from students perspective).
Different Versions
J2SE (regular desktop applications), J2ME (PDAs, cell phones)
Java 2 Platform
} <html> <head> <title>Hello, World</title> </head> <body> Here is the output: <p> <applet code="HelloApplet.class" width=150 height=25></applet> <p> </body> </html>
How to run?
% java Sample
How does the JVM find the classes that it has to run?
The JVM finds the class loader using the CLASSPATH environment variable In a bash/sh environment, % CLASSPATH=/home/jmk/classes.jar:$CLASSPATH % export CLASSPATH
Comments
/* text */ // text /** text */, then you can generate javadoc documents by running % javadoc Sample.java
7
What is a variable?
A memory location to store data. <type> <identifier>; or <type> <identifier> = <expr>; E.g., int count; or int count = 10; <type>: int, float, long, double <identifier>: a sequence of letters and digits when the first must be a letter. Must be self-identifying and no Java reserved words.
8
Example
char myChar = a;
int index = 1;
Assignments
Stores values into a variable.
<variable> = <expression> The result of <expression> is assigned to <variable>. <expression> is any valid combination of constants, variables, parentheses, and arithmetic or boolean operators. count = 5; sum = sum + myCount;
10
Arithmetic Expressions
Addition: var1 = var2 + var3; Subtraction: var1 = var2 var3; Multiplication: var1 = var2 * var3; Division: var1 = var2 / var3; Modulus (remainder): var1 = var2 % var3; Shortcuts for binary operators
a += 1, a -= 1, a *= 1, a /= 1, a %= 1
Integer arithmetic
int x = 4/3, then x=1
Bitwise operations
& (and), | (or), ^ (xor)
11
Results
3 4 7 -3 -4 -7 5 5 >> 1 -5 -5 >> 1 -5 >>> 1 = = = = = = = = = = = 3 4 7 -3 -4 -7 5 2 -5 -3 2147483645 = = = = = = = = = = = 00000000000000000000000000000011 00000000000000000000000000000100 00000000000000000000000000000111 11111111111111111111111111111101 11111111111111111111111111111100 11111111111111111111111111111001 00000000000000000000000000000101 00000000000000000000000000000010 11111111111111111111111111111011 11111111111111111111111111111101 01111111111111111111111111111101
13
Negative Numbers?
How do we represent negative integers? Use twos complement representation. How to compute the twos complement of an integer?
Obtain the ones complement first. How? Convert 0 to 1 and 1 to 0. The twos complement is the ones complement plus 1.
Example
+3 = 0011, +4 = 0100, +7 = 0111 -3 = 1101, -4 = 1100, -7 = 1001 What about -5 and -3?
14
Type Conversions
Automatic type conversion
In mixed-mode arithmetic, e.g., addition of integers and real numbers, a smaller data type is converted into a larger data type (widening conversion). double > float > long > int
Casting conversion
int x = (int) 89.99; double x = x + (double) y;
15
Continued
/** uses casts and literals */ void shortRange () { System.out.println("short\t" + Short.MAX_VALUE + "\t" + Short.MIN_VALUE); System.out.println("short\t" + (short)077777 + "\t" + (short)0x8000); } /** shifts ones until no further changes occur */ void byteRange () { byte i, j = 1; do { i = j; j = (byte)(i << 1 | 1); } while (j > i); System.out.print("byte\t" + i); do { i = j; j = (byte)(i << 1); } while (j < i); System.out.println("\t" + i); } public static void main (String args []) { Ranges aRange = new Ranges(); aRange.byteRange(); aRange.shortRange(); aRange.intRange(); aRange.longRange(); } }
18
Results
byte 127 -128 short 32767 -32768 Short 32767 -32768 int 2147483647 -2147483648 (~0 >>> 1) = 2147483647 01111111111111111111111111111111 (~ (~0 >>> 1) = -2147483648 10000000000000000000000000000000 long 9223372036854775807 -9223372036854775808
19
Strings
A string is a set of characters.
hello consists of h, e, l, l, and o. Example: I am Tom, 1+2=3
Get familiar with many useful String methods for concatenation, location, substrings, string comparison.
20
10
Strings
class StringThing { public static void main(String args[]) { String aString; aString = new String("Last Stop Wonderland"); System.out.println( aString.length() ); System.out.println( aString.toUpperCase() ); System.out.println( aString.toUpperCase() + "."); } }
Results?
20 LAST STOP WONDERLAND LAST STOP WONDERLAND.
21
More on Strings
class String_1 { public static void main( String args[] ) { String aString = "David"; String bString = "David Bowie"; if ( "hello".equals("hello") ) System.out.println("equal"); if ( "David" == aString ) System.out.println("David == aString "); System.out.println(aString.length()); System.out.println(aString.charAt(0)); System.out.println(aString.indexOf("vid")); System.out.println(aString.substring(2,3)); System.out.println(aString.substring( aString.indexOf("a"), aString.indexOf("i") )); System.out.println(aString.concat(" Bowie").length()); String help = bString.substring(0, aString.length()); System.out.println("-->" + help + "<--" ); if ( "David" == help ) System.out.println("David == help "); if ( "David" == aString ) System.out.println("David == aString "); } }
22
11
Result
equal David == aString 5 D 2 v av 11 -->David<-David == aString
23
Unicode
Numbers are represented using 0s and 1s in computer memory, e.g., twos complement. How do we represent characters in computer memory? We use special codes of 0s and 1s, e.g., 65 for A. We should use a common encoding scheme.
ASCII: 8 bits for 128 codes
What about then non-English or non-European languages? We definitely need more bits. Lets use Unicode (2 bytes)! We can print code or symbols as follows.
System.out.println((int)A + (char)88);
24
12
Strings to Integers?
How can we convert a string to an integer?
class StringToInt { public static void main(String args[]) { int i; Integer aInt = new Integer("4"); i = aInt.intValue(); i = Integer.parseInt("4"); } }
25
Strings + Numbers?
class StringAndInteger { public static void main(String { System.out.println("Well, 3 System.out.println("Well, 3 System.out.println("Well, 3 } } args[]) + 4 = " + 7 ); + 4 = " + 3 + 4 ); + 4 = " + ( 3 + 4 ) );
Results?
Well, 3 + 4 = 7 Well, 3 + 4 = 34 Well, 3 + 4 = 7
26
13
Selection Statement
Statements are executed in the order listed and are always terminated by a semicolon.
Statement1; Statement2; Statementn;
14
Boolean Expressions
The truth table
P T T F F
Q T F T F
P && Q P || Q T F F F T T T F
!P !(P&&Q) !P||!Q F F T T
(9) (8)
!(P||Q) !P && !Q F F F T F F F T
(4) (3) (2) (1)
F T T T
Precedence
F T T T
Parentheses: () Unary operators: !, Multiplicative operators: *, /, % (7) Additive operators: +, Relational operators: <, <=, >, >=
(6) (5)
29
30
15
31
The Loop
How can I repeat the execution until a certain condition is met? Use the loop -- while, for, do-while while
while ( expression ) statement
for
for ( init; expression; increment ) statement
do-while
do statement while ( expression);
32
16
Example: while
Can you write a program that computes sqrt(2) without java.util.Math?
class Sqrt { private double calculateSqrt_2() { double n1 = 1.0; double n2 = 2.0; while ( (n2 * n2 - n1 * n1) > 0.0001) { double x = ( n2 + n1 ) * 0.5; if ( x * x > 2.0 ) n2 = x; else n1 = x; } return n1; } public static void main( String args[] ) { System.out.println("sqrt(2) = " + new Sqrt().calculateSqrt_2() + " +- 0.0001 " ); } }
33
Example: for
Write a program that finds all the prime numbers between 2 and 100.
class Prime_1 { private boolean isPrime(int n) { for ( int index = 2; index < n; index ++ ) { if ( n % index == 0 ) return false; } return true; } public static void main( String args[] ) { Prime_1 aPrime = new Prime_1(); for ( int index = 2; index <= 100; index ++ ) if ( aPrime.isPrime(index) ) System.out.println(index + " " ); } }
34
17
Flow Control
The continue statement without a target transfers control to the innermost loop.
class Continue_1 { public static void main( String args[] ) { int n = 0; // here: while ( n < 5 ) { System.out.println("outer while here n == " + while ( n < 5 ) { // while ( true ) --> n++; System.out.println("inner while here n == " if ( n > 2 ) continue; // continue here; System.out.println("inner while here n == " } } } }
+ n + "--------");
35
Result
outer while here n == 0 inner while here inner while here inner while here inner while here inner while here inner while here inner while here n n n n n n n == == == == == == == 1 1-------2 2-------3 4 5
36
18
Flow Control
The break statement without a target transfers control to the innermost enclosing loop or switch statement.
class Break_1 { public static void main( String args[] ) { int n = 0; // here: { System.out.println("here {"); while ( n < 100 ) { if ( n > 4 ) System.exit(1); while ( n < 100 ) { n++; System.out.println( inner while here n == " + n); if ( n > 2 ) // break here; break; } System.out.println("outer while here n == " + n); } // } System.out.println("after here }"); } }
37
Result
here { inner while here inner while here inner while here outer while here n == 3 inner while here outer while here n == 4 inner while here outer while here n == 5 n == 1 n == 2 n == 3 n == 4 n == 5
38
19
Example
You can test multiple values
break; break;
Causes execution to continue from the statement following the switch statement.
39
Example: switch
class Many { static void howManyWithBreak(int k) { System.out.println(k + ":------------------"); switch (k) { case 1: System.out.println("with break: one "); break; case 2: System.out.println("with break: too "); break; default: System.out.println("with break: many"); } } static void howManyWithoutBreak(int k) { System.out.println(" " + k + ":------------------"); switch (k) { case 1: System.out.println(" without break: one "); case 2: System.out.println(" without break: too "); default: System.out.println(" without break: many"); } } public static void main(String[] args) { new Many().howManyWithBreak(3); new Many().howManyWithBreak(2); new Many().howManyWithBreak(1); new Many().howManyWithoutBreak(3); new Many().howManyWithoutBreak(2); new Many().howManyWithoutBreak(1); } }
40
20
Result
3:-----------------with break: many 2:-----------------with break: too 1:-----------------with break: one 3:-----------------without break: many 2:-----------------without break: too without break: many 1:-----------------without break: one without break: too without break: many
41
Motivation: Arrays
Suppose that you want to read 100 numbers, compute their average, and find out how many numbers are above the average. The problem is that those numbers must all be stored in variables. One possible way is to declare 100 variables and repeatedly write almost identical code 100 times. Would you like this way? Of course NOT. Our answer is to use an array! What is an array?
42
21
Arrays
An array is used to store a collection of data, or can be thought of a collection of variables of the same type. How to declare array variables?
double[] myList;
4.5 4.2 9.9 8.2 4.5 0.0 0.1 4.5 5.2 0.3
43
More on Arrays
An element is accessed by the position in the array.
myList[3] == 8.2; // true
44
22
Example: Array
This program reads scores, finds the best score, and finally assigns grades to the students based on their grades.
public class AssignGrade { public static void main(String[] args) { int[] scores = new int[100]; int best = 0; char grade; for (int i = 0; i < scores.length; i++) { if (scores[i] > best) best = scores[i]; } for (int i = 0; i < scores.length; i++) { if (scores[i] >= best - 10) grade = A; else if (scores[i] >= best - 20) grade = B; else grade = C; output += Student + i + score is + scores[i] + and grade is + grade + \n; }}}
45
46
23
47
Recursive Definitions
A recursive definition of an entity defines the entity in terms of itself. Think about onions An onion is a sphere that has an outer layer, inside which is a smaller onion. For example, here is a list:
A B C D
24
Recursion
What problems can we solve using recursion?
Recursion can be used to solve problems that can be reduced to smaller instances of the same problem.
Can you write an iterative program using a loop? Can you write a recursive version of the factorial? What are the three basic elements?
49
Factorial
class Fact { private int factorial(int num) { if ( num <= 1) return 1; else return num * factorial(num-1); } public static void main(String args[]) { Fact f = new Fact(); for (int counter = 0; counter <= 10; counter++) System.out.println( counter + "! = f.factorial(counter)); } }
50
25
fact(4)
call return 3*2=6
fact(3)
call return 2*1=2 return 1*1=1
fact(2)
call
fact(1)
call return 1
fact(0)
Can you write an iterative program? Can you write a recursive program?
26