1 / 68

Introduction to Java Programming and BlueJ IDE

Learn the basics of Java programming and how to use the BlueJ IDE for developing Java programs. Topics include writing code, using methods and constructors, and understanding fields and variables.

lydiawalker
Télécharger la présentation

Introduction to Java Programming and BlueJ IDE

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CPSC150 Spring 2006 Dr. L Lambert

  2. Week 1/2 intro (and Chapter 1)

  3. Syllabus • Java • CPSC150Lab • Attendance, but does not count • weekly quiz. Due the next week. Graded. Collaborative. Come prepared to work on it in class. • Come see me/Java expert early and often • Ask questions • Consult with (possibly non-expert) peers, but be careful. >50% of your grade is exams.

  4. Virtual Machine • Review: • Computers understand machine language only • Each computer has its own language • No computer understands English, Powerpoint, or Java • Java developed to be platform independent • Virtual machine built on top of each actual machine to make all machines (windows, mac, UNIX) look alike • Java compiles to byte-code – not machine code, but “virtual machine code”

  5. Why Java? • Java is a large, complete language • Works well with web applications • GUIs “part” of the language • Extensive libraries • (Other CS courses will cover C++)

  6. Why BlueJ • Easy to use • Object-oriented • Start programming immediately • GUI, not console-based • Object visualization using UML • Debugger, Editor, other standard stuff • Simple, not for advanced applications

  7. Using Java and BlueJ • We will use BlueJ for program development • BlueJ runs on the Java virtual machine • BlueJ is IDE – lots of others (e.g., Eclipse) • BlueJ is free and available for Mac, Windows, UNIX • You will test and submit program using UNIX • Use your Hunter Creech Account • Download BlueJ for your home machines for development: www.bluej.org • (download Java 1.5 first): http://java.sun.com/j2se/1.5.0/download.jsp (Download SDK, NOT JRE)

  8. Reading and Writing Java Code Weeks 1 and 2 Chapters 1 and 2

  9. By the end of this week, you should know how to: • Write a Java program • Use BlueJ to write and run a Java program • Call methods from inside a program and from the object bench • Use parameters in method definitions and method calls • Use instance variables/fields • Create constructors • Write assignment statements • Write mathematical expressions

  10. Terms on test 1 • object (on object bench and in source code) • class, instance • default constructor, overloading • method (definition) • method call • return value • parameter • source code • signature (in source code and external view) • formal parameter • actual parameter • type

  11. Writing a Java program // import statements if any public class Name { // instance variables or fields // visible to all methods in class // constructors. with no parameters is Default // methods }

  12. /** starts javadoc. TimesTable performs multiplication/times table */ public class TimesTable // NO ( ) s in class { private int factor; // field /** have javadoc for every class, constructor and method * Constructor . without parameter, called default constructor. no return type */ // return type void because nothing is returned public void TimesTable(int nbr) // actual parameter has type AND name { factor = nbr; // assignment statement } public int times(int nbr) // return type int { return nbr * factor; // math } // other methods go in here. printTimes(int nbr) and printTable( ) }

  13. Do your own On the board, with 1 or 2 others, write: • printTimes(int nbr) • printTable( )

  14. // insert these methods into class on previous slide public void printTimes(int nbr) { // System.out.println changes System.out.println(factor + " times " + nbr + " is " + times(nbr)); } public void printTable( ) // methods start with lowercase { printTimes(0); printTimes(1); printTimes(2); printTimes(3); printTimes(4); printTimes(5); printTimes(6); printTimes(7); printTimes(8); printTimes(9); }

  15. Class Details • Using bluej • Using methods • Fields/instance variables • constructors • methods

  16. Class details: fields/instance variables • Lifetime/scope of class • field vs local variable • private int myfield; // primitive • char, boolean, double, a few others • private String mystring; // class • private Circle sun; // from Shapes • user and library defined • BlueJ: primitive has data; object has pointer

  17. Source Code (Internal View) • import • Comments // single line /* */ multiline /** */ Javadoc • Class definitions public class Picture { // fields // constructors // methods }

  18. Class details: constructors • Initialize objects. Called when object is created • no return type • can be overloaded public void TimesTable (int nbr) { factor = nbr; } public void TimesTable ( ) { factor = 1; }

  19. Source Code (Internal View) • import • Comments // single line /* */ multiline /** */ Javadoc • Class definitions public class Picture { // fields // constructors // methods } • writing a method • methods vs fields vs local variables • Java statements • accessor/mutator methods

  20. first line signature or header (visible in external view also) return type int formal parameter list: type AND name curly braces, stuff inside is method body Local variable Java statements inside body, e.g., single = assignment return statement Class Details: Methods • General Structure: public/private return-type name (param1name param1type, param2name param2type) • times method from TimesTable: public int times(int nbr) { int answer; answer = nbr * factor; return answer; }

  21. Method vs. Field • Both have private or public • Both have types • Both have names • fields have ‘;’ at end of line/methods do not • methods have ( ) (even without parameters); fields do not • methods have a body; fields do not • fields have memory to hold information; methods do not

  22. Field vs. Local variable • local variables declare in a method; fields outside of all methods • local variables have the lifetime of the method call • local variables and fields have type and ‘;’ • when possible, use local variables • local variables do NOT have private/public designation

  23. Writing methods:More Java statements • Arithmetic Expressions • Compound Assignment • System.out.println • this • new • dot notation: external method calls • return

  24. Arithmetic • +, /, *, -, % • Be careful about integer division • 4/3 p r 3 • Use codepad (Choose view, then codepad) • int answer=30; answer %= 4; System.out.println("Answer is " + answer);

  25. Compound Assignment • assignment: • answer = factor1 * factor2; • answer = answer + newsum; • compound assignment • answer += newsum; • answer -= diff; • answer *= product; // e.g., factorial • answer /= digit; // getting rid of digits • answer %= digit;

  26. Math ProblemsDo on board • int x=3; double y=4.0; x + y x / 2 y / 3 x % 2 x % 3

  27. System.out.println( ) • To print out messages to a terminal • Can print strings or integers • Use + to concatenate/append. Be careful with numbers • e.g., • System.out.println("Answer is " + answer); • System.out.println(answer + answer); • System.out.println(“answer is” + answer + answer);

  28. this public void changeColor(String newColor) { color = newColor; draw( ); } • public void • changeColor(String color) • { • this.color = color; • draw( ); • } this specifies the current object

  29. new, dot notation public void draw() { wall = new Square( ); wall.moveVertical(80); wall.changeSize(100); wall.makeVisible(); //rest of method from Picture class } To create a new object, use new. calls constructor External method call dot notation

  30. return statement public int sum(int x, int y) { int answer; answer = x+y; return answer; } type of method is return type to return a value, use ‘return value’; can be calculation

  31. Another Java Example: Picture.java public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; public Picture() { // nothing to do... instance variables are automatically set to null } // other methods }

  32. Picture.java public void draw( ) { wall.makeVisible(); window = new Square(); window.changeColor("black"); window.moveHorizontal(20); window.moveVertical(100); window.makeVisible(); roof = new Triangle(); roof.changeSize(50, 140); roof.moveHorizontal(60); roof.moveVertical(70); roof.makeVisible(); sun = new Circle(); // set sun to be where it should be }

  33. Picture.java Constructor: • now: blank canvas like TV show • one option: create a finished picture • another option: create shapes, then put them on Modify to do second option

  34. Picture.java On the board, write a new constructor and a new draw( ) that creates the shapes, then puts them on

  35. More Picture.javaon the board • Write a new constructor in Circle.java that allows Circles to be created in the right place with the right color. For example, instead of // old sun = new Circle( ); sun.changeColor("yellow"); sun.moveHorizontal(180); sun.moveVertical(-10); sun.changeSize(60); sun.makeVisible( ); // new // xPosition = 180 + 20; // yPosition = 60-10 sun = new Circle("yellow", 60, 200, 50); sun.makeVisible( );

  36. Common Methods to Write • Wizard at writing code; let’s look at common methods • Mutator method: change value of a field • Accessor method: get the value of a field

  37. Common methods: Accessor • Retrieve the value of a part of a class, often a field • no parameter, return type is type of value being returned • method body is (often) one line public class Fraction { // only a little bit defined private int numerator; private int denominator; public int getNum() { return numerator; } }

  38. Common Method: mutator • Changes field value • void return type, one parameter, the new value • not all fields have mutator methods public class fraction {// only a portion of this class private int numerator; private int denominator; public void setNum(int newvalue) { numerator = newvalue; } }

  39. Do on board • Write a setFactor and a getFactor method

  40. Conditionals

  41. Conditionals • Execute code under some conditions • In Canvas public static Canvas getCanvas() { // only create Canvas if not already created if (canvasSingleton == null) { canvasSingleton = new Canvas("BlueJ Shapes Demo", 300, 300, Color.white); } canvasSingleton.setVisible(true); // does this no matter what return canvasSingleton; }

  42. if statements if (booleanexpression) java statement; we don’t know about this any Java statement you know about

  43. Boolean Expressions • Evaluate to be true or false • boolean variables • boolean isVisible = false; • relational expressions (compares values) • logical expressions (compares expressions with and, or, not)

  44. Relational Operatorsfor primitives int x, y; • x < y • x <= y • x > y • x >= y • x != y • x == y // NOT x=y • NOTE: most of these don’t work for classes (== is a problem)

  45. Evaluating Boolean ExpressionsDo on board with partners int x=3; int y = 4; int z=5; x < y true x < y < z error: < cannot be applied to boolean,int x = y error: incompatible types - found int; expected boolean y == 4 true z >= x false x != 3 false (x + 4) < (y - 1) 7 < 3; false

  46. Logical Operators • and (&&, single & very different) • both values must be true for the expression to be true • if it is cold and rainy, wear your winter raincoat (both must be true) • or (|| - on keyboard, called pipe symbol) • either value can be true • if it is cold or rainy, wear a coat (if either or both is true, do) • not (!) • changes the truth value of the expression • if it is not cold, do not wear a winter coat

  47. int x=3; int y=10; (x < y) && (y < 20) (x == 3) || (y == 3) x < y; 3 < 10; true y < 20; 10 < 20; true true && true is true x == 3 true. short circuit evaluation (y==3 false true || false is true) Logical OperatorsDo on board

  48. int x=3; int y=10; !(y=10) (x != 3) || (y != 3) trick question error !(y==10) y == 10 true !true false x != 3 false Keep going. y != 3 true false || true is true More logical operatorsDo on board

  49. int x=3; int y=10; !((x+1 < 4) || (y <= 10)) !((x+1 < 4) && (y <= 10)) x+1 = 4 4 < 4 false.keep going y <= 10 true false || true true ! true is false 4 < 4 false. DONE with &&. Do not look at y <=10. !false true Yet more logical operatorsDo on board

  50. Strings and Classes • == tests if objects are equal (point to the same thing), NOT if they have the same content. May return false when true should be returned • use equals • no corresponding <, lessthan,… • use compareTo • Difference between primitives (holds a value) and Classes (holds a pointer) is important. • = is for comparing if values are the same

More Related