480 likes | 676 Views
Intro to Java. RoboRebels. Java. Why use Java to program our robot? Java is a very popular programming language Java is used to teach programming in many secondary and higher educational institutions
E N D
Intro to Java RoboRebels
Java • Why use Java to program our robot? • Java is a very popular programming language • Java is used to teach programming in many secondary and higher educational institutions • Java is used in many industries to program robots (NASA uses Java in some of the Mars Rovers)
Syntax • Java has a specific set of rules which you must follow to program • For example, names of variables, methods, classes and packages are case sensitive! Variable != variable • Each statement line must end with a semicolon, ;
Variables • Variables allow Java programmers to access data via human readable names • Java uses various variable types to define how to interpret the data it contains. • A variable has a name and a value. A variable can be accessed and modified using its name. • Variables can be manipulated using operators.
Variable Types • Boolean – true/false value • Integer – whole number value [-2,147,483,648, 2,147,483,647] • Double – decimal value [4.94x10^-324,1.79x10^308] - precision • Char – (‘x’, ‘z’, ‘5’) – 16 bit Unicode character • String – a group of characters - “Welcome to Java” • Arrays – groups of a type - {6, 3, 5, 1, 3, 0}
Variable Declaration • Before you can use a variable, you have to declare it. This means that you tell java to create a memory location to store the variable, and the type of data to be stored in it. int variable; String name;
Variable Assignment • The = operator is used to assign a value to a variable. • The new value is stored inside the previously declared variable, and can be accessed by calling the variable’s name. int value; value = 6; (value + 5) returns the value 11
Arithmetic Operators • The +, -, *, and / operators can modify the value in a variable. double value = 9.5; double value2; value2 = value / 4; • value2 now contains 2.375
Conditions • Conditions can be relational comparisons, or logical comparisons. • Java uses operators to evaluate conditions. • All conditions are evaluated to a true or false value
Relational Operators • > - greater than (5>2) - true • < - less than (5<2) - false • >= greater than or equal to (5>=5) - true • <= less than or equal to (5 <= 6) - false • == equal to (5==2) - false • != not equal to (5!=2) - true
Logical Operators • && - AND • T & T == T • T & F == F also F & T == F • F & F == F • || - OR • T & T == T • T & F == T also F & T == T • F & F = F • ! – NOT • !F = T • !T = F
Complex Conditions • Logical and Relational operators can be used to evaluate more complex conditions • (4 < 5 && 3 == 2) returns false • (!(5 == 4) || (5 != -7 && 9 >= -7) returns true
Flow Control Structures • Loops allow groups of code to be run repeatedly • while • for • Branches use a condition to decide which group of code to run • if
While Loop • A while loop is the simplest type of loop. • It evaluates a condition, which it uses to determine whether the body of the while loop is executed. • Once the body is run, it evaluates the condition again, and repeats if it is true. • While the condition is true, continue executing this code. while( 5>3 ) { //body }
For Loop • For loops offer the use of a counter to repeat code a number of times. They are particularly useful for cycling through every element in an array of data. • A for loop uses a more complex condition system for ( int value=1; value<=5; value++ ) { //body } Can you think of a way to make a while loop act like a for loop?
The If Statement • The if flow control structure is a mechanism used to execute a block of code, but only if a certain condition is true. • If the condition evaluates to true, the code is run. If it evaluates to false, it is skipped entirely. if( 6 == 6 ) { //body }
If-Else Statement • The if-else statement runs one block of code if the condition is true, or another if the condition is false. if (5>30){ //true body } else { //false body }
If – Else If - Else • Another form of the If/Else control structure is the If – Else If – Else structure if ( time <= 0 ) {// time is up!} else if ( time == 15 ) { // you have 15 minutes left!} else { // keep working!}
Statements • A statement is a line with an instruction on it: • A variable declaration or assignment • An arithmetical operation • A call to a method • Statements must be followed by a semicolon ; • Examples: • intn = 7; • n = n + 1; • doSomething();
Methods • A method is a block of statements grouped together under one name. In other languages they are called functions or procedures. • The header gives information about the method. • A method can be called using its name. A method call results in the body of the method being run at the point where it is called. • Methods can have local variables, which are only accessible from within.
Method Header • The header contains the name and the return type of a method. public static void methodName(int parameter){ //body} • Here, void is the return type, meaning that no value will be returned. The parameter variable can be used inside the body of the method.
Using (calling) Methods • A method can be called using its name. methodName(6); • The preceding method call is a valid statement that runs the body of methodName • Within the methodName method, the value of the parameter “parameter” is 6.
The Main Method • The main method is the entry point of a program. The code at the top of this method is run first. public static void main(String[] args){ //body of method and entry point of program } • Our robot’s main method is hidden in FRC’s provided code.
Classes • Most code belongs in a class. A class is a group of methods and variables. • Classes are like blueprints for objects. Objects can be instantiated from a class. • Classes may contain static variables and methods • Access Modifiers are used to control they type of access other objects have to they methods and members of your class (public, private)
Instantiation • Classes that are designed to be instantiated as objects have constructors that initialize the object. A constructor’s syntax is like a method’s, but with no return type. The name of the method must be the name of the class. public class className {public className() { //constructor body} }
Static • Static variables and methods cannot be instances. The variable is shared with every object instantiated. • Static variables and methods must be accessed directly through the class.
Access Modifiers • Access Modifiers change how other classes can interact with a method or variable. • A public variable or method can be accessed by other classes. • private variables or methods are strictly limited to the class they are declared in.
Comments & the Readability of Code • Comments • What are they? • How are they created? • Where can they be used? • Coding styles • What is the readability of code? • Why is it important?
What is a Comment • What is a comment? • Written text in your source code which doesn’t effect the functionality of your code. • Provides information to you and your team about what your code is supposed to do. • TODO items, notes, etc.
How are comments created • There are two types of comments • Single-line comments • // this is a single-line comment • Multi-line comments • /* * * This is a multi-line comment * */
Where can comments be used? • Comments are usually used outside of statements and before blocks of code • Comments are used to describe the functionality of classes and methods
Comment example /* * This method calculates the square of the passed double * Parameters: x [double] number to be squared * Return value: the square of the passed number */ Public double squared ( double x ) { return x * x; }
The Readability of Code • What is it? • Keeping the code of our project readable means following a convention, or set of rules, to format your code • For example: • For each comment above a method you must describe what the method does, what parameters it takes and what it returns.
Why is readability important? • Keeping code readable and consistent with formatting allows: • Code reviews are easier • Bug hunting and testing is easier • Can you imagine if a magazine or newspaper’s formatting wasn’t consistent? It would be tedious to not only edit, but to read as well.
What formatting convention will we use? • We’ll follow the guidelines provided by Sun: • http://java.sun.com/docs/codeconv/CodeConventions.pdf • Some quick guidelines • Use blank lines often to separate sections of code • Have only one statement per line • If you create a new block of code indent it • Comment your code! Too many comments is better than not enough • Use descriptive variable, method and class names
Formatting is an art • Properly formatted and commented code is an art form • Don’t be discouraged if your coding and formatting is sloppy if you are new. It takes practice. • Don’t be afraid to ask questions about the guidelines that we’ll be following.
Guidelines for writing Reusable code • In Java, Object Oriented Programming (OOP) is forced upon you so most Java programmers use this model to write reusable code. Here are some guidelines: • Imagine that you are writing a self-contained component. • Don’t write code that isn’t needed and keep it simple. • Don’t repeat yourself and try to eradicate duplication. • For more tips see: http://hoskinator.blogspot.com/2006/06/10-tips-on-writing-reusable-code.html
.java, .class and .jar files • .java – A source file which you write your code in. In Java, you must have only one class per .java file. • .class – When the compiler compiles your .java file it turns your source code into bytecode which the Java Virtual Machine can read. The compiler writes this bytecode to a .class file. • .jar – In most medium to large Java projects more than one class is created and, therefore, multiple .class files are created. In order to make downloads of Java applications more efficient .class files are bundled together in .jar (Java Archive) files.
Java Packages • Custom and pre-made groups of Java classes are grouped into Java Packages which are arranged hierarchically. • On your computer packages use folders/directories to organized the .java/.class files and are named in a format which is like the URL of a website
Java Package Example • Let’s say we have two classes: Rectangle and Motor which reside in Rectangle.java and Motor.java • On your hard drive the directory structure would look like this:org/priory/Math/Rectangle.javaorg/Priory/Robot/Motor.java
Java Package Example • Placing the .java files in their respective directories is not enough, however. They must be marked within the files like so:// In the Rectangle.java filepackage org.priory.Math;// In the Motor.java filepackage org.priory.Robot;
Using Java Packages • If we would like to create a Rectangle or Motor object in another class we must import the class or location (called a nameplace) like so:import org.priory.Math.Rectangle; // this imports only // Rectangle class // - or –import org.priory.Math.*; // this imports all // classes in the // Math namespace
Java Libraries • There are many pre-made Java classes and packages available to be used • All you need to do is import the packages or classes and you can use the classes
Further Reading • Introduction to Programming Using Java - http://math.hws.edu/javanotes/ • Java Programming For Kids, Parents and Grandparents - http://myflex.org/books/java4kids/java4kids.htm • See the RoboRebels website under Resources