Java
Multidimensional Arrays (Winder 112) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
// 2D array with 10 rows of 20 columns. final int[][] array2D = new int[10][20]; // 3D array of String of size 10×20×30. final String[][][] array3D = new String[10][20][30]; // 4D array of double of size 5×10×5×10. final double[][][][] array4D = new double[5][10][5][10]; (Winder 112) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
int [] y = {9000, 1000, 1337}; String names [] = {"Bob", "John", "Fred", "Juan Pedro"}; boolean bools[] = new boolean[] {true, false, false};
// Another way to declare & initialize an array
int [] intArray = new int[10]; String [] stringArray = new String[1]; boolean boolArray [] = new boolean[100];
// Arrays //The array size must be decided upon instantiation //The following formats work for declaring an arrow //<datatype> [] <var name> = new <datatype>[<array size>]; //<datetype> <var name>[] = new <datatype>[<array size>];
int month = 3; String monthString; switch (month){ case 1: monthString = "January"; break; case 2: monthString = "February"; break; case 3: monthString = "March"; break; default: monthString = "Some other month"; break; } System.out.println("Switch Case Result: " + monthString);
// Switch Case // A switch works with the byte, short, char, and int data types. // It also works with enumerated types (discussed in Enum Types), // the String class, and a few special classes that wrap // primitive types: Character, Byte, Short, and Integer.
Arrays as Return Values
A method can be declared as returning an array as a result: private static int[] createInitializedIntArray (final int size, final int value) { final int[] array = new int[size]; for (int i = 0; i < array.length; ++i) {array[i] = value;} return array; } (Winder 108) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
method
A method declaration consists of a named sequence of statements that appear within a compound statement. The rules determining what is a valid method name are the same as those for variables. An example method declaration is: private void sayHello(){ System.out.println("Hello!"); System.out.println("This is a method called sayHello"); System.out.println("It contains 3 statements"); } This method is named sayHello. In the method body, the statement sequence within the compound statement( compound statement is the statement following the method parameters encapsulate dby { } and contains more statements divided by ; ), there are three output statements. (Winder 60) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
encapsulation
Abstraction in programming is intimately associated with the concept of encapsulation. Encapsulation is a mechanism for ensuring that things have a definite inside and outside. The inside is protected from anything on the outside, offering a guarantee that some outside agent cannot arbitrarily change anything on the inside. Once protected by encapsulation, an abstraction can only be accessed via a well-defined interface visible from the outside. The inner workings are hidden and do not have to be known about to make use of the abstraction. Hence, the outside view and the interface present the abstraction, hiding away the internal details. Encapsulation is often referred to as being an information-hiding mechanism, for fairly obvious reasons. (Winder 59) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
array bounds
Array bounds errors are only found at run time. The Java compiler doesn't check at compile time. This can make errors hard to detect. An array of size n is indexed from 0 to n-1 and any attempt to use an index outside of that range will result in an error when the program is run. This is known as bounds checking and if an out-of-bounds indexing is attempted a message similar to this is displayed: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11 at ArrayIndexError.main(ArrayIndexError.java:4) By default, the error will cause the program to terminate, requiring the problem in the code to be located, corrected and recompiled. (Winder 106) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
Arrays as Method Parameters (Winder 107) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
Arrays can be passed as parameters to methods and returned as the result. However, because an array variable is actually a reference to an array object, the effects of the parameter mechanism when applied to arrays are very different to the situation with primitive types. This means we should study this quite carefully. An array parameter is specified in the same way as any other parameter, using a parameter variable declaration. The size of the array does not need to be included as a parameter in the declaration as an array always knows its own size. So, for example: void f (final int[] array) { ... } declares a method f with parameter variable array which is initialized with an array reference specified as the parameter value in the method call. For example: int[] anArray = new int[100]; object.f (anArray); The use of parameter variables and parameter values is the same here as it was for the case of primitive types. The critical difference is that we are passing a reference to the array and not the array object as a parameter: the parameter variable and parameter value are references to an array object. This means that the array object is not copied; the array object inside the called method is the same as the one in the caller. The result of this is that if array elements are changed by assignment in the method, the array seen outside the method is also changed as it is the same array. (Winder 107-108) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
/** * This is a documentation comment. The first sentence is a one‐line description and the rest of * the comment provides more detail. * * @author Russel Winder and Graham Roberts * @version 2005‐07‐21 * @see Integer */
Documentation comments Documentation comments have a structure to allow them to be processed automatically by the JavaDoc program. The first sentence of the comment is assumed to be a summary and the rest of the comment the main body of information. Within these comments you can embed HTML tags, for example to add emphasis or other typesetting features. The @author, @version and @see elements are special JavaDoc tags that allow the programmer to mark information as having a particular meaning and be treated accordingly when the documentation is created. Comments should always be used to add information to source code, not to repeat what is obvious by reading the source code. The key to good commenting is balance. Too few comments may require too much study of the source code to work out what is going on, while too many comments will hide the source code and be laborious to read. DisplayOneToFive is short and simple, so does not need much in the way of comments; the source code is largely self‐documenting. However, for every program it is useful to have some preliminary comments that state things such as - the purpose of the program, - who wrote it and when, - and a revision history summarizing changes made to the program . These are all useful bits of information that cannot be determined from the source code alone. (Winder 36-37) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
public class DisplayOneToFive { private void outputCounts() { int counter = 1; while ( counter < 6 ) { System.out.println ( counter ); counter = counter + 1; }//closes while loop }//closes outputCounts method public static void main ( final String[] args ) { DisplayOneToFive object = new DisplayOneToFive(); object.outputCounts(); } //closes main method } //closes DisplayOneToFive class (Winder 33) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
Example of how you write a programme, with class and main method to execute output
compiling and running java code
Having created the source code of the program in a file called Hello.java, we can compile it with the command: javac Hello.java to create the file Hello.class and then run it with the command: java Hello This command causes the Java run-time system to search for the file Hello.class, read the contents and then begin execution with the main method. Thus, the execution of any Java program is always initiated by calling a main method. (Winder 61) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
System.out.print ("Hello"); System.out.print ("World"); System.out.println ("Hello"); System.out.println ("World");
Hello World Hello World
reference type
Java separates primitive data types and object data types (Java uses the term reference type) handling variables of the two sorts of type differently. Until we started looking at arrays we had only dealt with primitive types, for example int and double. String is special in that whilst it is actually a reference type, there is special syntactic support in Java so that it can be used more or less like a primitive type. With arrays we can no longer ignore the difference between primitive types and reference types. As we noted in Section 2.6.3, page 28, a variable of a reference type does not contain a representation of an abstract type in the way a variable of primitive type does. Instead, it contains a reference to an object. So in the declaration above, the variable n is a reference to an array object which is constructed using the new expression. It is important to always separate thinking about the variable and the object for all reference types. (Winder 105) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
state
Programming languages use the concept of state in order to remember things: the state provides a set of values that can be manipulated by statements. The execution of a program can be described in terms of a state machine model, where each statement causes the program to change from one state to the next. The initial state holds the set of starting values (the input) while the final state holds the set of result values (the output). The statements in the program are responsible for transforming the initial state to the final state. (Winder 26) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
void
Rather than having two kinds of method, one that specifies a return type and another that does not, Java requires that all methods have a return type. This necessitates having a type indicating that there is no return value from a method. This type is type void. void is a place-holder for strong type checking purposes indicating to the compiler that: there is no return value from the method; there need be no return statements in the method; if the method has return statements there must be no expression following the return keyword; and calls to the method cannot be used in expressions. (Winder 63) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
comparing two strings
String s = "Hello" ; String t = "hello" : int result = s.compareTo (t); Strings are compared by calling the compareTo method for one string (using the '.' to separate the object name from the method name) and giving the other string as the parameter value. The method returns an integer value that encodes the result of the comparison, which in the example is stored in the variable result. The return value will be less than zero if string s comes before t, zero if s and t represent strings of equal value, and greater than zero if s comes after t. For the example above, result should be initialized to an integer less than zero, as 'Hello' comes before 'hello'. (Winder 42) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file. because if using == it's actually comparing the variables(?)
The Class Arrays
The JDK provides a class Arrays in the package java.util. This provides a number of very useful utility methods for working with arrays, such as those for sorting and searching. For example, if an array of integers needs to be sorted into ascending order, the following statement can be used: // Assume n is an array of integers in unsorted order. Arrays.sort(n);// Sort the array. The sort method is a static method (see Section 3.3, page 59, and Section 6.7, page 197), so does not need to be called for a specific object, so in this example we can call the method on the class name. (Winder 112) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
javabytecode
The Java compiler generates Java bytecodes. When a Java program is executed the bytecodes are interpreted by an implementation of the Java Virtual Machine (JVM). while Java Virtual Machine, runs on the real processor of the machine. the java programme, through the jvm is architecture neutral, provided the jvm is installed.
break;
The break statement causes the loop to terminate immediately and the program execution to jump to the statement following the loop. This 'test in the middle' strategy can often turn out to be a very useful one since it can often simplify the structure of loops. (Winder 25) ie while ( piece.canMoveForward()){ piece.forward (); if ( piece.cannotMoveForward()){ break; } piece.forward (); } Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
calling a method
To invoke the method (or as it is often termed, 'call the method') and execute its statements we need an object and a statement of the form: anObject.sayHello (); where the object needs to have been created using the new operator in a statement like: Hello anObject = new Hello (); (Winder 61) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
for calling methods within the same class
You need to use the dot notation to call object methods (like name.toUpperCase() ) For methods within the same class, you can just write the method name: starLine();
int foo = 5; String bar = (foo < 10) ? "A" : "B"; System.out.println(bar); // Prints A, because the statement is true
_conditional operator / ternary operator (expression)? if_true:if_false;
// Do While Loop int fooDoWhile = 0; do { fooDoWhile++; }while(fooDoWhile < 100);
_do while loop counter_initialisation do { statement(s); counter_increment; } while (expression);
for (int counter =0; counter<10; counter++) { statement(s); }
_for loop for (initialization; termination; increment) { statement(s); }
int counter = 0 while (counter<10) { statement(s); counter ++ }
_while loop counter_initialisation while (expression) { statement(s); counter_increment; }
recursion
a method that call itself. private int sum (final int n){ if (n == 0) {return 0;} else{return sum (n - 1) + n;} } (Winder 66) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
ArrayList<String> a = new ArrayList<String> (); // Create an empty ArrayList able to hold Strings.
a type of container classes . Before an ArrayList can be declared as shown above, an import statement has to appear. This tells the Java compiler where it can find information about the named class, thereby making it available for use. This is not done automatically. So we must have the statement: import java.util.ArrayList; (Winder 120) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
return the size of an array
array.length An array always knows its own size: for an array array, the expression array.length returns the number of elements in the array. This expression is not a method call so no parentheses are used. This means that if we want to iterate over all the elements in an array we do not need to know its length to write the code. (Winder 106-107) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
indexing multidimensional Arrays
array2D[1][2] = 2; array3D[4][6][8] = "Hello"; array4D[1][1][1][1] = 2.34; (Winder 112) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
=
assignment operator. variable_name = expression;
javac fileName.java
compile java file in terminal in file to run
design
deciding the structure of the program to be constructed.
declaring and initialising variables
declaring and initialising a variable, done together: double pi = 3.1416; or done separately : double pi; //declaring ... pi = 3.141593; //initialising. Having said this, we should note that the Java system provides default initialization for all variables. For example, int variables are initialized to 0 and double variables to 0.0. However, the Java compiler still checks for situations where default initialization is relied on and will complain in cases where it matters, so it is always better practice to use explicit initialization. See Section 19.8.2, page 642, for the full details on variable initialization. (Winder 30) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
count through the elements of an array (for loop)
double sum = 0; for (int i = 0; i < array.length; ++i) {sum += array[i];} (Winder 107) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
public enum Chessmen { WHITE KING, WHITE QUEEN, WHITE ROOK, WHITE BISHOP, WHITE KNIGHT, WHITE PAWN, BLACK KING, BLACK QUEEN, BLACK ROOK, BLACK BISHOP, BLACK KNIGHT, BLACK PAWN, E MPTY }
enums are used to express fixed sets of constants throughout your program, and because they are constants, we type-set them in UP- PER CASE. Similarly, you could have enum for days of week ( MONDAY, TUESDAY...), compass directions (NORTH, WEST...) etc.
\n
escape character, carriage return, new line.
Once the ArrayList has been created, values can be added to it using the add method. So, for example: (Winder 120) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
final ArrayList<String> a = new ArrayList<String>(); final String s = "hello"; a.add(s); // Add elements to end of ArrayList. a.add("world"); (Winder 120) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
arrays of chars and Strings are able to interwork easily with each other as we can create Strings from arrays of chars:
final char[] hello = {'h', 'e', 'l', 'l', 'o'}; final String s = new String (hello); and arrays of chars from Strings: final char[] hello2 = s.toCharArray (); In the first code fragment, the String s has been initialized using the character array hello, which was created using an initializer list, instead of the more usual: final String s = 'hello'; which is, of course, more appropriate in most circumstances since it better represents the abstraction of string. (Although a String is a reference type, the compiler recognizes the special syntax and does the right thing.) There can be times though where this relationship between Strings and arrays of chars can be extremely useful: occasionally, it can be useful to convert a String to a char array in order to manipulate the individual characters and this would require use of the toCharArray method of class String as shown above. It has to be said though that most string manipulation is better handled using the class StringBuffer rather than the array of chars explicitly. It is all to do with providing useful methods easily usable and (dare we say it) good use of abstraction! (Winder 118-119) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
declaring and initialising a constant
final double pi = 3.14159265; (Winder 30) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
scanner
import java.util.Scanner; Scanner scan = new Scanner(System.in); System.out.println("a question?"); int num1 = scan.nextInt();
declearing an array
int[] n = new int[10]; // An array of 10 ints ps:arrays in java can only have elements of one type. (Winder 105) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
public static main void(String[] args)
is the main method in java. _public or private _static, means that the class can call methods without having to instantiate objects in order to do so. example[..] _void, the method does not return any output, datatype. _(String[] args) the argument of the main method is a array of type string, called args, name can be anything but convention is args or argv. this is to capture the command line parameters, and use them during the programme.
int
primitive types,By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.
String
primitive types,In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. You'll learn more about the String class in Simple Data Objects
boolean
primitive types,The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
byte
primitive types,The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
char
primitive types,The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
double
primitive types,The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
float
primitive types,The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
long
primitive types,The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.
short
primitive types,The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters
getInput
private int getInput() { Input in = new Input(); System.out.print ("what's the input?"); return in.nextInt(); } Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
example of declaration of a method that takes an argument
private int times2 (final int x) { return x* 2; } The method name, times2, is preceded by the private keyword (which we will deal with in Chapter 6, page 171) and the return type int, and is followed by a parameter declaration. The parameter declaration appears in parentheses and looks very like a variable declaration, which, in fact, it is. The final int x is declaring a parameter variable called x that will not be changed in the method. If the final is not present, then the value of the parameter can be changed in the method body. Neither situation is more correct, the right choice depends upon the context; what the method is computing and how it does it. However, in all situations where the parameter remains unchanged in the method it is always best to have the final—the compiler supports our intention of the parameter variable being a constant by checking to ensure that the value is never actually assigned to, issuing an error if it is. (Winder 64) Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file.
static
static means that the variable or method marked as such is available at the class level. In other words, you don't need to create an instance of the class to access it. public class Foo { public static void doStuff(){ // does stuff } } So, instead of creating an instance of Foo and then calling doStuff like this: Foo f = new Foo(); f.doStuff(); //which would be calling an object You just call the method directly against the class, like so: Foo.doStuff(); //calling the class from http://stackoverflow.com/questions/2649213/in-laymans-terms-what-does-static-mean-in-java The word static marks the method as a static method, meaning that, although it is part of the class, it can be called directly rather than only being called for a specific object in the way the sayHello must be. A (Winder 62) For instance this is the case with the main method. Winder, Russel. Developing Java Software, 3rd Edition. John Wiley & Sons UK, 122006. VitalBook file. The static keyword tells us that this method is not an object method (we do not have to create a new object in order to be able to use it)[Slides]
compound statement
{ }