1 / 95

An introduction to Java

An introduction to Java. What is Java?. Java is a programming language: a language that you can learn to write, and the computer can be made to understand Java is currently a very popular language Java is a large, powerful language but it is not simple! Compared to C++, Java is elegant.

tomasm
Télécharger la présentation

An introduction to Java

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. An introduction to Java

  2. What is Java? • Java is a programming language: a language that you can learn to write, and the computer can be made to understand • Java is currently a very popular language • Java is a large, powerful language • but it is not simple! • Compared to C++, Java is elegant

  3. Declarations, statements, comments • A declaration gives some information to the computer • A statement tells the computer to do something • Statements should really be called “commands” • Comments are ignored by the computer—they are explanations of your program for human beings to read

  4. Two aspects of Java • Java has syntax and semantics • This is where you begin • It is possible to learn everything about Java’s syntax and semantics • We will cover most of Java’s syntax and semantics • Java also has “packages” • Packages are sort of like vocabulary bundles • To be good at Java, you need to learn many packages • There are more Java packages than you can ever learn

  5. logic errors runtime error syntax errors compile run (execute) ok ok ok .java file .class file input data (optional) results The programming cycle ACTIONS: edit THINGS:

  6. Vocabulary I • JRE, Java Runtime Environment • This is the software that allows you to run Java programs on your computer • SDK, System Development Kit (previously called JDK, Java Development Kit) • The software that allows you to create and run Java programs on your computer • When you install the SDK, you get a JRE along with it • IDE, Integrated Development Environment • A tool that makes it easier to write programs

  7. Vocabulary II • Beta software • Software that is new, untested, often buggy • Interface • the place where things touch each other • the way that distinct things communicate • GUI, Graphical User Interface • A way for the computer and the user to communicate via graphics (pictures) on the screen

  8. JBuilder • JBuilder is an IDE (Integrated Development Environment). It includes • an editor, which you use to write your programs • a graphical editor, to easily create GUIs • a debugger, to help you find your mistakes • an easy way to organize and run Java programs

  9. What You Need • 256 MB of RAM (512 MB recommended) • 800 MHz Pentium III or better • Java JDK 1.4.2 or 1.5 (includes JRE) • JBuilder 2005 Foundation • By the way: the SDK and JBuilder Foundation are free

  10. Variables • A variable is a “box” that holds data • Every variable has a name • Examples: name, age, address, isMarried • Variables start with a lowercase letter • In multiword variables, each new word is capitalized • Every variable has a type of value that it can hold • For example, • name might be a variable that holds a String (sequence of characters) • age might be a variable that holds an integer value • isMarried might be a variable that holds a boolean (true or false) value

  11. Some Java data types • In Java, the four most important primitive (simple) types are: • int variables hold integer values • double variables hold floating-point numbers, that is, numbers containing a decimal point • boolean variables hold a true or false value • char variables hold single characters • Another important type is the String • A String is an Object, not a primitive type • A String is composed of zero or more chars

  12. Declaring variables • Every variable that you use in a program must be declared (in a declaration) • The declaration specifies the type of the variable • The declaration may give the variable an initial value • Examples: • int age; • int count = 0; • double distance = 37.95; • boolean isReadOnly = true; • String greeting = "Welcome to CIT 591"; • String outputLine;

  13. Assignment statements • Values can be assigned to variables by assignment statements • The syntax is: variable = expression; • The expression must be of the same type as the variable • The expression may be a simple value or it may involve computation • Examples: • name = "Dave"; • count = count + 1; • area = (4.0 / 3.0) * 3.1416 * radius * radius; • isReadOnly = false; • When a variable is assigned a value, the old value is discarded and totally forgotten

  14. Comments • A comment is a note to any human reading the program; comments are ignored by Java • There are three kinds of comments: // starts a comment that goes to the end of the line /* starts a comment that can extend over many lines,and ends at */ /** is a “javadoc” comment that can be extractedfrom your program and used in documentation */ • A comment may be put after a statement (on the same line) to say something about that one statement • A comment may be put before a statement, to say something about the following statements • Example: • // Swap the values of x and ytemp = x; // save old value of x in tempx = y; // replace old value of x with yy = temp; // this many comments is just silly

  15. Methods • A method is a named group of declarations and statements • void tellWhatYearItIs( ) { int year = 2004; System.out.println("Hello in " + year + "!");} • We “call,” or “invoke” a method by naming it in a statement: • tellWhatYearItIs( ); • This should print out Hello in 2004!

  16. Arithmetic expressions • Arithmetic expressions may contain: • + to indicate addition • - to indicate subtraction • * to indicate multiplication • / to indicate division • %to indicate remainder of a division (integers only) • parentheses ( ) to indicate the order in which to do things • An operation involving two ints results in an int • When dividing one int by another, the fractional part of the result is thrown away: 14 / 5 gives 2 • Any operation involving a double results in a double:3.7 + 1 gives 4.7

  17. if statements • An if statement lets you choose whether or not to execute one statement, based on a boolean condition • Syntax: if (boolean_condition)statement; • Example:if (x < 100) x = x + 1; // adds 1 to x, but only if x is less than 100 • C programmers take note: The condition must be boolean • An if statement may have an optional else part, to be executed if the boolean condition is false • Syntax:if (boolean_condition)statement; else statement; • Example:if (x >= 0 && x < limit) y = x / limit;else System.out.println("x is out of range: " + x);

  18. Compound statements • Multiple statements can be grouped into a single statement by surrounding them with braces, { } • Example:if (score > 100) { score = 100; System.out.println("score has been adjusted"); } • Unlike other statements, there is no semicolon after a compound statement • Braces can also be used around a single statement, or no statements at all (to form an “empty” statement) • It is good style to always use braces in the if part and else part of an if statement, even if the surround only a single statement • Indentation and spacing should be as shown in the above example

  19. while loops • A while loop will execute the enclosed statement as long as a boolean condition remains true • Syntax: while (boolean_condition)statement; • Example: n = 1; while (n < 5) { System.out.println(n + " squared is " + (n * n)); n = n + 1; } • Result: 1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16 • C programmers take note: The condition must be boolean • Danger: If the condition never becomes false, the loop never exits, and the program never stops

  20. Method calls • A method call is a request to an object to do something, or to compute a value • System.out.print(expression) is a method call; you are asking the System.out object to evaluate and display the expression • A method call may be used as a statement • Example: System.out.print(2 * pi * radius); • Some method calls return a value, and those may be used as part of an expression • Example: h = Math.sqrt(a * a + b * b);

  21. A complete program • public class SquareRoots {// Prints the square roots of numbers 1 to 10 public static void main(String args[]) { int n = 1; while (n <= 10) { System.out.println(n + " " + Math.sqrt(n)); n = n + 1; } }} • 1 1.02 1.41421356237309513 1.73205080756887724 2.05 2.23606797749979etc.

  22. Classes and Objects • A Java program consists of one or more classes • A class is an abstract description of objects • Here is an example class: • class Dog { ...description of a dog goes here... } • Here are some objects of that class:

  23. More Objects • Here is another example of a class: • class Window { ... } • Here are some examples of Windows:

  24. Example: a “Rabbit” object • You could create an object representing a rabbit • It would have data: • How hungry it is • How healthy it is • Where it is • And methods: • eat, run, dig, hide

  25. Objects have behaviors • In old style programming, you had: • data, which was completely passive • functions, which could manipulate any data • In O-O programming, an object contains both data and methods that manipulate that data • An object is active, not passive; it does things • An object is responsible for its own data • But it can expose that data to other objects

  26. Classes • A class describes a set of objects • The objects are called instances of the class • A class describes: • Fields that hold the data for each object • Constructors that tell how to create a new object of this class • Methods that describe the actions the object can perform • In addition, a class can have data and methods of its own (not part of the objects) • For example, it can keep a count of the number of objects it has created • Such data and methods are called static

  27. Defining a class • Here is the simplest syntax for defining a class: • class ClassName{// the fields (variables) of the object // the constructors for the object // the methods of the object} • You can put public, protected, or private before the word class • Things in a class can be in any order (I recommend the above order)

  28. Classes describe the data held by each of its objects Example: class Dog { String name; int age;...rest of the class...} A class may describe any number of objects Examples: "Fido", 3; "Rover", 5; "Spot", 3; A class may describe a single object, or even no objects at all Data usually goes first in a class Classes contain data definitions

  29. Defining fields • An object’s data is stored in fields (also calledinstance variables) • The fields describe the state of the object • Fields are defined with ordinary variable declarations: • String name;Double health;int age = 0;

  30. Objects have state • An object contains data • The data represent the state of the object • Data can also describe the relationship of the object to other objects • Example: a checkingAccount might have • A balance (the internal state of the account) • An owner (some object representing a person) • An accountNumber (used as an ID number)

  31. A class may contain methods that describe the behavior of objects Example: class Dog { ... void bark() { System.out.println("Woof!"); }} When we ask a particular Dog to bark, it says “Woof!” Only Dog objects can bark; the classDog cannot bark Methods usually go after the data Classes contain methods

  32. Methods • Primitives have operations, classes have methods • You cannot define new primitives, but you can define new classes • You cannot define new operations, but you can define new methods • Here we will talk about using methods supplied by Java, not defining new ones

  33. Methods contain statements • A statement causes the object to do something • (A better word would be “command”—but it isn’t) • Example: • System.out.println("Woof!"); • This causes the particular Dog to “print” (actually, display on the screen) the characters Woof!

  34. Methods may contain temporary data • Data described in a class exists in all objects of that class • Example: Every Dog has its own name and age • A method may contain local temporary data that exists only until the method finishes • Example: • void wakeTheNeighbors( ) { int i = 50; // i is a temporary variable while (i > 0) { bark( ); i = i – 1; }}

  35. Sending messages to objects • We don’t perform operations on objects, we “talk” to them • This is called sending a message to the object • A message looks like this: • object.method(extra information) • The object is the thing we are talking to • The method is a name of the action we want the object to take • The extra information is anything required by the method in order to do its job • Examples: g.setColor(Color.pink); amountOfRed = Color.pink.getRed( );

  36. Messages and methods • Messages can be used to: • Tell an object some information • Ask an object for information (usually about itself) • Tell an object to do something • Any and all combinations of the above • A method is something inside the object that responds to your messages • A message contains commands to do something • Java contains thousands of classes, each typically containing dozens of methods • When you program you use these classes and methods, and also define your own classes and methods

  37. (This part is the constructor) Classes always contain constructors • A constructor is a piece of code that “constructs,” or creates, a new object of that class • If you don’t write a constructor, Java defines one for you (behind the scenes) • You can write your own constructors • Example: • class Dog { String name; int age; Dog(String n, int age) { name = n; this.age = age; }}

  38. Defining constructors • A constructor is code to create an object • You can do other work in a constructor, but you shouldn’t • The syntax for a constructor is: • ClassName(parameters) {…code…} • The ClassName has to be the same as the class that the constructor occurs in • The parameters are a comma-separated list of variable declarations

  39. Parameters • We usually need to give information to constructors and to methods • A parameter is a variable used to hold the incoming information • A parameter must have a name and a type • You supply values for the parameters when you use the constructor or method • The parameter name is only meaningful within the constructor or method in which it occurs

  40. Program File File File Class Variables Constructors Variables File Methods Variables Diagram of program structure • A program consists of one or more classes • Typically, each class is in a separate .java file

  41. Summary • A program consists of one or more classes • A class is a description of a kind of object • In most cases, it is the objects that do the actual work • A class describes data, constructors, and methods • An object’s data is information about that object • An object’s methods describe how the object behaves • A constructor is used to create objects of the class • Methods (and constructors) may contain temporary data and statements (commands)

  42. Writing and running programs • When you write a program, you are writing classes and all the things that go into classes • Your program typically contains commands to create objects (that is, “calls” to constructors) • Analogy: A class is like a cookie cutter, objects are like cookies. • When you run a program, it creates objects, and those objects interact with one another and do whatever they do to cause something to happen • Analogy:Writing a program is like writing the rules to a game; running a program is like actually playing the game • You never know how well the rules are going to work until you try them out

  43. Getting started • Question: Where do objects come from? • Answer: They are created by other objects. • Question: Where does the first object come from? • Answer: Programs have a special main method, not part of any object, that is executed in order to get things started • The main method is defined in a class, but it belongs to the class itself, not to any specific objects of that class • The special keyword static says that the method belongs to the class, not to objects of the class • public static void main(String[ ] args) { Dog fido = new Dog("Fido", 5); // creates a Dog}

  44. class Dog { String name; int age; Dog(String n, int age) { name = n; this.age = age; } void bark() { System.out.println("Woof!"); } void wakeTheNeighbors( ) { int i = 50; while (i > 0) { bark( ); i = i – 1; }}public static void main(String[ ] args) { Dog fido = new Dog("Fido", 5); fido.wakeTheNeighbors();} } // ends the class A complete program using a class

  45. null • If you declare a variable to have a given object type, for example, • Person john; • String name; • ...and if you have not yet assigned a value to it, for example, with • john = new Person();String name = “John Smith"; • ...then the value of the variable is null • null is a legal value, but there isn’t much you can do with it • It’s an error to refer to its fields, because it has none • It’s an error to send a message to it, because it has no methods • The error you will see is NullPointerException

  46. String • A String is an object, but... • ...because Strings are used so much, Java gives them some special syntax • There are String literals:"This is a String" • (Almost) no other objects have literals • There is an operation,concatenation, on Strings: • "Dave" + "Matuszek" gives "DaveMatuszek" • In other respects,Strings are just objects

  47. String methods • A String, is immutable • Once you create it, there are no methods to change it • But you can easily make new Strings: • myName = "Dave";myName = "Dr. " + myName; • This is kind of a subtle point; it will be important later, but you don’t need to understand it right away • Ifsis the name of the string"Hello", then • s.length()tells you the number of characters in String s (returns 5) • s.toUpperCase() returns the new String "HELLO"(sitself is not changed) • But you can say s = s.toUpperCase();

  48. String concatenation • + usually means “add,” but if either operand (thing involved in the operation) is a String, then + means concatenation • If you concatenate anything with a String, that thing is first turned into a String • For example, you can concatenate a String and a number: • System.out.println("The price is $" + price); • + as the concatenation operator is an exception to the rule: Primitives have operations, Objects have methods

  49. String concatenation • Be careful, because + also still means addition • int x = 3;int y = 5;System.out.println(x + y + " != " + x + y); • The above prints 8 != 35 • “Addition” is done left to right--use parentheses to change the order

  50. Printing out results, part 1 • In Java, “print” really means “display on the screen” • Actually printing on paper is much harder! • System is one of Java’s built-in classes • System.out is a data object in the System class that knows how to “print” to your screen • We can “talk to” (send messages to) this mysterious object without knowing very much about it

More Related