Java Programming Atul Prakash
Java Language Fundamentals The language syntax is similar to C/ C++ If you know C/C++, you will have no trouble understanding Java s syntax If you don't, it will be easier to learn C/C++ later! We will contrast Java with Python where necessary
Keywords Keywords are reserved words ANSI C has around 32, Java around 50 Keywords in the Java Language abstract continue for new switch assert *** default goto * package synchronized boolean do if private this break double implements protected throw beyte else import public throws case enum **** instanceof return transient catch extends int short try char final interface static void class finally long strictfp ** volatile const * float native super while * not used ** added in 1.2 *** added in 1.4 **** added in 5.0
Python: you can just type in code. Runs as you type: 2 + 3 Programs Java: programs are compiled. Always start from a "main" function in a class // HelloWorld.java x = "hello" print x public class HelloWorld { public static void main(string[] args) { String x = "hello"; System.out.println(x); } }
Variables and Types All variables must given a type at start. Variable type cannot change (unlike Python)
Common Types short, int, long (integers of various max. lengths) float, double (floating point values) char (single unicode character)e.g., 'a', '\n' boolean: true/false String: immutable. Use double quotes.
Primitive Data Types Type Name Type Value Size Range Example literals boolean true/false 1 byte - true, false int integer 32-bit (4-byte), signed, two scomplement long integer 64-bit (8-byte), signed, two scomplement -2 31 2 31-1 -2147483648-2147483647 -2 63 2 63-1 -9,223,372,036,8 54,775,808) 9,223,372,036,8 54,775,807 byte integer 1 byte -128 127 - decimals: 100, -2 Octal: 07, 05 Hexadecimal: 0x1, 0xA9 decimals: 10000L, -212L Octal: 07123L, 0125L Hexadecimal: 0x1D3L, 0xA9L short integer 16-bit (4-byte), signed, two scomplement -2 15 2 15-1 -32,768 32,767 -
Primitive Data Types Type Name double float Type Value floatingpoint floatingpoint Size Range Example literals 64-bit (8-byte), described in IEEE reference 754 36-bit (4-byte), described in IEEE reference 754 char Single char 16-bit (2-byte), signed +-1.7676931348 6231570 x 10 +308 +-4.9406564584 1246544 x 10-324 -3.40282347 x 10 +38-1.40239846 x 10-45 1e1, 2.,.3, 3.14, 56.3e_45d 1e1f, 2.f,.3f, 3.14f, 56.3e_4f 0 65535 Single char: T Escapes: \n, \r, \t Unicode escape: \u0041 (A)
Type Conversions Generally, if you are doing: a = b Then, a and b must of compatible types.
Casting Conversion to more general types generally automatic. E.g. But, not all casts allowed. They must make "sense". double z = 3; // works Conversion the other way generally requires a "cast" to tell the compiler that this is intentional.
Conditions && used for anding. used for oring.! used for negation. == for equality check.!= for non-equality
Operators Operators are symbols that perform an operation on a set of operands (one, two, three) Most operators require two operands - binary operator. For example, z = x + y; Some unary operators: ++: increment operator for integers. Two forms: pre-increment and post-incremet int i = 10; int j = ++i; // increment i, then assign. int i = 10; int j = i++; // assign i, then increment. Operator requires three operands - ternary operator op1? op2 : op3 (infix notation): (x==y)? x=9 : x = 99; x = ((x == y)? 9 : 99);
Loops Example initialize continuing condition advance i after each iteration for (int i = 0; i < 10; i++) { statement1;... statement n; } Using while loops: int i = 0; while (i < 10) { statement1;... statement n; i++; } Python equivalent: for i in range(10): statements
Classes and Objects Classes: User-defined object type E.g., a graphics library may define classes for Point, Rectangle, Square, etc. Objects: instances of a class.
Creating Objects Usually, done using the new operator. Point p = new Point(10, 15); Dog d = new Dog("fido", "woof"); d refers to an object of type Dog create a new dog object whose name is fido and who woofs
Defining a Class Constructor method method on a dog Dog d; // Does not create a dog. Just a reference to dog. d = new Dog("Fido", "woof"); d.bark(); d
Testing a Class Write another class for testing: DogTestDrive. We will do this in the class using Eclipse and also show some of the Eclipse features.
Small Test Example static methods: apply to the class, not to individual objects
Add new features to the Dog class We want to be able to change the bark of the dog. May be make it bark multiple times. Change the name.
Design Process Write the tests for the new features first! Once you have pinned down the tests, it is easier to design and write the features. This is a recommended practice in Agile Programming (or Extreme Programming).
Adding Tests assert expr: program stops if expr is false
Enabling Assertions By default, assert statements are ignored by the compiler. To enable them for debugging, add "-enableassertions" to the javac command. In Eclipse, do Run-> Run Configurations -> Arguments. Add -enableassertions to the VM argument.
Extending the Dog Class
Assignment 2 Write a game similar to Battleship (but not identical). Guess and shoot Klingon spaceships that are cloaked. No GUI at this point. Only text input and output. We will do to the assignment in small stages. Initially, a very simple version of the game will be built --- in fact, I will give you the 0 th version of the game.
0 th Version 1-dimensional grid consisting of 10 squares. A space ship of length 3 somewhere in the grid. User guesses a square. The program prints out "hit" or a "miss". The game ends when the entire ship has been hit. User's goal: to make minimum number of guesses. s s s
What classes do we need? We definitely need a class for a game. Let's call it SpaceshipGame. What methods will we need? Requires some brainstorming. Some likely needs: Place a ship on the game Shoot a ship Check the status of hits and misses With this, we can start writing a SpaceshipTestdrive class.
Writing a test driver public class SpaceshipTests { public static void testhitsandmisses() { SpaceshipGame g = new SpaceshipGame(); } g.addship(3); // Add a ship at position 3. Assume ship of length 3 g.shoot(2); // This should be a miss. Shoot at coordinate 2 assert g.gethits() == 0; assert g.getmisses() == 1; g.shoot(3); // A hit assert g.gethits() == 1; assert g.getmisses() == 1; g.shoot(4); // Another hit g.shoot(5); assert g.gethits() == 3; assert g.getmisses() == 1; main not shown
Writing shoot We need to think about how we are going to know where the ship is. We can use an array or list of 10 positions and mark the ones where the ship is. But, may be we don't need an array. We can just imagine one and simply record where the ship is (e.g., at position 4). Use the simplest strategy initially.
Logic Good idea to write the logic in English (pseudo-code) first. Place ship at a random position on the grid Loop: get user input check if hit or a miss Break out of the loop when everything hit.
Files Will be posted on CTools.