/* +--------------------------------+ | A Lightning-Fast Tour of Java | | | | by Ed Faulkner | +--------------------------------+ Constructive criticism appreciated. */ /* PRIMITIVE TYPES */ //Signed integer types byte a; // 8 bit short b; // 16 bit int c; // 32 bit long d; // 64 bit //Signed floating point types float e; // 32 bit double f; // 64 bit //Character type char g; // 16 bit unicode character /* Literals */ int baseTenInteger = 60; // Actual value 60 int octalInteger = 060; // Actual value 48 int hexInteger = 0x60; // Actual value 96 double pi = 3.14159; // Floating point literals are double float probability = 0.325f; // Unless they're suffixed with f; double scientific = 3.0e+8; // Scientific notation String message = "A Message."; // String literal. Note that Java is // transparently creating a new String // object for you. /* OPERATORS */ int x = (1 + 3)*10/2 - 1; // Arithmetic. Be careful with order // of operations. When in doubt, use // parentheses. int y = 1; double half = y/2; // Be careful with things like this. // y and 2 are both integers, and // dividing them returns another // integer, which will get rounded to // zero. double half = y/2.0; // This would do what you really want int z = half * 10; // This will fail to compile because // there's a possible loss of // precision. int z = (int)(half * 10); // You can add an explicit cast to // make it compile correctly. int q = x%z; // The mod operator. q is the // remainder when you divide x by z. String foo = "Go" + " away"; // The plus operator can also be used // for string concatenation. int p = foo.length(); // The dot operator accesses member // varibables and methods. In this // case, we're accessing the member // method length(), which gives us the // length of the string. /* CONTROL STRUCTURES */ if (condition) { //do something } else if (othercondition) { //do something } else { //do something } for (int x = 0; x < 10; x++) { System.out.println(x); // Prints 0,1,2...9 } for (int x = 0; x > -10; x-=2) { System.out.println(x); // Prints 0,-2,-4...-8 } for (int x = 2; x < 100; x = x*x) { System.out.println(x); // Prints 2,4,16,32,64 } while(condition) { //Keep repeating until condition is false. The condition is //checked at the beginning of each loop. } do { //Keep repeating until condition is false. The condition is //checked at the end of each loop. } while(condition); switch(someInteger) { case 1: //Do something if someInteger == 1 break; case 2: //Do something if someInteger == 2 break; default: //Do something default } //If you leave out the breaks, cases with fall through. In general //"break" causes control to leave the current block. For example: while(A) { B = B + 1; if (B > 10) break; //Break will end looping } //break sends you to here. //"continue" causes a loop to start back at the top. In this example, //if B is true, the loop will print lots of Hellos, but no Goodbyes. while(A) //continue sends you to here. { System.out.println("Hello"); if (B) continue; System.out.println("Goodbye"); } /* CLASSES */ // Each class should be defined in a file with the same name as the // class, ie MyClass.java. There are exceptions to this rule, but // you don't need to worry about it. class MyClass { int x = 1; // A member variable, with an initial value. public String y; // A public member variable //This is a method that takes no arguments and returns an integer. //"answer" is a local variable that is only defined within this //method. Methods may refer directly to member variables and //other methods. int getXSquared() { int answer = x*x; return answer; } //A public method that takes no arguments and returns nothing. //Notice that it calls another method (getXSquared). public void printXSquared() { System.out.println(getXSquared()); } } class Tester { //Every java program starts at a main method. To run this //program, you'd type "java Tester", which will call this method. //Any command line arguments are passed in as a string array. public static void main(String[] args) { MyClass foo; // Create a reference with type // MyClass. Initially, the reference // is null. foo = new MyClass(); // Instantiate a new object. Now we // can use the reference to access the // object. foo.y = "Hello"; // Access a public member variable System.out.println(foo.y); foo.x = 5; // This is not allowed because x is // not public. foo.printXSquared(); // Access a public method int a = foo.getXSquared(); // This is not allowed because // getXSquared is not public; } } /* Within a class, there is a special pointer always available: * "this". "this" refers to the current object. */ /* ARRAYS */ //Arrays of primitive types int[] numbers; // Defines a reference to an integer // array. numbers = new int[100]; // Creates an array of size 100, // indexed from 0 to 99 numbers[42] = 123; // Refer to an element int s = numbers.length; // Retrieve the length of the array x = numbers[200]; // Throws an // ArrayIndexOutOfBoundsException. //Arrays of Objects MyClass[] foo; // Defines a reference to a MyClass // array. foo = new MyClass[100]; // Creates an array of 100 references // of type MyClass. Each reference is // initially null. foo[10].y = "Hello"; // Throws a NullPointerException, // because foo[10] is still null. foo[10] = new MyClass(); // Instantiate an object and store it // in the array. foo[10].y = "Hello"; // Now we can reference it. /* Static vs Nonstatic */ // Static variables and methods are associated with a class. // Nonstatic variables and methods are associated with a specific // instance of a class. // Static variables and methods may be used anywhere. Nonstatic // variables and methods may only be used in nonstatic methods. // First we'll define a class that contains some static and nonstatic // members and methods, and then we'll illustrate what this means. class AnotherClass { public static int a; // A static member variable public int b; // A nonstatic member variable public int getSum(int c) // A nonstatic method { return a+b+c; } public static int getProduct(int c) // A static method { return a*c; } // main is always static. public static void main(String[] args) { AnotherClass foo = new AnotherClass(); AnotherClass bar = new AnotherClass(); foo.a = 1; foo.b = 2; bar.a = 3; bar.b = 4; System.out.println(foo.a); // Prints 3, because static variables // are shared between all objects of // the same type. System.out.println(foo.b); // Prints 2, because nonstatic // variables are unique for each // individual object. //These both work, because both static and nonstatic methods //may be called from an object. int theProduct = foo.getProduct(10); int theSum = foo.getSum(10); //This works, because static methods may be called directly from the //class name theProduct = AnotherClass.getProduct(10); //This is not allowed, because nonstatic methods may only be //called from a particular object, not from the class name. theSum = AnotherClass.getSum(10); } } //Here another example with static/nonstatic. This class will fail to //compile, because you're trying to access a nonstatic variable (x) //and a nonstatic method (printX) from a static method (main). class MyClass { int x; void printX() { System.out.println(x); } public static void main(String[] args) { x = 10; //This is not allowed printX(); // Neither is this. MyClass c = new MyClass(); c.x = 10; // This is ok, because its associated c.printX(); // with a specific instance of MyClass (c). } } /* CONSTRUCTORS A method with the same name as its class is a constructor. Constructors should have no return type, but can take whatever arguments you want. The constructor is called when a new object is instantiated. */ class Example { String message; public Example(String foo) { message = "You said " + foo; } public static void main(String[] args) { Example foo = new Example("Hello"); //Here's where we call the //constructor. Example bar = new Example(); // This won't work because there // is no constructor that takes // no arguments. } } /* OVERLOADING */ // You may create multiple version of the same method that take // different arguments. The correct method will be called based on // which arguments you pass in. Constructors may also be overloaded. class OverloadedExample { int b; public int sum(int a) { return a + b; } public int sum(int a, int c, int d) { return a + b + c + d; } public double sum(double a) { return a + b; } } /* IMPORTING AND THE CLASSPATH */ // To utilize other people's classes, you must import the appropriate // packages. Import statements must come at the beginning of your // file. import maslab.*; // This imports all classes in the // package maslab. HOWEVER, this does // not import any sub-packages, such // as maslab.camera or // maslab.telemetry import maslab.camera.*; // This imports all classes in // maslab.camera. Now we can refer to // them by name. import java.awt.*; // Many standard Java packages are not // imported by default. This package // is the abstract window toolkit. // In order to properly compile and run with imported classes, the // appropriate classfiles must be located in directories listed in // your CLASSPATH environment variable. In the example above, you'd // need to make sure your classpath contains the maslab class library, // which is at /mit/6.186/maslab.jar. The standard java packages do // not need to be in your classpath, because the compiler already // knows where to find them. In addition, classes defined in the same // directory do not need to be imported. /* POLYMORPHISM */ class Animal { public String sound; public void makeSound() { System.out.println(sound); } } // Class Animal is referred to as the parent of Class Bird, which is // referred to as the subclass of Class Animal. Bird inherits all the // members and methods of Animal, plus it adds some new ones. class Bird extends Animal { int altitude = 0; public Bird() { sound = "Tweet tweet"; } public void fly() { altitude += 10; } } class Fish extends Animal { int numberOfFins; public Fish() { sound = "Glub glub"; } public void swim() { System.out.println("Swimming along..."); } } Bird b = new Bird(); Fish f = new Fish(); b.fly(); f.swim(); // Both birds and fish are animals, so they can be used wherever an // Animal is required. Animal[] zoo = new Animal[2]; zoo[0] = b; zoo[1] = f; for (int i=0; i