Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Beginning JAVA (Final)

Vina
July 12, 2018
37

Beginning JAVA (Final)

Vina

July 12, 2018
Tweet

Transcript

  1. What is Java u Is an object oriented programing language

    u Developed by Sun Microsystems which is now owned Oracle now since 2010 u Modeled after C++ an older programing language
  2. What is Java cont. u It was developed as part

    of a research project to develop software for electronic devices like TV, VCRS, toasters, etc u Also wanted a programming language that was small, fast, efficient, and portable to a range of hardware devices
  3. Applet u An interactive program that can run instead a

    web page u You write it in java language, compile using a Java compiler, and then insert it to an applet file in HTML (web page language)
  4. Compiled vs. Interpreted u A compiler figures out everything a

    program will do, turns it into “machine code” (a format the computer can run really fast), then saves that to be executed later. u An interpreter steps through the source code line by line, figuring out what it’s doing as it goes. u Technically any language could be compiled or interpreted, but one or the other usually makes more sense for a specific language. Generally, interpreting tends to be more flexible, while compiling tends to have higher performance.
  5. Compiled and Interpreted u Java has a Java compiler and

    Java interpreter. u Compiler takes Java program and generate bytecodes from it u Bytecodes are set of instruction processed by a program called the virtual machine, rather than the “real” computer u Processor is the circuit in a computer that processes the basic instructions and make the computer work u Java interpreter translate .class file (contains java bytecodes) into a code (raw machine language code) that works on your computer
  6. Object-Oriented u Java is Object Oriented u Object oriented programing

    is a type of technique to organize programs by objects or a.k.a data u Rather than by actions or functions
  7. If you want to try java on your computer u

    You should download Java onto your computer (most likely already has it) u A program to compile your code u Eclipse (advance) u Notepad++ (PC) u BlueJ
  8. First Java application Public class HelloWorld { public static void

    main (String args [] ) { System.out.println(“Hello World!”) ; } }
  9. Public class HelloWorld { public static void main (String args

    [] ) { System.out.println(“Hello World!”) ; } } TWO MAIN PARTS: - PROGRAM IS ENCLOSED IN A CLASS DEFINITION (HELLOWORLD) - THE BODY OF THE PROGRAM IS CONTAINED IN A ROUTINE CALLED MAIN() - MAIN() IS THE FIRST THING THAT RUNS WHEN A PROGRAM EXECUTES
  10. Syntax cont u Still have strings in “ “ u

    After every method/function, you must end with ; a semicolon u Use { } u Indentation is not important, it’s only for making your code neat u To print, you need to type out u System.out.println( “ “ ); u For variables, it’s the same but you need to declare the variable type u Ex, string phrase = “hello world”; u int number = 4;
  11. Errors u You still get Syntax errors like you would

    in Python u Run time error or logic error is when syntax is correct but the program does something it isn’t supposed to do u You made an logic error u like misspelling in a string, a wrong math formula, etc
  12. Algorithm Concepts u A sequence of steps for solving a

    problem u MUST BE: u Unambiguous : Precise instructions for what to do at each step and where to go next. No guess work. u Executable : It can be carried out, no syntax errors and etc u Terminating : the sequence of steps must eventually come to a stop u if it doesn’t your program will continue to run forever and forever and it most likely will break your program/computer u Will usually show up as an error
  13. Comments u In python it was # u In Java,

    you use // (double slashes) u Or /* and */ // this is a comment for only one line /* this is also a comment but I can write multiple lines of comments */
  14. Objects u Like lego building blocks of code u Objects

    are made up of many kinds of smaller object u Is an instance of a class u Objects have state and behaviors u Example: dogs has states: color, name, breed, and behaviors like barking, eating, and etc
  15. Class u A template or blueprint that describes the behavior

    and state of an object u Embody all the features of a particular set of objects u When you write a program in object-orientated language, you don’t define the objects. You define the classes of objects
  16. Constructors u VERY VERY VERY IMPORTANT. ALSO VERY CONFUSING (and

    that’s okay if you don’t 100% understand them now) u Every class has a constructor u If you don’t create one yourself, Java will make a default one for you that may not be correct or not u Each time a new object is created, one constructor will be made and used. u Can have more than one constructor for one class u Rule: constructors have the same name as the class.
  17. Methods u In a class, you have methods that you

    write and make u Methods are similar to functions u Java has some premade functions like print
  18. Variables u Classes can contain 3 of these variable types

    u Local variable u Instance variables u Class variables
  19. Local Variable u Variables defined inside a method u Made

    in the method and then destroyed with the method/function is finished
  20. Instance Variables u Variables that within the class but not

    in any particular method/function u They can be reused by any method, will not be destroyed u Can be changed by methods
  21. How to name variables, methods, classes u Must start with

    a letter, or underscore, u No starting with numbers u No other symbols other than underscore u CASE SENSITIVE u milespergallon and milesPerGallon are two different variables u Never start with a capital letter for variables u Don’t use Java reserved worlds like class, double, and etc (you’ll learn more soon)
  22. Correct or incorrect? u distance_1 u x u CanVolume u

    6pack u can volume u milesPurGalleon
  23. Methods u We learned methods before (in Python we called

    them functions) u Methods often require values that give them details about the work that the methods need to do u Like Println method, you must supply the string or value to be printed u Argument is the value that is supplied in a method call u System.out.println(“greetings”)
  24. Return Values u There are some methods compute and return

    a value u Ex. length method returns a value string greeting = “Hello”; int numberOfCharacters = greeting.length(); System.out.println(numberOfCharacters);
  25. ( ) u So yes, most methods you seen has

    the () u Reminder, you usually put arguments or parameters in () u Or the code will give you something (return a value) that you might need to store in a variable if you want to save it
  26. Boolean u Stores true or false u boolean value =

    true ; u boolean bob = false;
  27. Order of Operations - Basic Math - PEMDAS - Parentheses

    first, exponents, multiply, divide, add, subtract
  28. Modulo % u Gives you the remainder Activity: Finish the

    code so that will print out the remainder of 2 public class Modulo { public static void main(String[] args) { int myRemainder = System.out.println(myRemainder); } }
  29. Relational Operators u Relational operators compare data types (like numbers)

    u < Less than u <= less than or equal to u > greater than, u >= greater than or equal to
  30. Equality operators u == is equal to u != is

    not equal to public class EqualityOperators { public static void main(String[] args) { int myInt = -1; double myDouble = -1.0; System.out.println(myInt == myDouble); } }
  31. && and || or (boolean operators) u && means and

    u Returns true only if both sides of the equation are true u System.out.println ( true && false ); u || means or u Returns true if at least one expression is true u System.out.println ( true || false);
  32. ! u Means not u !true = false u !false

    = true u != u ! <= u etc
  33. Precedence u public class Precedence { public static void main(String[]

    args) { boolean riddle = ??( 1 < 8 && (5 > 2 ??? 3 < 5)); System.out.println(riddle); } } You can order Boolean operators
  34. Answer public class Precedence { public static void main(String[] args)

    { boolean riddle = !( 1 < 8 && (5 > 2 || 3 < 5)); System.out.println(riddle); } }
  35. API Documentation u The classes and methods of the Java

    Library are listed in the API documentation u Application Programing Interface u If you need help finding a code or figuring out what a particular code does, you go there u You can also create your own methods (System programming) u Programmers who uses the already created standard Java classes are Application programmers
  36. Activity u http://docs.oracle.com/javase/8/docs/api/index.html. u Go to this website for the

    API documentation. See if you can figure out how to use some of the new code and methods you find
  37. Format u Click on a method, gives you the name

    u Description of what it does u The type and name of the parameter variables u The value that it returns
  38. Conditionals u If is the first part of a conditional

    expression u Followed by a Boolean expression and then a block of code u If Boolean expression is true, then block of code that folls will be run
  39. Example if (9 > 2) { System.out.println("Control flow rocks!"); }

    ______________________________________________ - No semicolon after if, need { }
  40. Try it out public class If { public static void

    main(String[] args) { if (???????????) { System.out.println("Access granted."); } } }
  41. If-Else Statement u So you only need If, if keyword

    is true u Sometimes we want to execute a different block of code when Boolean expression is false u That’s why we have else
  42. if (1 < 3 && 5 < 4) { System.out.println(“I

    defy Boolean laws!”); } else { System.out.println(“You can thank George Boole!”); }
  43. If / else if / else u Sometimes you just

    need more conditionals if (shoeSize > 12) Print “sorry, your shoe size is out of stock” else if (shoeSize >= 6) Print “you shoes size is in stock” else Print “We don’t carry sizes smaller than a size 6”
  44. Set int round = ????; so that else if runs

    int round; if (round > 12) System.out.println("The match is over!"); } else if (round > 0) { System.out.println("The match is underway!"); } else { System.out.println("The boxing match hasn't started yet."); }
  45. Switch Statements u Another type of conditionals u Switch statements

    keep code organized and less wordy u You don’t need to use them but useful (I don’t like them) u Switch u Case u Break
  46. Constructing Objects u You need to define the properties of

    objects with classes u Objects of type Rectangle describes rectangular shapes u Etc
  47. Unfortunately… u You can’t do this with the online Java

    compilers you guys are using, you would need the actually compiler program for this to work properly
  48. Activity Write a program as a class to create an

    image - snowman - dog - or etc.
  49. Class Syntax class Dog { } Created a class Dog

    and we will define the behavior of dog
  50. Constructors u A class constructor will allow us to create

    instances of Dog and set some information about the Dog u If you don’t create one, Java provides one for you class Dog { public Dog () { } }
  51. Instance Variables u Specific details about the class u Ex,

    we might want to describe the age of the Dog
  52. Methods u Pre-defined set of instruction u Teach you have

    to create a new method for the class you made
  53. Accessor and Mutators u An accessor method does not change

    the data of the object u A mutator method changes the data
  54. Which of these are Accessor and Mutator Methods? u .getWidth()

    u .getX() u .translate(12, 30) u .toUpperCase()
  55. Calling the method you made u In your same program

    you’ve been writing public static void main(String[] args) { Dog spike = new Dog(2); spike.bark(); }
  56. Creating Methods with parameters u Same thing as writing a

    method without one (like bark) u Except you have to write variable type and variable name in the ( ) public void run (int feet) --------------------------------------------- Spike.run(30);
  57. void u Note how the previous methods all had void

    in it u It means that the method returns no value u It’s performing another duty that does not require it to give you an answer
  58. Making a method that returns a value u It’s pretty

    much the same as methods that return nothing u Use data type keywords (String, int, char, and etc.) to specify what that method should return
  59. Method returning an int u In between the run and

    main method, add a method called getAge that returns the age of your dog
  60. Now in the main u Set an int variable spikeAge

    to a value returned by spike.getAge(); u Then print it out
  61. Inheritance u You can share or inherit behavior from one

    class to another u It’s so that we can reuse and maintain code more efficiently
  62. For example class Dog extends Animal { …. …. public

    static void main… { spike.checkStatus(); } }
  63. Review • - Class: a blueprint for how a data

    structure should function • - Constructor: instructs the class to set up the initial state of an object • - Object: instance of a class that stores the state of a class • - Method: set of instructions that can be called on an object • - Parameter: values that can be specified when creating an object or calling a method • - Return value: specifies the data type that a method will return after it runs • - Inheritance: allows one class to use functionality defined in another class
  64. Data Structure u They are much more advance topic in

    programming u Most professional code requires heavy use of different types of data structures u As long as you understand how data structure works, you’re in good shape
  65. Data Structures u It’s a particular way of storing and

    organizing data in a computer so that it can be used efficiently u The are the key to designing and programming efficient algorithms u All of these affects the quality of your program u Which affects your electronic products and user’s experiences with them
  66. In this class u We can’t go over all of

    them, but here are some: u Interfaces u List, Queue, Deque, etc. u Classes u ArrayList, Vector, LinkedList, HashSets, TreeSets, etc
  67. While Loop and For Loop u Loop Statements execute instructions

    repeatedly while a condition is true u Uses boolean expressions like if statements u So if true, loop continues u If false, loop stops or terminates
  68. While loops while (condition) { statements } int num =

    5; while (num < 10) { int equ= num + 2; num++; System.out.println(equ); }
  69. Variables inside a loop u When you declare a variable

    inside the loop body, the variable only exists for that iteration u As your code keeps going through different iteration, the variable is created again and again and then forgotten again and again
  70. u That means the variable equ is constantly being made

    and forgotten u This loop will keep printing as long as num < 10 u ++ is a short cut for +1 (adding 1 to the variable value) int num = 5; while (num < 10) { equ= num + 2; num++; System.out.println(equ); }
  71. Errors to look out for u Infinite loop: a loop

    that runs forever and can only be stopped by killing the program or restarting the computer. u You forgot to update the variable the controls the loop (in boolean expression) u Off by one error: You end the program maybe 1 times off after you wanted to. u Keep in mind when you want to us < or <=
  72. Pseudocode u Psuedocode is “fake” programming. You use english and

    diagrams to help you figure out what you need to write in real coding language. u When you’re having trouble writing a loop, always go back to pseudocode and hand trace the loop you want to write u Then go back to the programming language
  73. For Loops u For loops is used when a value

    runs from a starting point to an ending point with a constant increment or decrement. u In other words, it is controlled by a counter u There isn’t much difference between while and for loops except for loops are cleaner and neater to use
  74. What does this print? for (int counter =1 ; counter

    <= 10; counter++) { System.out.println(counter); }
  75. For loops cont. u Groups initialization, conditions, and update expressions

    together u Can count down instead of up u Instead of ++ you can use --
  76. i and j u So people use “ i ”

    and “ j “ more commonly to use as the counter variable u So they aren’t confused with x, y, z, or n which are common names for other number variables
  77. Common Loop Algorithms u Sum and average values u Counting

    and finding matches of number or strings (like ctrl F) u Maximum and Minimum (storing data of the largest or smallest numbers)
  78. Something fun… u Scanner class u Allow users to input

    info into the terminal (where code stuff is previewed like your print statements) https://bit.ly/2u3rOt2
  79. Array u An array collects a sequence of values of

    the same type u You could technically store 10 values into variables like this: value1, value2, value3, and etc… but that’s not practical
  80. Declaring Arrays u How to create an array that holds

    10 double (data type) double [] value = new double [10] u double[] values = we are creating the variable of the type array u [10] is the length of the array u new operator constructs the array
  81. Declaring Arrays cont. double [] moreValues = { 0, 3,

    5, 7, 9 }; u Here you can declare an array with specific variables
  82. How to access your array double [] value = new

    double [10] u So your array hold elements of the type double here u Position number of the elements (or index number) starts from 0 u To access an element and store a number in it value [0] = 1.0;
  83. Accessing elements u value[0] is the first element u value[1]

    is the second element u And etc. u System.out.println(value[2]); u value[3] = anotherVariable
  84. Try making an array of type String data_Type variable_Name =

    new data_Type [length#] Replace with the appropriate items If you still need help, here’s another example int [ ] string = new int [2];
  85. Using Arrays with Methods u You can have a for

    loop and store variables into an array
  86. Packages u Classes in the standard library are organized into

    packages u Package is a collection of classes with a related purpose u Ex. Rectangle class belong to package java.awt which contains many classes for drawing window, graphics, and shapes u You have to import these classes u System and string classes don’t need to be imported by it’s already automatically imported