1 / 76

Java basics

Java basics. Chapter 2 Slides still stolen (and in a very exciting format!) Trey Kirk. DisplayForecast.java. // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point

munin
Download Presentation

Java basics

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. Java basics Chapter 2 Slides still stolen (and in a very exciting format!) Trey Kirk

  2. DisplayForecast.java // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } Three comments A class like a method must have a name Three statements make up the action of method main() Method main() is part of class DisplayForecast A class like a method must have a name A class defines an object form. An object can have methods and attributes Keyword class indicates a class definition follows We will discuss static and void later Java allows a statement to be made up of multiple lines of text Semicolons delimit one statement from the next // indicates rest of the line is a comment Comments are used to document authors, purpose, and program elements public, static, and void are keywords. They cannot be used as names public means the method is shareable Programs are read by people – make sure they are readable. Use whitespace, comments, and indentation to aidunderstanding A method is a named piece of code that performs some action or implements a behavior An application program is required to have a public static void method named main().

  3. Indentation // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } Method main() is part of DisplayForecast Statements are part of method main() Indentation indicates subcomponents

  4. Good whitespacing // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } Whitespace Whitespace separates program elements Whitespace between program elements is ignored by Java

  5. Bad whitespacing • The same program without any whitespacing or comments: public class DisplayForecast2 { public static void main (String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } }

  6. Identifiers • Identifiers are names for variables, classes, etc. • Good ones are compact, but inidicate what they stand for • radius, width, height, length • Bad ones are either too long • theRadiusOfTheCircle • theWidthOfTheBoxThatIsBeingUsed • the_width_of_the_box_that_is_being_used • Or too short • a, b, c, d, e • Good identifiers will help the graders understand your program!

  7. Keywords • Some words are reserved, and can’t be used as identifiers // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } } // Authors: J. P. Cohoon and J. W. Davidson // Purpose: display a quotation in a console window public class DisplayForecast { // method main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world market for"); System.out.println(" maybe five computers."); System.out.println(" Thomas Watson, IBM, 1943."); } }

  8. Capitalization • Case matters! • public ≠ Public ≠ PUBLIC • This is different than FORTRAN and BASIC • This is the same as C/C++ • You can use Public as a identifier • Not recommended, though!

  9. Statements • A statement in Java is (usually) a single line • Example: System.out.println (“Hello world!”); • All statements must end with a semi-colon • That tells Java that the statement is finished

  10. A bit of humor:1989 ComputerAdvertisement Guess the price!

  11. Variables

  12. 5 x Defining variables • We’ve seen variables before in math • y = mx + b • Here y, m, x, and b can hold any value • To store things in a computer program, we also use variables • Example: • int x = 5; • Visualization: • This defines an integer variable with value 5 • The variable is x • The type is int

  13. 4.3 d More on variables • An integer variable can only hold integers • In other words, it can’t hold 4.3 • To hold floating point values, we use the double type • double d = 4.3; • The variable is d • The type is double

  14. Primitive variable assignment • Assignment operator = • Allows the variable to be updated • Consider int j = 11; j = 1985; • Assignment operator = • Allows the memory location for a variable to be updated • Consider int j = 11; j = 1985;

  15. Primitive variable assignment • Consider int a = 1; int aSquared = a * a; a = 5; aSquared = a * a; • Consider int i = 0; i = i + 1; • Consider int asaRating; asaRating = 400; int a = 1; int aSquared = a * a; a = 5; aSquared = a * a; int i = 0; i = i + 1; int asaRating; asaRating = 400;

  16. Primitive variable assignment • Consider double x = 5.12; double y = 19.28; double rememberX = x; x = y; y = rememberX; • Consider double x = 5.12; double y = 19.28; double rememberX = x; x = y; y = rememberX; • Consider double x = 5.12; double y = 19.28; double rememberX = x; x = y; y = rememberX; • Consider double x = 5.12; double y = 19.28; double rememberX = x; x = y; y = rememberX; • Consider double x = 5.12; double y = 19.28; double rememberX = x; x = y; y = rememberX; • Consider double x = 5.12; double y = 19.28; double rememberX = x; x = y; y = rememberX;

  17. Printing variables • To print a variable to the screen, put it in a System.out.println() statement: • int x = 5; • System.out.println (“The value of x is “ + x); • Important points: • Strings are enclosed in double quotes • If there are multiple parts to be printed, they are separated by a plus sign

  18. public class SolvingABC { public static void main(String[] args) { // variable definitions and initializations int a = 3; int b = 12; int c = 6; int d = 1; // calculate results double result1 = d * a; double result2 = c + 2 * a; double result3 = d - b / c; double result4 = c * b % c; double result5 = b / 2; // display the results System.out.println(); System.out.println("result1 : " + result1); System.out.println("result2 : " + result2); System.out.println("result3 : " + result3); System.out.println("result4 : " + result4); System.out.println("result5 : " + result5); System.out.println(); } } From this week’s lab Note that I don’t show a lot of comments so that the code will fit on a single slide Also note all the semi-colons

  19. Variable initialization • Note that the following • int x; • x = 5; • is (mostly) the same as the following: • int x = 5;

  20. You can only declare variables once • The following code will not work: • int x = 5; • int x = 6; • Java can have only one variable named x • So you can’t declare multiple variables with the same name • (we’ll see ways around this later in the semester)

  21. Today’s demotivators

  22. Types

  23. Primitive variable types • Java has 8 (or so) primitive types: • float • double • boolean • char • byte • short • int • long real numbers two values: true and false a single character integer numbers • Also the void “type”, which we will see later • We’ll only be using half of the types in this course: int, double, boolean, and char

  24. Primitive real (floating-point) types • A float takes up 4 bytes of space • Has 6 decimal places of accuracy: 3.14159 • A double takes up 8 bytes of space • Has 15 decimal places of accuracy: 3.14159265358979 • Always use doubles • It will save you quite a headache!

  25. Primitive integer types • Consider a byte: • 1 byte = 8 bits • Each bit has two possibilities: 0 or 1 • 28 = 256 • Thus, a byte can have any one of 256 values • A Java byte can have values from -128 to 127 • From -27 to 27-1 • C/C++ has unsigned versions; Java does not

  26. Primitive integer types

  27. Increment and decrement operators • ++ • Increments a number variable by 1 • -- • Decrements a numeric variable by 1 • Consider int i = 4; // define ++i; System.out.println(i); System.out.print(++i); System.out.println(i++); System.out.println(i); • ++ • Increments a number variable by 1 • -- • Decrements a numeric variable by 1 • Consider int i = 4; ++i; // increment System.out.println(i); System.out.print(++i); System.out.println(i++); System.out.println(i); • ++ • Increments a number variable by 1 • -- • Decrements a numeric variable by 1 • Consider int i = 4; ++i; System.out.println(i); // display System.out.print(++i); System.out.println(i++); System.out.println(i); • ++ • Increments a number variable by 1 • -- • Decrements a numeric variable by 1 • Consider int i = 4; ++i; System.out.println(i); System.out.print(++i); // update then display System.out.println(i++); System.out.println(i); • ++ • Increments a number variable by 1 • -- • Decrements a numeric variable by 1 • Consider int i = 4; ++i; System.out.println(i); System.out.print(++i); System.out.println(i++); // display then update System.out.println(i); • ++ • Increments a number variable by 1 • -- • Decrements a numeric variable by 1 • Consider int i = 4; ++i; System.out.println(i); System.out.print(++i); System.out.println(i++); System.out.println(i); // display • ++ • Increments a number variable by 1 • -- • Decrements a numeric variable by 1 • Consider int i = 4; ++i; System.out.println(i); System.out.print(++i); System.out.println(i++); System.out.println(i);

  28. Why C++ was named C++ • The increment operator adds one to the integer value • Or makes it ‘one better’ • So when Bjarne Stroustrup was making the successor to C, he was making a ‘one better’ language

  29. Primitive character type • All characters have a integer equivalent • ‘0’ = 48 • ‘1’ = 49 • ‘A’ = 65 • ‘a’ = 97 • Thus, you can refer to ‘B’ as ‘A’+1

  30. Primitive boolean type • The boolean type has only two values: • true • false • There are boolean-specific operators • && is and • || is or • ! is not • etc. • We’ll see those operators in a few slides

  31. Variables must be declared before use • The following code will not work: • x = 5; • System.out.println (x); • Java requires you to declare x before you use it

  32. Variable initialization • Consider the following code: int x; System.out.println(x); • What happens? • Error message: • variable x might not have been initialized • Java also requires you to give x a value before you use it

  33. Constants • Consider the following: final int x = 5; • The value of x can NEVER be changed! • The value assigned to it is “final” • This is how Java defines constants • Constants have a specific naming scheme • MILES_PER_KILOMETER • All caps, with underscores for spaces

  34. Expressions • What is the value used to initialize expression int expression = 4 + 2 * 5; • What value is displayed System.out.println(5 / 2.0); • Java rules in a nutshell • Each operator has a precedence level and an associativity • Operators with higher precedence are done first • * and / have higher precedence than + and - • When floating-point is used the result is floating point

  35. Question on expressions • Does the following statement compute the average of double variables a, b, and c? Why or why not? double average = a + b + c / 3.0;

  36. Java operators • The following are the common operators for ints: • + - / * % • Division is integer division • 6 / 2 yields 3 • 7 / 2 yields 3, not 3.5 • Because everything is an int, the answer is an int • Modulus is % • Returns the remainder • 7 % 2 yields 1 • 6 % 2 yields 0 • Floats and doubles use the same first four operators • + - / * • 7.0 / 2.0 yields 3.5 • 7.0 / 2 yields 3.5 • 7 / 2.0 yields 3.5 • 7 / 2 yields 3

  37. Java operators • Booleans have their own operators • && is AND • Only true when both operands are true • true && true yields true • false && true yields false • || is OR • True when either of the operands (or both) are true • true || false yields true • false || false yields false • ! is NOT • Changes the value • !true yields false • !false yields true

  38. New York Drivers

  39. System.out.println • Can print multiple things by using the + operator • Let int i = 7; • Example: System.out.println (“i = “ + i); • Prints i = 7 • Can also have the statement on multiple lines System.out.println ( “hello world!” ) ; • But can’t have the String on multiple lines System.out.println ( “hello world!” );

  40. System.out.println • System.out.println (“result: “ + 3/5); • What does it print? • result: 0 • System.out.println (“result: “ + 5 % 3); • What does it print? • result: 2 • System.out.println (“result: “ + 3/5.0); • What does it print? • result: 0.6 • System.out.println (“result: “ + 3+4.0); • What does it print? • result: 34.0 • System.out.println (“result: “ + (3+4.0)); • What does it print? • result: 7.0

  41. Scanner usage

  42. Interactive programs • Programs that interact with their users through statements performing input and output

  43. Reading in a value from the keyboard • We will see this in more detail later in this slide set • For now (and for lab 2), this is what you need to know • To read in values from the keyboard, you first have to create a Scanner object • Don’t worry about what an object is, what a Scanner is, or about creation of these things • We’ll get to them later • To do this, use the following code: Scanner stdin = new Scanner (System.in);

  44. Reading in more values from the keyboard • You should have this only once in your program. • From then on, when you want to read in a value into a variable, use the following: int x = stdin.nextInt(); double d = stdin.nextDouble(); • Or x = stdin.nextInt(); d = stdin.nextDouble();

  45. Scanner usage example import java.util.*; public class ScannerUsage { public static void main (String args[]) { Scanner stdin = new Scanner (System.in); System.out.println ("Enter first value"); int x = stdin.nextInt(); int y; System.out.println ("Enter second value"); y = stdin.nextInt(); int z = x + y; System.out.println ("The sum of " + x + " and " + y + " is " + z); } }

  46. Program demo… • ScannerUsage.java • Note that all this code is available on the website!

  47. How to make Java work with the Scanner class • In Java 1.5, do a:import java.util.*; • To create a new Scanner:Scanner stdin = new Scanner (System.in);

  48. Today’s demotivators

  49. Program Examples

  50. Example program: temperature conversion // Purpose: Convert a Celsius temperature to Fahrenheit public class CelsiusToFahrenheit { // main(): application entry point public static void main(String[] args) { // set Celsius temperature of interest int celsius = 28; // convert to Fahrenheit equivalent int fahrenheit = 32 + ((9 * celsius) / 5); // display result System.out.println("Celsius temperature"); System.out.println(" " + celsius); System.out.println("equals Fahrenheit temperature"); System.out.println(" " + fahrenheit); } }

More Related