Presentation is loading. Please wait.

Presentation is loading. Please wait.

Http://java.oracle.com Introduction to Java.

Similar presentations


Presentation on theme: "Http://java.oracle.com Introduction to Java."— Presentation transcript:

1 Introduction to Java

2 A Brief History Originally released in 1995 by Sun Microsystems (now a subsidiary of Oracle) Designed to write programs for “embedded devices,” specifically TVs As such, Java is designed for small, lightweight programs Turns out, this makes it ideal for writing programs for the internet as well

3 Key Characteristics “Write-once, run anywhere”
Java programs are compiled to bytecode rather than machine code The bytecode can be executed by any Java VM on any computer Similar to C# Automatic memory management Java tracks what memory is currently in use and reclaims memory that is no longer needed Other languages (such as C/C++) require the developer to track this themselves Object-oriented

4 Writing Java Programs Java has many, many predefined classes and objects that provide common behavior System.out from our program is one example This prevents Java developers from having to constantly “reinvent the wheel” These classes and objects (collectively referred to as the “Java API”) are documented on the Java website: Bookmark this page– it will be your lifeline

5 Actually Writing Java Programs
We could just use notepad (or any other text editor) and command-line tools javac (compiler) and java (vm) This is very simple and lightweight, but has a lot of drawbacks Very little confirmation we’re doing things right Introduces multiple potential points of failure

6 Using Eclipse Instead, we’ll use an Integrated Development Environment (IDE) called Eclipse Available for download from You want “Eclipse IDE for Java Developers” IDEs combine all the tools we need into one centralized, integrated environment (hence the name) Most IDEs (including Eclipse) also provide a bunch of other useful features

7 Eclipse Walkthrough

8 Exercise Create Hello World program.
Outputs “Hello world. My name is <your name>.”

9 Actually Writing Java Programs
Writing and running programs requires a number of tools: An editor to write and edit the code We will use eclipse A compiler to translate the program from Java code to Java bytecode A virtual machine or runtime to translate the bytecode to machine code, which the computer can execute A debugger to help track down and fix problems We will primarily use print statements to track and debug programs.

10 Actually Writing Java Programs
Edit Compile Run Debug

11 Actually Writing Java Programs
Edit Compile Run Debug Java Bytecode Java VM Machine Code

12 Actually Writing Java Programs
Edit Compile Run Debug Java VM Machine Code Execute Java Bytecode

13 Your First Java program
public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); System.out.println(); System.out.println("This program produces"); System.out.println("four lines of output"); } Its output: Hello, world! This program produces four lines of output console: Text box into which the program's output is printed.

14 Your First Java program
class: a program public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); System.out.println(); System.out.println("This program produces"); System.out.println("four lines of output"); } Every executable Java program consists of a class, that contains a method named main, that contains the statements (commands) to be executed. method: a named group of statements statement: a command to be executed

15 System.out.println A statement that prints a line of output on the console. pronounced "print-linn" sometimes called a "println statement" for short Two ways to use System.out.println : System.out.println("text"); Prints the given message as output. System.out.println(); Prints a blank line of output.

16 Documentation Documentation refers to elements of code that help a reader understand what’s going on Comments are the primary, but not the only, form of documentation Two types of comments in Java: Single-line comments: // this is a single-line comment Multi-line (or C-style) comments: /* this is a multi-line comment */ Comments are ignored when compiling and executing code

17 Review What is the name of the statement that prints a line of output on the console? System.out.println What is Eclipse? An IDE that combines all the tools we need into one centralized, integrated environment In the program below, public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); System.out.println(); System.out.println("This program produces"); System.out.println("four lines of output"); } What is the name of the program? What is the name of a method? What is one statement in this program?

18 Documentation Use comments frequently to:
Describe the basic, high-level behavior of a chunk of code Explain anything potentially unclear or tricky Explain why you chose to do something a certain way if there were multiple options Etc. You should also make your code self-documenting by: Choosing descriptive, readable names Using line breaks Indenting/aligning things well Readability of you code is important. For clarity and understanding especially on debugging You will be graded on the readability of your code.

19 Bugs A bug is anything that goes wrong with a program
Debugging is the act of going through code and fixing bugs In industry, software engineers usually spend more time debugging code than they did writing it (sometimes orders of magnitude more)

20 Bugs Eclipse helps you find some bugs:
Notice the red squiggly and red x Hovering over the x tells you what’s wrong When you try to compile, you also get an error:

21 Bugs Bugs that can be detected like this are called compile-time errors These are usually relatively simple to find and fix Bugs that don’t show up until you try to execute the program are called run-time errors Run-time errors are generally much trickier to deal with

22 ALL PROGRAMS HAVE BUGS, AND YOURS WILL TOO!
Important takeaway: ALL PROGRAMS HAVE BUGS, AND YOURS WILL TOO! Don’t be discouraged when things don’t work right away Keep working at it, and try to see what the code really does, not what you think it does We’ll talk more about debugging and testing later

23 Names and identifiers You must give your program a name.
public class ComputerScience { Naming convention: capitalize each word (e.g. MyClassName) Your program's file must match exactly (ComputerScience.java) includes capitalization (Java is "case-sensitive") identifier: A name given to an item in your program. must start with a letter or _ or $ subsequent characters can be any of those or a number legal: _myName TheCure ANSWER_IS_42 $bling$ illegal: me+u ers side-swipe Ph.D's

24 Identifiers continued
Identifiers should be descriptive, but not unwieldy Bad: x (non-descriptive), myVariableThatIsUsedToCountSomething (too long) Good: count, numTries, xCoordinate Java has certain conventions for identifiers Identifiers are always a single word (no spaces) Class names should start with an uppercase letter, and use an uppercase letter to indicate word breaks e.g. String, PrintStream, MixedFraction This is called Pascal casing Variables/methods/etc. should start with a lowercase letter, and be cased similarly e.g. size, numLoops, firstName This called Camel casing

25 Keywords keyword: An identifier that you cannot use because it already has a reserved meaning in Java. abstract default if private this boolean do implements protected throw break double import public throws byte else instanceof return transient case extends int short try catch final interface static void char finally long strictfp volatile class float native super while const for new switch continue goto package synchronized

26 Strings A sequence of characters is called a string
Strings are usually, but not exclusively, used for input and output Strings in Java are enclosed in double-quotes (“string”) Identify the string in System.out.println(“Welcome to Java!”); String is an example of a pre-defined Java class

27 Escape sequences escape sequence: A special sequence of characters used to represent certain special characters in a string. \t tab character \n new line character \" quotation mark character \\ backslash character Example: System.out.println("\\hello\nhow\tare \"you\"?\\\\"); Output: \hello how are "you"?\\

28 Review What kind of bugs don’t show up until you try to execute the program? Run-time bugs What is an identifier? A name given to an item in your program What kind of casing you should use for classes? Class names should start with an uppercase letter, and use an uppercase letter to indicate word breaks e.g. String, PrintStream, MixedFraction This is called Pascal casing What is a keyword? An identifier that you cannot use because it already has a reserved meaning in Java In Java, how do you specify a string? Strings in Java are enclosed in double-quotes (“string”)

29 Exercise Chapter 1 Exercises 1-5

30 Review What is the name of the method that all Java applications must have? main What is an identifier? A name given to an item in your program What kind of casing you should use for classes? Class names should start with an uppercase letter, and use an uppercase letter to indicate word breaks e.g. String, PrintStream, MixedFraction This is called Pascal casing What is a keyword? An identifier that you cannot use because it already has a reserved meaning in Java In Java, what is the escape sequence for a ‘\’ character? \\

31 Static methods

32 Algorithms algorithm: A list of steps for solving a problem.
Example algorithm: "Bake sugar cookies" Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. Set the oven temperature. Set the timer. Place the cookies into the oven. Allow the cookies to bake. Spread frosting and sprinkles onto the cookies. ...

33 Problems with algorithms
lack of structure: Many tiny steps; tough to remember. redundancy: Consider making a double batch... Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. Set the oven temperature. Set the timer. Place the first batch of cookies into the oven. Allow the cookies to bake. Place the second batch of cookies into the oven. Mix ingredients for frosting. ...

34 Structured algorithms
structured algorithm: Split into coherent tasks. 1 Make the cookie batter. Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. 2 Bake the cookies. Set the oven temperature. Set the timer. Place the cookies into the oven. Allow the cookies to bake. 3 Add frosting and sprinkles. Mix the ingredients for the frosting. Spread frosting and sprinkles onto the cookies. ...

35 Removing redundancy A well-structured algorithm can describe repeated tasks with less redundancy. 1 Make the cookie batter. Mix the dry ingredients. ... 2a Bake the cookies (first batch). Set the oven temperature. Set the timer. 2b Bake the cookies (second batch). 3 Decorate the cookies.

36 Using static methods 1. Design the algorithm.
Look at the structure, and which commands are repeated. Decide what are the important overall tasks. 2. Declare (write down) the methods. Arrange statements into groups and give each group a name. 3. Call (run) the methods. The program's main method executes the other methods to perform the overall task.

37 A program with redundancy
public class BakeCookies { public static void main(String[] args) { System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); System.out.println("Set the oven temperature."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles."); }

38 Static methods static method: A named group of statements.
denotes the structure of a program eliminates redundancy by code reuse procedural decomposition: dividing a problem into methods Writing a static method is like adding a new command to Java. What is a statement? statement: a command to be executed class method A statement method B method C

39 Gives your method a name so it can be executed
Declaring a method Gives your method a name so it can be executed Syntax: public static void name() { statement; statement; statement; } Example: public static void printWarning() { System.out.println("This product causes cancer"); System.out.println("in lab rats and humans."); }

40 Design of an algorithm // This program displays a delicious recipe for baking cookies. public class BakeCookies2 { public static void main(String[] args) { // Step 1: Make the cake batter. System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); // Step 2a: Bake cookies (first batch). System.out.println("Set the oven temperature."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); // Step 2b: Bake cookies (second batch). // Step 3: Decorate the cookies. System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles."); }

41 Executes the method's code
Calling a method Executes the method's code Syntax: name(); You can call the same method many times if you like. Example: printWarning(); Output: This product causes cancer in lab rats and humans.

42 Program with static method
public class Macklemore{ public static void main(String[] args) { rap(); // Calling (running) the rap method System.out.println(); rap(); // Calling the rap method again } // This method prints the lyrics to Can’t Hold Us. public static void rap() { System.out.println("So we put our hands up like the ceiling can't hold us. "); System.out.println("Like the ceiling can't hold us"); Output: So we put our hands up like the ceiling can't hold us. Like the ceiling can't hold us

43 Final cookie program // This program displays a delicious recipe for baking cookies. public class BakeCookies3 { public static void main(String[] args) { makeBatter(); bake(); // 1st batch bake(); // 2nd batch decorate(); } // Step 1: Make the cake batter. public static void makeBatter() { System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); // Step 2: Bake a batch of cookies. public static void bake() { System.out.println("Set the oven temperature."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); // Step 3: Decorate the cookies. public static void decorate() { System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles.");

44 Demo: Methods calling methods
public class MethodsExample { public static void main(String[] args) { message1(); message2(); System.out.println("Done with main."); } public static void message1() { System.out.println("This is message1."); public static void message2() { System.out.println("This is message2."); System.out.println("Done with message2."); Output: This is message1. This is message2. Done with message2. Done with main.

45 Control flow When a method is called, the program's execution...
"jumps" into that method, executing its statements, then "jumps" back to the point where the method was called. public class MethodsExample { public static void main(String[] args) { message1(); message2(); System.out.println("Done with main."); } ... public static void message1() { System.out.println("This is message1."); } public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with message2."); } public static void message1() { System.out.println("This is message1."); }

46 When to use methods Place statements into a static method if:
The statements are related structurally, and/or The statements are repeated. You should not create static methods for: An individual println statement. Only blank lines. (Put blank printlns in main.) Unrelated or weakly related statements. (Consider splitting them into two smaller methods.)

47 Review What is a static method? What is an algorithm?
A named group of statements What is an algorithm? A list of steps for solving a problem.

48 Exercise Write a Java program called TwoRockets that generates the following output. Use Static methods to show structure and eliminate redundancy in your solution. Note that there are two rocket ships next to each other. What redundancy can you eliminate using static methods? What redundancy can be eliminated? /\ /\ / \ / \ / \ / \ | | | | |United| |United| |States | |States | | | | | /\ /\ / \ / \ / \ / \ If they get done, Finish Homework Exercises Do the Binary Self-Check exercies (1-3)

49 Unit 1 Review Java programs Identifiers Method String Documentation

50 Your First Java program
class: a program public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); System.out.println(); System.out.println("This program produces"); System.out.println("four lines of output"); } Every executable Java program consists of a class, that contains a method named main, that contains the statements (commands) to be executed. method: a named group of statements statement: a command to be executed

51 Identifiers The names of classes, methods, variables, etc. are referred to as identifiers Identifiers can consist of letters, digits, underscores (_), or $ The first character cannot be a digit Identifiers should be descriptive, but not unwieldy Bad: x (non-descriptive), myVariableThatIsUsedToCountSomething (too long) Good: count, numTries, xCoordinate

52 Identifiers Java has certain conventions for identifiers
Identifiers are always … a single word (no spaces) Class names should start with … an uppercase letter, and use an uppercase letter to indicate word breaks e.g. String, PrintStream, MixedFraction This is called Pascal casing Variables/methods/etc. should start with a … lowercase letter, and be cased similarly e.g. size, numLoops, firstName

53 Keywords keyword: An identifier that you cannot use because it already has a reserved meaning in Java. abstract default if private this boolean do implements protected throw break double import public throws byte else instanceof return transient case extends int short try catch final interface static void char finally long strictfp volatile class float native super while const for new switch continue goto package synchronized

54 Methods A method is a defined behavior of a particular class
Passing a message in Java is referred to as calling (or invoking) a method Method calls have the following parts: The target or receiver of the message is the object whose behavior we want to trigger The method name of the method we want to call If necessary, some number of arguments Arguments provide additional information needed by the method

55 Anatomy of a Method Call
System.out.println(“Welcome to Java!”); Target or Receiver Argument Method Name

56 Documentation Use comments frequently to:
Describe the basic, high-level behavior of a chunk of code Explain anything potentially unclear or tricky Explain why you chose to do something a certain way if there were multiple options Etc. You should also make your code self-documenting by: Choosing descriptive, readable names Using line breaks Indenting/aligning things well Readability of you code is important. For clarity and understanding especially on debugging You will be graded on the readability of your code.


Download ppt "Http://java.oracle.com Introduction to Java."

Similar presentations


Ads by Google