Slide navigation: Forward with space bar, → arrow key, or PgDn. Backwards with ← or PgUp.
Copyright © Cay S. Horstmann 2016
public class FirstSample { public static void main(String[] args) { System.out.println("We will not use 'Hello, World!'"); } }
Main
≠ main
.public
, static
, etc.{
}
are used for blocks.FirstSample.java
.System.out.println("We will not use 'Hello, World!'");
object.method(parameters)
System.out.println();
// like this
/* like this ... */
/** * This is the first sample program in Core Java Chapter 3 * @version 1.01 1997-03-22 * @author Gary Cornell */
/* ... */
comments do not nest.
|
4 bytes |
–2,147,483,648 to 2,147,483, 647 (just over 2 billion) |
|
2 bytes |
–32,768 to 32,767 |
|
8 bytes |
–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
|
1 byte |
–128 to 127 |
4000000000L
0xCAFE
0b1111_0100_0010_0100_0000
|
4 bytes |
Approximately ±3.40282347E+38F (6–7 significant decimal digits) |
|
8 bytes |
Approximately ±1.79769313486231570E+308 (15 significant decimal digits) |
float
literals: 0.5F
float
if a library requires it.Double.POSITIVE_INFINITY
, Double.NEGATIVE_INFINITY
, Double.NaN
.char
Typechar
values:
A
has “code point” U+0041 and is encoded as a single char
value (hex 0041 or decimal 65).𝕆
has “code point” U+1D546 and is encoded by two
code units with hex values D835 DD46.char
unless you know that you won't run into Unicode characters ≥ U+10000.'A'
, '\n'
, '\u2122'
.boolean
Typefalse
, true
.int
and boolean
.int
, long
, short
, byte
double
, float
char
boolean
int vacationDays;
int vacationDays = 12;
=
operator:
vacationDays = 11;
final
:
final int vacationDays = 12;
+
, -
, *
, /
/
and %
(with integer operands):
15 / 2
is 7
.15 % 2
is 1
.15.0 / 2
is 7.5
.Math.sqrt(x)
is √ x.Math.pow(a, b)
is abMath.floorMod(a, b)
is like a % b
with better behavior for negative values:
Math.floorMod(-15, 2)
is 1
.Math.sin
, Math.log
, ...double x = 9.997; int nx = (int) x; int rx = (int) Math.round(x)
n += 4; // Same as n = n + 4
-=
, *=
, /=
, %=
, and so on.n++; n--;
==
, !=
, <
, <=
, >
, >=
boolean
operators: &&
, ||
, !
&
, |
, ^
, ~
, >>
, >>>
, <<
x < y ? x : y
enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE };
Size s = Size.MEDIUM;
s
can only hold size values or null
.jshell
is a part of Java 9.jshell
and hit the Enter key.Math.sqrt(1764)
and hit the Enter key.$1 + 1
$1
$2
and so on."Hello".
and then hit the Tab key.
toU
and hit the Tab key again.
toUpperCase
method is completed.new Random()
, then Shift+Tab, then the V key (unshifted).Instant
, then Shift+Tab, then the I key.var
instead of type for local variables:
var counter = 0; // anint
var message = "Greetings, earthlings!"; // aString
counter = 0.5; // Error—can't assign adouble
to anint
var traces = Thread.getAllStackTraces(); // a Map<Thread,StackTraceElement[]>
"Java\u2122"
.String
class.substring
method to extract substrings:
String greeting = "Hello"; String s = greeting.substring(0, 3);
s.substring(a, b)
has length b
- a
.+
) joins strings:
String expletive = "Expletive"; String PG13 = "deleted"; String message = expletive + PG13;
int age = 13; String rating = "PG" + age;
greeting.substring(0, 3)
, greeting + "!"
don't change greeting
.greeting = greeting.substring(0, 3) + "p!";
"Hello".equals(greeting) "Hello".equalsIgnoreCase(greeting)
==
operator.
"Hello".substring(0, 3) == "Hel" // probably false
""
has length 0.null
indicates no string at all.s.length()
is the number of code units (not Unicode characters).s.charAt(i)
is the i
th code unit.i
th code point:
int index = s.offsetByCodePoints(0, i); int cp = s.codePointAt(index);
int[] codePoints = str.codePoints().toArray();
String
methods.trim
yields a new string, trimming leading and trailing white space.toLowerCase
yields a new string that coverts all uppercase characters to lowercase.indexOf
, lastIndexOf
find the location of a substring.Scanner
:
Scanner in = new Scanner(System.in);
nextLine
, next
, nextInt
, nextDouble
to read input:
int age = in.nextInt();
import java.util.*;
printf
for formatted printing:
System.out.printf("Price:%8.2f", 10000.0 / 3.0); // Prints Price: 3333.33
f
for floating-point, d
for integer, s
for strings and other objects.System.out.printf("%(,.2f", -10000.0 / 3.0); // prints (3,333.33)
String.format
if you don't want to print:
String message = String.format("Hello, %s. Next year, you'll be %d", name, age);
Scanner in = new Scanner(Paths.get("myfile.txt"), "UTF-8");
PrintWriter out = new PrintWriter("myfile.txt", "UTF-8"); out.println(...);
java.io
, java.nio.path
packages.main
like this:
public static void main(String[] args) throws IOException { Scanner in = new Scanner(Paths.get("myfile.txt"), "UTF-8"); . . . }
if
Statementif (yourSales >= 2 * target) { performance = "Excellent"; bonus = 1000; } else if (yourSales >= 1.5 * target) { performance = "Fine"; bonus = 500; } else if (yourSales >= target) { performance = "Satisfactory"; bonus = 100; } else { System.out.println("You're fired"); }
while
Statementwhile (balance < goal) { balance += payment; double interest = balance * interestRate / 100; balance += interest; years++; } System.out.println(years + " years.");
do/while
Statementdo { balance += payment; double interest = balance * interestRate / 100; balance += interest; year++; // print current balance . . . // ask if ready to retire and get input . . . } while (input.equals("N"));
for
Statementfor (int i = 1; i <= 10; i++) System.out.println(i);
switch
StatementScanner in = new Scanner(System.in); System.out.print("Select an option (1, 2, 3, 4) "); int choice = in.nextInt(); switch (choice) { case 1: . . . break; case 2: . . . break; case 3: . . . break; case 4: . . . break; default: // bad input . . . break; }
break
Statementwhile (years <= 100) { balance += payment; double interest = balance * interestRate / 100; balance += interest; if (balance >= goal) break; years++; }
break
by placing the remainder inside if
and adding another termination condition:
while (years <= 100 && balance < goal) { balance += payment; double interest = balance * interestRate / 100; balance += interest; if (balance < goal) years++; }
break
” lets you break out of multiple nested loops.continue
StatementScanner in = new Scanner(System.in); while (sum < goal) { System.out.print("Enter a number: "); n = in.nextInt(); if (n < 0) continue; sum += n; // not executed if n < 0 }
n < 0
, then sum < goal
is checked next.continue
by placing the remainder inside if
.continue
” lets you continue in an outer loop.int
and double
doesn't suffice, use BigInteger
or BigDecimal
.int
into a BigInteger
:
BigInteger a = BigInteger.valueOf(100);
add
and multiply
to combine big numbers:
BigInteger c = a.add(b); // c = a + b BigInteger d = c.multiply(b.add(BigInteger.valueOf(2))); // d = c * (b + 2)
BigInteger.ZERO
, BigInteger.ONE
, and BigInteger.TEN
BigInteger.TWO
BigInteger.THREE
in Java 10, but there is always hope for Java 11.int[]
is an array of integers.int[] a;
new
operator creates array:
int[] a = new int[100];
a.length
- 1.[]
to access elements:
for (int i = 0; i < a.length; i++) System.out.println(a[i]);
for (int element : a) System.out.println(element);
int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };
new int[] { 17, 19, 23, 29, 31, 37 }
int[] luckyNumbers = smallPrimes; luckyNumbers[5] = 12; // now smallPrimes[5] is also 12
Arrays.copyOf
to make a true copy:
int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length);
int[][]
is an array of arrays or a two-dimensional array:
int[][] magicSquare = { {16, 3, 2, 13}, {5, 10, 11, 8}, {9, 6, 7, 12}, {4, 15, 14, 1} };
int[][] magicSquare = new int[ROWS][COLUMNS];
magicSquare[1][2]
is 11.for (int[] row : magicSquare) for (int element : row) do something with value
int[][] triangle = new int[ROWS][]; for (int i = 0; i < ROWS; i++) triangle[i] = new int[i + 1];