Java 1
Java 1
0
Light Version
Overview
• Enumerated types • Static Import
• Automatic Boxing and Unboxing of • Formatted Output
Primitive Values • Formatted Input
• Enhanced for loop
Enumerated Types
• An enumerated type defines a finite set of symbolic names and their values.
• Standard approach is the int enum pattern (or the analogous String enum pattern):
Enum Constructors
• Each constant declaration can be followed by an argument list that is passed to the
constructor of the enum type having the matching parameter signature.
– An implicit standard constructor is created if no constructors are provided for the
enum type.
– As an enum cannot be instantiated using the new operator, the constructors cannot
be called explicitly.
public enum Meal {
BREAKFAST(7,30), LUNCH(12,15), DINNER(19,45);
Meal(int hh, int mm) {
assert (hh >= 0 && hh <= 23): "Illegal hour.";
assert (mm >= 0 && hh <= 59): "Illegal mins.";
this.hh = hh;
this.mm = mm;
}
// Time for the meal.
private int hh;
private int mm;
public int getHour() { return this.hh; }
public int getMins() { return this.mm; }
}
• Enum types are based on the java.lang.Enum class which provides the default
behavior.
• Enums cannot declare methods which override the final methods of the
java.lang.Enum class:
– clone(), compareTo(Object), equals(Object), getDeclaringClass(),
hashCode(), name(), ordinal().
– The final methods do what their names imply, but the clone() method throws an
CloneNotSupportedException, as an enum constant cannot be cloned.
• Note that the enum constants must be declared before any other declarations in an enum type.
// Boxing
Boolean boolRef = boolVal;
Byte bRef = (byte) 2; // cast required as int not assignable to Byte
Short sRef = (short) 2; // cast required as int not assignable to Short
Character cRef = '2';
Integer iRef = 2;
// Integer iRef1 = s; // short not assignable to Integer
// Unboxing
boolean boolVal1 = boolRef;
byte b1 = bRef;
short s1 = sRef;
char c1 = cRef;
int i1 = iRef;
• Casting Conversions:
Integer iRef = (Integer) 2; // Boxing followed by identity cast
int i = (int) iRef; // Unboxing followed by identity cast
// Long lRef = (Long) 2; // int not convertible to Long
• In the switch statement, the switch expression can be Character, Byte, Short or
Integer.
// Constants
final short ONE = 1;
final short ZERO = 0;
final short NEG_ONE = -1;
• In the while, do-while and for statements, the condition can be Boolean.
Boolean expr = true;
while (expr)
expr = !expr;
int[] ageInfo = {12, 30, 45, 55}; int[] ageInfo = {12, 30, 45, 55};
int sumAge = 0; int sumAge = 0;
for (int i = 0; i < ageInfo.length; i++) for (int element : ageInfo)
sumAge += ageInfo[i]; sumAge += element;
– Note that an array element of a primitive value cannot be modified in the for(:)
loop.
• Note that syntax of the for(:) loop does not use an iterator for the collection.
• The for(:) loop does not allow elements to be removed from the collection.
STATIC IMPORT
Note that import from the unnamed package (a.k.a. default package) is not permissible.
class Factory {
public static void main(String[] args) {
States[] states = {
IDLE, BUSY, IDLE, BLOCKED
};
for (States s : states)
out.println(s);
}
}
FORMATTED OUTPUT
• Format string syntax provides support for layout justification and alignment, common
formats for numeric, string, and date/time data, and locale-specific output.
%[argument_index$][flags][width][.precision]conversion
• The characters %, $ and. have special meaning in the context of the format specifier.
• The optional argument_index is a decimal integer indicating the position of the
argument in the argument list. The first argument is referenced by "1$", the second by
"2$", and so on.
• The optional flags is a set of characters that modify the output format. The set of valid
flags depends on the conversion.
• The optional width is a decimal integer indicating the minimum number of characters
to be written to the output.
• The optional precision is a decimal integer usually used to restrict the number of
characters. The specific behavior depends on the conversion.
• The required conversion is a character indicating how the argument should be
formatted. The set of valid conversions for a given argument depends on the
argument's data type.
Conversion Categories
General (’b’, ’B’, ’h’ , ’H’,’s’, ’S’):
May be applied to any argument type.
Character (’c’, ’C’):
May be applied to basic types which represent Unicode characters: char,
Character, byte, Byte, short, and Short.
Numeric:
Integral (’d’, ’o’, ’x’, ’X’):
May be applied to integral types: byte, Byte, short, Short, int and Integer, long,
Long, and BigInteger.
Floating Point (’e’, ’E’, ’f’, ’g’, ’G’, ’a’, ’A’):
May be applied to floating-point types: float, Float, double, Double, and
BigDecimal.
Percent (’%’): produces a literal '%', i.e. "%%" escapes the '%'character.
Line Separator (’n’): produces the platform-specific line separator, i.e. "%n".
'h','H' general If the argument arg is null, then the result is "null". Otherwise, the result is obtained
by invoking Integer.toHexString(arg.hashCode()).
's','S' general If the argument arg is null, then the result is "null". If arg implements Formattable,
then arg.formatTo() is invoked. Otherwise, the result is obtained by invoking
arg.toString().
Flags
• y means the flag is supported for the indicated argument types.
Flag General Character Integral Floating Point Date/Time Description
'-' y y y y y The result will be left-justified.
'#' y1 - y3 y - The result should use a conversion-
dependent alternate form.
'+' - - y4 y - The result will always include a sign.
' ' - - y4 y - The result will include a leading
space for positive values.
'0' - - y y - The result will be zero-padded.
',' - - y2 y5 - The result will include locale-specific
grouping separators.
'(' - - y4 y5 - The result will enclose negative
numbers in parentheses.
1 4
Depends on the definition of Formattable. For 'd', 'o', 'x' and 'X' conversions applied to
2 BigInteger or 'd' applied to byte, Byte, short,
For 'd' conversion only. Short, int , Integer, long, and Long.
3 For 'o', 'x' and 'X' conversions only.
5
For 'e', 'E', 'g' and 'G' conversions only.
Formatted Input
• Class java.util.Scanner implements a simple text scanner (lexical analyzer) which
uses regular expressions to parse primitive types and strings from its source.
• A Scanner converts the input from its source into tokens using a delimiter pattern,
which by default matches whitespace.
• The tokens can be converted into values of different types using the various next()
methods.
Scanner lexer1 = new Scanner(System.in); // Connected to standard input.
int i = lexer1.nextInt();
...
Scanner lexer2 = new Scanner(new File("myLongNumbers")); (1) Construct a scanner.
while (lexer2.hasNextLong()) { // (2) End of input? May block.
long aLong = lexer2.nextLong(); // (3) Deal with the current token. May block.
}
lexer2.close(); // (4) Closes the scanner. May close the source.
• Before parsing the next token with a particular next() method, for example at (3), a
lookahead can be performed by the corresponding hasNext() method as shown at (2).
• The next() and hasNext() methods and their primitive-type companion methods
(such as nextInt() and hasNextInt()) first skip any input that matches the
delimiter pattern, and then attempt to return the next token.
Constructing a Scanner
• A scanner must be constructed to parse text.
Scanner(Type source)
Returns an appropriate scanner. Type can be a String, a File, an InputStream, a
ReadableByteChannel, or a Readable (implemented by CharBuffer and various
Readers).
String nextLine()
Advances this scanner past the current line and
returns the input that was skipped.
{
String input = "123 45,56 false 567 722 blabla";
Scanner lexer = new Scanner(input);
out.println(lexer.hasNextInt()); true
out.println(lexer.nextInt()); 123
out.println(lexer.hasNextDouble()); true
out.println(lexer.nextDouble()); 45.56
out.println(lexer.hasNextBoolean()); true
out.println(lexer.nextBoolean()); false
out.println(lexer.hasNextInt()); true
out.println(lexer.nextInt()); 567
out.println(lexer.hasNextLong()); true
out.println(lexer.nextLong()); 722
out.println(lexer.hasNext()); true
out.println(lexer.next()); blabla
out.println(lexer.hasNext()); false
lexer.close();
}