CT 229 Fundamentals of Java Syntax 19/09/2006 CT229
New Lab Assignment Monday 18 th Sept -> New Lab Assignment on CT 229 Website Two Weeks for Completion Due Date is Oct 1 st Assignment Submission is online @ http://ecrg-vlab01.it.nuigalway.ie/uploader/submissions.html There is a link to the submission page from the main course webpage @ http://www.nuigalway.ie/staff/ted_scully/ct229/ 19/09/2006 CT229 1
Assignment Upload 19/09/2006 CT229 2
Assignments Submission Submit one file at a time You can only submit.java files Assignment Marking There will be four sections to assignment 20% for successful completion of each section No marks will be awarded unless section is running correctly 20% goes for correct programming style (naming conventions, commenting, formatting etc) Always keep a copy of your completed assignment Original Work Only!!! 19/09/2006 CT229 3
Java Style Guide Adhering to a programming style guide results in writing correct, high quality, maintainable and easily readable java code. The Java Programming Style guide can be divided into: Naming Conventions Commenting Formatting 19/09/2006 CT229 4
Naming Conventions Variable Names Variable should have mixed-case letters, beginning with lower-case use accountbalance instead of AccountBalance or accountbalance Avoid using abbreviations (accbal) or very long names Use a name that describes the function of the variable Constant Names Use all upper case letters, separating words with underscore INTEREST_RATE instead of interestrate Avoid the use of magic number, that is actual numbers that appear in the code without any explanation interestdue = 2000*10 interestdue = accountbalance * INTEREST_RATE 19/09/2006 CT229 5
Naming Conventions Methods As with variables use mixed-case letters for naming methods Method name should indicate its purpose Generally methods that return a the value of a variable have a prefix get (Example: getaccountbalance) While methods that set a variable value have a prefix set (Example: setaccountbalance) Parameter Names Follow same naming convention as used with variables 19/09/2006 CT229 6
Commenting Comments should be used to improve the readability of the program Two Types of Comments: Header Comment Single-line Comments 19/09/2006 CT229 7
Header Comment A header comment appears at the beginning of a.java file. Informs the reader of the function of the program Identifies the original author Example /* Simple Java program that prints a Hello message */ /* John Doe, Student Number: 00003112 */ NOTE!! For each assignment ensure that your name and student number is written in the header comments 19/09/2006 CT229 8
Single Line Comment Normally provides an overview of a line or a number of lines. Begin with // or nested between /* */ Do not insert useless comments Example // Get hourly pay rate in string form: convert to double ratestr = JOptionPane.showInputDialog("Enter Hourly Rate:"); rate = Double.parseDouble(rateStr); 19/09/2006 CT229 9
Formatting Formatting relates to the appearance of your code Code should be tidy and easy to read Two important types of formatting generally applied Indentation Space 19/09/2006 CT229 10
Indentation Use of indentation makes code easier to read Simple Rules for indentation After each { move the subsequent code in by three spaces Open and close parentheses { } should be inline with each other Example /* Simple Java program that prints a Hello message */ /* Ted Scully, Sept 2006 */ public class Hello { public static void main(string[] args) { System.out.println("Hello World!"); } } 19/09/2006 CT229 11
Space Use of white space improves the readability of programs 19/09/2006 CT229 12
Second Java Program Program to Calculate Employee s Total Week s Wages: 1.Look up the employee s pay rate (rate) 2.Determine the number of hours worked (hrs) in week 3.If no. of hours worked < or = 40 then regular wages (wage) = hrs*rate and overtime pay (over) = 0 4.If hrs > 40 then wage = 40*Rate and overtime pay (over) = hrs - 40) * (1.5 * rate) 5.Total Wages (total) = wage + over 19/09/2006 CT229 13
Wages.java /* Basic Java Program that asks the user for the hourly payrate and the number * of hours worked. It then calculates the total wage earned for the user */ /* Ted Scully, Sept 2006 */ import javax.swing.joptionpane; // Dialog box methods public class Wages { public static void main(string[] args) { double rate, hrs, over, wage, total; String ratestr, hoursstr; REMEMBER: For Assignments include name and student number // Get hourly pay rate in string form: convert to double ratestr = JOptionPane.showInputDialog("Enter Hourly Rate:"); rate = Double.parseDouble(rateStr); // Get hourly pay rate in string form: convert to double hoursstr = JOptionPane.showInputDialog("Enter Hours Worked:"); hrs = Double.parseDouble(hoursStr); 19/09/2006 CT229 14
Wages.java if (hrs <= 40) { wage = rate * hrs; over = 0; } else { wage = rate * 40; over = (hrs - 40) * 1.5 * rate; } total = wage + over; // Display total wage earned JOptionPane.showMessageDialog(null, "Total weekly wages are " + total); } } // Terminate program System.exit(0); 19/09/2006 CT229 15
Main Features import javax.swing.joptionpane; Loads classes from Java API that program will use javax.swing is a graphical user interface package JOptionPane is a class in package for displaying msg boxes double rate, hrs, over, wage, total; String ratestr, hoursstr; Declares existence of four variables that can hold numerical data ( double-precision floating-point ), and two variables that can hold string (i.e. text) data ratestr = JOptionPane.showInputDialog("Enter Hourly Rate:"); Invokes a method called showinputdialog, which is part of the JOptionPane class (defined javax.swing package) Displays input box with text Enter Hourly Rate ratestr is set to whatever text the user types in 19/09/2006 CT229 16
Main Features rate = Double.parseDouble(rateStr); parsedouble is a method in Double class, that converts text ( 123 ) to a double number (123.0) Double is a class defined in the Java language package (java.lang); imported automatically if (hrs <= 40) Code to make a decision: which lines will be executed next depends on the data in the variable called hrs Exactly like C total = wage + over; Sets total equal to the sum of wage and over This line is after the if-block; it is executed after whichever of the previous blocks of code is executed 19/09/2006 CT229 17
Main Features JOptionPane.showMessageDialog (null, "Total weekly wages are " + total); Method that displays a message box Two arguments: 1: usually null 2: the text to display The + joins text; automatically converts numbers to text command (statement) can be split over more than one line The ; indicates the end of a statement System.exit(0); Method of the System class: terminates the program Required for graphical programs Like Double, System is part of java.lang package, which is imported automatically at the start of the program 19/09/2006 CT229 18
Comparing C and Java Syntax Java copies basics of C syntax Expressions end in ; Almost all operators the same (Java has a few extra) Basic data types similar but not identical Same comment forms, but Java also has Javadoc comments Same decision and loop syntax, similar use of { } Java method parameters, structure and return values similar to C functions (some differences) 19/09/2006 CT229 19
Comparing C and Java Syntax Java is Object-Oriented C has nothing like Java classes (but C++ has) Basic structure of programs different main method has different syntax Class name must be the same as the.java file name Classes and methods in Java standard API completely different from C Standard Library functions Java has automatic garbage collection: no malloc(), no free(), no pointers! 19/09/2006 CT229 20
Primitive Data Types All variables must be declared with a name and a data type before they can be used May declare multiple variables of same type: int a, b, c, d; Can have declarations in middle of executable code Primitive Data Types: Primitive Data Types are similar to variables in C. However, they are defined more precisely in the interests of portability. int integer (whole number, pos or neg; 32 bits) long integer (can hold larger value than int; 64 bits) short integer (can hold 16-bit integers) byte integer (can hold 8-bit integers) float real number (with decimal point; 32 bits) double real number (larger precision/size; 64 bits) char holds a single character (Unicode, 16 bits) boolean can be either true or false 19/09/2006 CT229 21
Primitive Data Types Unlike C, primitive data types all have fixed storage size Example boolean result = true; char capitalc = 'C'; byte b = 100; short s = 10000; int i = 100000; 19/09/2006 CT229 22
String Data Type String Class defined in java.lang (imported automatically) Stores text (multiple characters) Example public class Main { public static void main(string[] args) { String firstname = John "; String lastname = Doe"; String fullname = firstname + lastname; System.out.print(fullName); } } 19/09/2006 CT229 23
Wrapping Primitive Data Types in a Class For every primitive data type, there is a type-wrapper class While primitive types have no associated methods, their associated wrapper classes do Example int number = 5; // Integer is the wrapper class for the primitive type int Integer numberwrapper = new Integer(number); double realnumber1 = number1wrapper.doublevalue(); System.out.println(realNumber1); 19/09/2006 CT229 24
Constants The value of a variable can be changed, but the value of a constant is fixed To create a named constant in Java you use the final type modifier A field declared final cannot be changed in the program Remember in C: #define STUDENT_NUMBER 00112233 Example final int STUDENT_NUMBER = 00112233; final String HELLO_MESSAGE = "Welcome to the Class CT229"; System.out.println(STUDENT_NUMBER); System.out.println(HELLO_MESSAGE); 38043 Welcome to the Class CT229 19/09/2006 CT229 25
Scope of Variables Class Variables: Declared as part of the class definition Have a class-wide scope (visibility, life-span) Can be accessed by member methods of class Local variables: Variables declared within a method Visible only in this method Two or more methods can use same names for local variables public class variable: Visible throughout the program Will cover public/private visibility modifiers later 19/09/2006 CT229 26
Scope of Variables 19/09/2006 CT229 27
Primitive Type Conversion Converting from one type to another is possible in a number of ways in Java. One solution is to use wrapper classes Example int number1 = 5; // Integer is the wrapper class for the primitive type int Integer number1wrapper = new Integer(number1); // Converts int number to double double realnumber1 = number1wrapper.doublevalue(); System.out.println("double value is "+realnumber1); 19/09/2006 CT229 28
Type Conversion NOTE! Cannot do assignments that involve potential loss of data: OK to assign int value to double variable (implicit cast) Error to assign double value to float variable Could also use casting to force conversion between numeric types Example float floatnumber; double doublenumber = 1.234; floatnumber = (float)doublenumber; 19/09/2006 CT229 29
Type Conversion Convert using methods of number classes Can convert a String to a primitive data type int num = Integer.parseInt(str); double rate = Double.parseDouble(rateStr); Can convert a primitive data type to a String String str = Integer.toString(num); Using this method you cannot convert directly from one primitive data type to another 19/09/2006 CT229 30