Download presentation
Presentation is loading. Please wait.
1
Week 1 - Wednesday CS221
2
Last time What did we talk about last time? Course overview Policies
Schedule
3
Questions?
4
Assignment 1
5
Programming Model
6
Programming model The book talks about stuff that you know pretty well as Java programmers I just want to talk about a few issues Primitive types Shortcut notations Short circuit logic break and continue Libraries Strings
7
Primitive types Java has relatively strong typing
Understand why you're making a cast, and try not to make casts for no reason Remember that all the primitive numerical types in Java are signed Strange things can happen byte x = -128; x *= -1; System.out.println(x); //output?
8
Shortcut notations Java has various shortcuts that are almost the same as combinations of other operators: +=, -=, *=, /=, %=, ++, -- (and a few others) And know what you're doing with ++: int i = 0; while( i < 10 ) i += 0.1; //legal but crazy int i = 0; i = i++; //legal but crazy i = ++i; //legal, crazy, different result
9
Short-circuit logic Short-circuit logic means:
true || expression won't even evaluate expression false && expression won't even evaluate expression You can force evaluation with non-short-circuit operators | and &: if( alwaysTrue() || explode() ) whatever(); //explode() didn't run if( alwaysTrue() | explode() ) whatever(); //explode() did run
10
break and continue I don't like break and continue inside of loops
search: for (i = 0; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } } break and continue I don't like break and continue inside of loops There is usually a more readable, more elegant way to write the code But you should know that Java has a seldom-used labeled break feature that allows you to break out of multiple loops Say you're searching through a multi-dimensional array for a value: search: for (i = 0; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } Example from:
11
Libraries The only thing worth mentioning is that you get java.lang.* "for free," without importing anything: String Math Object Thread System Wrapper classes (Integer, Double, etc.) Any other classes outside of the current package must be imported to be used
12
Strings The String type is immutable in Java
You can never change a String, but you can create a new String The second line creates a new String: This approach can be very inefficient: When a lot of concatenation is expected, use StringBuilder String stuff = "Break it down "; stuff += "until the break of dawn"; String values = ""; for( int i = 0; i < ; i++ ) values += i;
13
References
14
Pointers in Java Technically, Java doesn't have pointers
Instead, every object in Java is referred to with a reference A reference is just an arrow that points at an object A reference can point at nothing (null) A primitive type can never be null
15
How should you think about this?
Picture a ham… Imagine that this ham is actually a Java object You may want a reference of type Ham to point at this ham Let’s call it ham1 ham1
16
How many hams? ham2 Now, what if we have another Ham reference called ham2 What happens if we set ham2 to have the same value as ham1 using the following code? Ham ham2 = ham1; ham1
17
There is only one ham! When you assign an object reference to another reference, you only change the thing it points to This is different from primitive types When you do an assignment with primitive types, you actually get a copy x 37 y 37 int x = 37; int y = x;
18
Reference vs. primitive variables
Since reference variables are only pointers to real objects, an object can have more than one name These names are called aliases If the object is changed, it doesn’t matter which reference was used to change it
19
Ham solo ham2 Thus, if we tell ham2 to take a bite away, it will affect the ham pointed at by ham1 Remember, they are the same ham ham2.bite(); ham1
20
Remember that primitives make copies
We have int values x and y, both with value 37 If we change x, it only affects x If we change y, it only affects y int x = 37; int y = x; x++; y--; x 37 y 37 38 36
21
The clone() method Sometimes you want to make a full copy of an object
Every object has a clone() method that allows you to do this clone() is intended to make a deep copy instead of a shallow copy Ideally, all the objects inside of the object are cloned as well There is no way to guarantee that clone() gives deep copies for arbitrary objects clone() works well for Java API objects You have to write your own if you want your objects to work right Doing so can be tricky
22
Static
23
What is static? There are three ways that static can be used in Java
Static methods Static members Static inner classes "Staticness" is a confusing concept, but it boils down to missing a connection to a particular object
24
Static methods A static method is connected to a class, not an object
Thus, static methods cannot directly access non-static members You also can't use this inside them Static methods can indirectly access members since they have the privileges to access private and protected data You just have to pass them an object of the class they're in Static methods are slightly more efficient since they do not have dynamic dispatch Thus, they cannot be overridden, only hidden
25
Static methods public class X { private int x; public static void print() { System.out.println("X"); //x = 5; //previous line would not compile //if uncommented } public class Y extends X { System.out.println("Y");
26
Static methods X x = new X(); Y y = new Y(); X z; x.print(); //prints X y.print(); //prints Y z = x; z.print(); //prints X z = y;
27
Static members A static member is stored with the class, not with the object There is only ever one copy of a static member Static members are a kind of global variable They should be used very rarely, for example, as a way to implement the singleton design pattern Static members can be accessed by static methods and regular methods
28
Static members public class Balloon { private String color; private int size; private static int totalBalloons = 0; public Balloon(String color, int size) { this.color = color; this.size = size; totalBalloons++; } public String getColor() { return color; public static int getBalloons() { return totalBalloons;
29
Inner Classes
30
Static inner classes The simplest kind of inner class is a static inner class It is a class defined inside of another class purely for organizational purposes It cannot directly access the member variables or non-static methods of a particular outer class object
31
Static inner class example
public class LinkedList { private Node head; private static class Node { public int value; public Node next; } In this example, the Node class is used like a struct from C or C++ to hold values
32
Inner classes A non-static inner class is connected to a specific outer class object It can directly access the members and non-static methods of the outer class Outer Inner Inner Inner Inner Inner
33
Inner class example public class LinkedList { private Node head;
private int size; private class Node { public int value; public Node next; public Node() { if( size > 100 ) System.out.println( "Your list is too long!"); }
34
Creating inner classes
If a static inner class is public, you can create it directly However, a non-static inner class requires an instance of the outer class to be created (with weird syntax) Inside the outer class, it is not necessary to give a reference to the outer class, since this is assumed Outer.StaticInner inner; inner = new Outer.StaticInner(); Outer outer = new Outer(); Outer.Inner inner = outer.new Inner();
35
Exceptions
36
Exceptions Java handles errors with exceptions
Code that goes wrong throws an exception The exception propagates back up through the call stack until it is caught If the exception is never caught, it crashes the thread it's running on, often crashing the program
37
Kinds of exceptions There are two kinds of exceptions:
Checked Unchecked Checked exceptions can only be thrown if the throwing code is: Surrounded by a try block with a catch block matching the kind of exception, or Inside a method that is marked with the keyword throws as throwing the exception in question Unchecked exceptions can be thrown at any time (and usually indicate unrecoverable runtime errors)
38
Examples of exceptions
Checked exceptions FileNotFoundException IOException InterruptedException Any exception you write that extends Exception Unchecked exceptions ArrayIndexOutOfBoundsException NullPointerException ArithmeticException Any exception you write that extends Error or RuntimeException
39
Exceptions in code Scanner in = null; try { in = new Scanner( file ); while( in.hasNextInt() ) process( in.nextInt() ); } catch( FileNotFoundException e ) { System.out.println ("File " + file.getName () + " not found !"); finally { if( in != null ) in.close (); }
40
Threads
41
Threads In Java, concurrency and parallelism are achieved primarily through threads A thread is a path of code execution that runs independently of others But threads can share memory with each other Some other languages use message passing semantics and no direct memory sharing
42
Creating threads in Java
To create a customized thread in Java, there are two routes: Create a class which is a subclass of Thread Create a class which implements the Runnable interface If you subclass Thread, you can't subclass some other object If you implement Runnable, there's an extra bit of syntax to create a new thread
43
Sample thread to sum things
public class Summer extends Thread { private double[] array; private int start; private int end; private double result = 0.0; public Summer(double[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } public void run() { for( int i = start; i < end; i++ ) result += array[i]; public double getResult() { return result; }
44
Using Summer public double findSum( double[] array, int threads ) throws InterruptedException { Summer[] summers = new Summer[threads]; double result = 0.0; int step = array.length / threads; if( array.length % threads > 0 ) step++; for( int i = 0; i < threads; i++ ) { summers[i] = new Summer(array, i*step, Math.min((i+1)*step, array.length)); summers[i].start(); } summers[i].join(); result += summers[i].getResult(); return result;
45
Tips for concurrency Keep it simple
Do not share data via static variables Be careful with load balancing If the work is not evenly divisible by n (the number of threads), give the first n – 1 threads one extra piece of work Why? Be aware that threading out a program will not necessarily make it faster
46
Upcoming
47
Next time… Finish threads Generics Java Collection Framework
48
Reminders Continue to read section 1.1
Keeping brushing up on Java if you are rusty Start on Assignment 1 Project 1 will be assigned Friday Decide your teammates on Canvas for Project 1 by Friday, September 1
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.