Notes for Java
一、fundamentals
Comments
• Comments are an important part of every program
– are purely for documentation purposes
– ie they are ignored by the compiler
– can be used anywhere in a program
• Essential comments are:
– Program header
• Program name, author, date written, program description
– Statement description
• To describe a particular statement eg a mathematical formula that may not be clear to someone reading the program
• Space precludes using adequate comments in lecture examples
• Java comments can take two main forms:
// this comment runs to the end of the line
/* this comment runs to the terminating
symbol, even across line breaks */
Initialising Variables
• Initialising a variable means to assign a value to the variable for the first time.
int total;
total = 0;
• Variables can be initialised at the time they’re declared
int total = 0;
int rate = 0, value = 100;
Trying to use uninitialized variables will generate a Syntax Error when the code is compiled
Primitive Data Types
• There are eight primitive (or simple) data types in Java
• Four of them represent integers:
– byte, short, int, long
• Two of them represent floating point numbers:
– float, double
• One of them represents characters:
– char
• And one of them represents boolean values:
– boolean
Numeric Primitive Data
• The difference between the various numeric primitive types is their size, and therefore the values they can store
• We will predominantly use int and double
Characters
• A char variable stores a single character
• Character literals are delimited by single quotes:
'a' 'X' '7' '$' ',' ‘ ‘
char charVariable = 'X‘;
char anotherCharVariable = ‘&‘;
Boolean
• A boolean value represents a true or false condition
• The reserved words true and false are the only valid values for a boolean type
boolean invalidInput = false;
boolean repeatLoop = true;
Identifiers
• Identifiers are the words you devise to use in a program ie.
– variables, constants, methods or the program name
total, countTotalParts, DemoProgram
• Use letters, digits, the underscore (_), and the dollar sign
• An identifier cannot begin with a digit
• Java is case sensitive, therefore Total and total are different identifiers
• There is no length limit
– make the identifier name understandable
Conventions
• A rule that we agree to follow, even though it’s not required by the language, is said to be a convention
– capitalise the first letter of each word after the first.
• begin a program (class) name with an uppercase letter :
DemoProgram
• Variable names should begin with a lower case letter
firstName
totalSalesValue
Variable Names
• Variable names should be descriptive.
• Descriptive names allow the code to be more readable; therefore, the code is more maintainable.
• Which of the following is more descriptive?
double tr = 0.0725;
double salesTaxRate = 0.0725;
• Java programs should be self-documenting.
• More Java naming conventions can be found at:
http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html
Arithmetic Operators
Operator Meaning Type Example
+ Addition Binary total = cost + tax;
- Subtraction Binary cost = total – tax;
* Multiplication Binary tax = cost * rate;
/ Division Binary salePrice = original / 2;
% Modulus Binary remainder = value % 5;
Increment and Decrement Operators
• Shortcuts – use them sparingly
• The increment operator (++) adds one to its operand
• The decrement operator (--) subtracts one from its operand
count++; is equivalent to count = count + 1;
Constants
• A constant is a type of variable, but one whose value doesn’t change during the execution of a program.
• Constants can be named by assigning them to variables:
double base = 32.0;
double conversionFactor = 5.0 / 9.0;
• To prevent a constant from being changed, the reserved word final can be added to its declaration:
final double base = 32.0;
final double conversionFactor = 5.0 / 9.0;
Naming Constants
• A convention
• The names of constants are written entirely in uppercase letters, with underscores used to indicate boundaries between words:
final double BASE = 32.0;
final double CONVERSION_FACTOR = 5.0 / 9.0;
• Programs are easier to read and modify
• Inconsistencies and typographical errors are less likely
Input and Output
• Programs use both input and output
• Input is any data the program requires
– It can be already stored in the program or
– Entered by a user or
– Obtained from a file or other input device
• Output is any data produced by the program
– It can be displayed to the terminal or
– Written to a file or
– Used to operate devices
Displaying output on the screen
System.out.println( )
– Prints what is contained in the argument ie. between ( )
– println() always advances to the next line after displaying its argument
System.out.print( )
– Does not advance to the next line after displaying its argument
Displaying output
• Strings are any characters contained within double quotes
• They are often displayed as output
System.out.println(“This string will be displayed”);
• System.out.println( ) and System.out.print( ) can only display arguments of a single type egs Strings or variables
System.out.println(fahrenheitTemp); //displays the value of the variable
• To display mixed types we need to concatenate or join numeric types into a string
The plus operator
• So the plus operator (+) is used for addition and concatenation
• The function that the + operator performs depends on the type of the information on which it operates
• If both operands are strings, or if one is a string and one is a number, it performs string concatenation
• If both operands are numeric, it adds them
• The + operator is evaluated left to right
• Parentheses can be used to force the operation order
Escape Sequences
• Escape sequences start with / followed by a character and are inserted in a string being displayed to alter the display
• /n to start a new line:
System.out.println("A hop,/nand a jump");
A hop,
and a jump
• /t represents a tab space
System.out.println("John’s total:/t " + salesTotal);
John’s total: 225
二、classes, objects, methods
String class
• The String class is one of the most important prewritten classes that come with Java
• Every character string delimited by double quotation marks, represents a String object
• Note that class names always start with a capital letter
• A variable either holds
– a primitive type, int totalValue;
– or it holds an object String title;
• A class name can be thought of as a type to declare an object
String title;
title = "Java Software Solutions”;
• Or just like primitive variables, combine the 2 steps
String title = "Java Software Solutions";
Methods
• Methods are easy to recognise –
– An identifier that is always followed by ( )
• Once an object has been created, we can do things to it by calling the methods in the object’s class
• In general a method call takes this form:
object . method-name (parameters)
• Parameters (or arguments) are data that the method requires
• Methods may require
– no parameter, one parameter, many parameters
Class Methods
• Some methods can be invoked through the class name, instead of through an object of the class
• These methods are called class methods or static methods
• The Math class contains many static methods, providing various mathematical functions, such as
– absolute value, trigonometry functions, square root, etc.
• These methods are invoked by the class name
Class . method-name (parameters)
Using the Result of a Method Call
• The value returned by a method can be saved in a variable:
double y = Math.abs(x);
• Or use the result returned by a method directly, without first saving it in a variable.
double z = Math.sqrt(Math.abs(x));
System.out.println(Math.sqrt(2.0));
Packages/Classes
Classes are in packages
• Import the classes you need at the start of the program
import javax.swing.JOptionPane; or
import javax.swing.*;
Dialog Boxes
• A dialog box is a graphical window that pops up on top of any currently active window for the user
• Import the JOptionPane class from the swing package
import javax.swing.JOptionPane; or
import javax.swing.*;
Getting Input
To display a dialog box with the specified message and an input text field. The contents of the text field are returned.
• For example
String numStr = JOptionPane.showInputDialog ("Enter an integer:");
Displaying an Output Message
• To display a dialog box containing the specified message. (null centres the box on the screen)
• For example
JOptionPane.showMessageDialog (null, result);
Arithmetic promotion
• Arithmetic promotion happens automatically when operators in expressions are different data types
• Java converts operands to a type that will safely accommodate both values
• For expressions using integer and floating-point values:
anInteger = aDouble * anInteger;
– The integer value is temporarily converted to a double type
– The operation is performed
– The result is a double
– It is stored according to the receiving variable type
Wrapper Classes
• Contain static methods that convert Strings to the associated type eg.
static int parseInt (String str)
static double parseDouble (String str)
• eg Integer and Double classes methods convert an integer or double stored in a String :
String aString = “ 123” ;
int num1 = Integer.parseInt (aString);
String anotherString = “ 123.999” ;
double num2 = Double.parseDouble(anotherString);
-- fundamentals of java