David Streader Computer Science Victoria University of Wellington Copyright: David Streader, Victoria University of Wellington Java Programing Basics COMP T1 #3
COMP 112 3: 2 Values are Typed in Java There are lots of different kinds of values: Numbers Integers( int or long) real numbers ( double or float ) e-34 … Characters ( char )'X' '4' Text ( String ) " F -> " Colours ( Color )Color.red Color.green Integer (same as int but an object) …
COMP 112 3: 3 Objects in Java Class defines Objects Used to structure code Objects contain: Fields (hold data) Methods (can be executed) Constructor methods Have same name as Class Have no return type Used to construct Object of the Class Best understood by an example.
COMP 112 3: 4 Simple Java Class Private FieldClass Name Class Declaration Public Method
COMP 112 3: 5 Java Method Variable Declaration Variable assignment Parameter TypeMethod nameReturn Type
COMP 112 3: 6 Java Program Library Constructor Main method
COMP 112 3: 7 Main - called from terminal Constructor Method Call on c1 New Object
COMP 112 3: 8 Structure of the program Import statements Comment Class definition (defining the objects) Class header Method definitions (defining Actions the objects can do) Method header Instructions for performing the action
COMP 112 3: 9 BlueJ Example Look at Floor and Ball from Week1 Class Static Field Object Field Method Variable Review BallError
COMP 112 3: 10 Comments Three kinds of comments: Documentation eg /** Program for converting between temperature scales */ end-of-line comments eg double fahren = celsius * 9 / ; // compute answer anywhere comments eg /* double fahren = celsius * 9 / ; UI.println(celcius + “C is " + fahren + " F"); */ /** 〈 text of comment 〉 */ // 〈 text of comment 〉 Top of class, Before each method Appears in BlueJay /* 〈 text of comment 〉 */
COMP 112 3: 11 Method Definitions /** Print out the conversion formulas */ public void printFormula ( ) { UI.println("Celsius = (Fahrenheit - 32) *5/9"); } 〈 Doc Comment 〉〈 Header 〉〈 Body 〉 {} public void () 〈 name 〉 〈 parameters 〉 instructions to perform this action Specifying the information the action needs. May be empty
COMP 112 3: 12 Variables can be Primitives or Objects Car21 Car z = new Car(2); Ov 2 z Car21 int x = 1; x 1 x names a piec e of memory in which the value 1 is stored The value in z is the reference to the Object.
COMP 112 3: 13 Java Java is very portable Java byte code runs on a Java virtual machine 1.Name.java is source code 2.To compile into byte code > javac -classpath./ecs100.jar Name.java 3.Name.class is the byte code 4.To execute you run the JVM with the byte code >java -classpath ".:ecs100.jar" Name java -classpath ".:/Users/dstr/JPath/ecs100.jar" Master