You are on page 1of 26

Computer Science 1 (4003-231)

Java Basics I

Minseok Kwon (jmk@cs.rit.edu) Department of Computer Science Rochester Institute of Technology

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)

Computer Science 1 (4003-231)

Java 2 Platform

My First Java: Hello, World


class Hello { public static void main (String args []) { System.out.println("Hello World!"); } }

% javac Hello.java % java Hello Hello World!

Computer Science 1 (4003-231)

Do You Like GUI?


import javax.swing.*; import java.awt.event.*; public class HelloWorld { public static void main(String[] args) { JFrame frame = new JFrame("HelloWorld"); final JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.pack(); frame.setVisible(true); } } // for WindowEvent

How About Applets Then?


import import import public java.applet.*; // find Applet class java.awt.*; // find Graphics class javax.swing.*; // find Swing class class HelloApplet extends JApplet { public void init () { resize(150, 25); } public void paint (Graphics g) { g.drawString("Hello, World", 50, 25); }

} <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>

Computer Science 1 (4003-231)

Java Tools Basics


How to compile?
% javac Sample.java

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

Lets See More Details


public class Division { public static void main (String[] args) int oper1 = 9, oper2 = 4; double oper3 = 4.0; {

System.out.println(Integer division: + oper1/oper2); System.out.println(Floating division: + oper1/oper3); System.out.println(Remainder division: + oper1%oper2); } }

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

Computer Science 1 (4003-231)

Primitive Data Types


Integer: byte, short, int, long Character: unicode representation Boolean: true or false Floating-point: float, double
Type byte char short int long float double Size 8 bits 16 16 32 64 32 64 double prob = 7.896;
9

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

Computer Science 1 (4003-231)

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

Floating point arithmetic


float x = 4/3, then x = 1.333333 double x = 4/3, then x = 1.333333333333333

Bit shift operations


>> (shift right), << (shift left), >>> (unsigned shift right)

Bitwise operations
& (and), | (or), ^ (xor)
11

Example: Bit Operations


class BitPrint { private void printBytes (String what, int value) { System.out.print(what + "\t=\t" + value + "\t=\t"); for ( int index = 31; index >= 0 ; index --) { if ( ( ( 1 << index ) & value ) == ( 1 << index ) ) System.out.print("1"); else System.out.print("0"); } System.out.println(); } public static void main (String args []) { BitPrint aBitPrint = new BitPrint(); aBitPrint.printBytes("3 ", 3); aBitPrint.printBytes("4 ", 4); aBitPrint.printBytes("7 ", 7); aBitPrint.printBytes("-3 ", -3); aBitPrint.printBytes("-4 ", -4); aBitPrint.printBytes("-7 ", -7); aBitPrint.printBytes("5 ", 5); aBitPrint.printBytes("5 >> 1 ", (5 >> 1)); aBitPrint.printBytes("-5 ", -5); aBitPrint.printBytes("-5 >> 1 ", (-5 >> 1)); aBitPrint.printBytes("-5 >>> 1", (-5 >>> 1)); } }
12

Computer Science 1 (4003-231)

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

Computer Science 1 (4003-231)

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

Example: Type Conversion


class OpEx { public static void main(String args[]) { int intVar_1 = 1; int intVar_2 = 2; int intRes = 3; double doubleVar_1 = 3.8; double doubleVar_2 = 4.8; double doubleRes = doubleVar_1 - doubleVar_2; intRes = 5 / 3; System.out.println(intRes); intRes = 5 % 3; System.out.println(intRes); // intRes = 5 / doubleVar_2; // Doesn't work, why? intRes = (int)(5 / doubleVar_2); System.out.println(intRes); doubleRes = 5 / doubleVar_2; System.out.println(doubleRes); doubleRes = 5.0 / doubleVar_2; System.out.println(doubleRes); } } 1 2 1 1.0416666666666667 1.0416666666666667
16

Computer Science 1 (4003-231)

Putting All Together


class Ranges { /** uses complement operations */ short x; void intRange () { System.out.println("int\t" + (~0 >>> 1) + "\t" + (~ (~0 >>> 1))); printBytes("(~0 >>> 1)", (~0 >>> 1)); printBytes("(~ (~0 >>> 1))",(~ (~0 >>> 1))); } /** maximum and minimum long value */ static final long maxLong = ~0L >>> 1; static final long minLong = ~ (~0L >>> 1); private static void printBytes (String what, int value) { System.out.print(what + "\t=\t" + value + "\t=\t"); for ( int index = 31; index >= 0 ; index --) { if ( ( ( 1 << index ) & value ) == ( 1 << index ) ) System.out.print("1"); else System.out.print("0"); } System.out.println(); } void longRange () { System.out.println("long\t" + maxLong + "\t" + minLong); }
17

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

Computer Science 1 (4003-231)

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

How to create a string?


String s = new String(hello); String s = hello;

Get familiar with many useful String methods for concatenation, location, substrings, string comparison.

20

10

Computer Science 1 (4003-231)

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

Computer Science 1 (4003-231)

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

Computer Science 1 (4003-231)

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

Computer Science 1 (4003-231)

Primitive Data Types versus Objects


Does the Java program below compile or not? Why or why not?
class WillNotCompile { public static void main(String args[]) { String aString; aString.length(); } }

Not compile. Sorry.


WillNotCompile.java:18: Variable aString may not have been initialized. aString.length(); ^ 1 error

How about this? What happens?


class WillCompileButDie { public static void main(String args[]) { String aString = new String(); aString = null; aString.length(); } }
27

Selection Statement
Statements are executed in the order listed and are always terminated by a semicolon.
Statement1; Statement2; Statementn;

However, the if statement allows conditional execution of a statement. Syntax


if ( booleanExpression ) statement if ( booleanExpression ) statement1 else statement2
28

14

Computer Science 1 (4003-231)

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)

Equality operators:==, != Boolean AND: && Boolean OR: || Assignment: =

29

Finding the Max of Two


Can you write a Java program that finds the max of two given integers?
class Maximum_2 { public static double maximum(double _first, double _second ) { double max; if ( _first > _second ) max = _first; else max = _second; return max; } public static void main( String args[] ) { Maximum_2 aMaximum_2 = new Maximum_2(); double firstN = 42.0; double secondN = 666.0; System.out.println("Maximum(" + firstN + ", " + secondN + ") = " + aMaximum_2.maximum( firstN, secondN) ); } }

30

15

Computer Science 1 (4003-231)

Use ?: to Find the Max


Are you familiar with the conditional expression a ? b : c in C? Java has the same expression. Can you re-write Maximum_2 using this expression?
class Maximum_3 { private double maximum(double _first, double _second ) { return _first > _second ? _first : _second; } public static void main( String args[] ) { Maximum_3 aMaximum_3 = new Maximum_3(); double firstN = 42.0; double secondN = 666.0; System.out.println("Maximum(" + firstN + ", " + secondN + ") = " + aMaximum_3.maximum( firstN, secondN) ); } }

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

Computer Science 1 (4003-231)

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

Computer Science 1 (4003-231)

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); which problem + n);

+ n + "--------");

The continue statement with a target transfers control to the target.

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

Computer Science 1 (4003-231)

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

Computer Science 1 (4003-231)

The switch Statement


Syntax
switch (expression) { case constantExpr : action1 case constantExpr : action2 default: statementSequence }

Example
You can test multiple values

switch ( i ) { case 1: z=1; case 2: case 3: z=3; default: z=0; } z++;

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

Computer Science 1 (4003-231)

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

Computer Science 1 (4003-231)

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;

How to create arrays?


myList = new double[10];

If you want to declare and create an array,


double[] myList = new double[10];

In memory level, this means 0 1 2 3 4 5 6 7 8 9

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

How to initialize an array?


int[] n = new int[5]; for (int i = 0; i < 5; i++) n[i] = i; int[] m = { 1, 2, 3, 4, 5 };

How to copy an array?


int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArray.length; i++) targetArray[i] = sourceArray[i];

44

22

Computer Science 1 (4003-231)

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

Passing Arrays to Methods


Unlike primitive types, the reference to an array is passed to the method. What is the output?
public class Test { public static void main(String[] args) { int x = 1; int[] y = new int[10]; m(x, y); System.out.println(x is + x); System.out.println(y[0] is + y[0]); } public static void m(int number, int[] numbers) { number = 1001; numbers[0] = 5555; } }

46

23

Computer Science 1 (4003-231)

Advanced Issues on Arrays


How to return an array? Process two-dimensional arrays Process multidimensional arrays Use the java.util.Arrays class Searching and sorting arrays

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

The first entry A followed by a list

24

Computer Science 1 (4003-231)

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.

Three basic elements


A test to stop or continue the recursion An end case that terminates the recursion A recursive call(s) that continues the recursion

Example: Factorial Can you define the factorial of n recursively?


fact(n) = n * fact(n-1) if n > 1 fact(n) = 1 if n = 1

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

Computer Science 1 (4003-231)

What happens inside?


return 4*6=24

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)

Another one: Fibonacci


What is the Fibonacci sequence?
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Can you define this function F(n)?


F(n) = 0, if n=0 F(n) = 1, if n=1 F(n) = F(n-1) + F(n-2), o.w

Can you write an iterative program? Can you write a recursive program?

26

You might also like