new Greeter("World")
public Greeter() { name = "Java"; }
new Greeter("World").sayHello()
Greeter worldGreeter = new Greeter("World");
String greeting = worldGreeter.sayHello();
javac GreeterTest.javaNote that Greeter.java is automatically compiled.
java GreeterTest
y = Math.sqrt(x);
/** Computes and displays n! */ public class Factorial { /** main function * @param args the command line arguments, stored in a String array */ public static void main(String[] args) { int f = 1; // convert command line argument to integer type: int n = Integer.parseInt(args[0]); // calculate factorial while (n > 1) { f = f * n; n--; } // display result: System.out.println(args[0] + "! = " + f); } }
type nameVariable scope: section of code where the variable's simple name can be used.
Example:
class Myclass { private int p; // .... public void method() { int i; for (i=0; i<10; i++) { int j = i * p; // ... } System.out.println("i=" + i); System.out.println("j=" + j); } } }
float pi = 3.1415;
final float e = 2.71828183;
Keyword | Description | Size/Format |
---|---|---|
(integers) | ||
byte |
Byte-length integer | 8-bit two's complement |
short |
Short integer | 16-bit two's complement |
int |
Integer | 32-bit two's complement |
long |
Long integer | 64-bit two's complement |
(real numbers) | ||
float |
Single-precision floating point | 32-bit IEEE 754 |
double |
Double-precision floating point | 64-bit IEEE 754 |
(other types) | ||
char |
A single character | 16-bit Unicode character |
boolean |
A boolean value (true or false ) |
true or false |
Arrays, classes, and interfaces are reference types.
Greeter g1 = new Greeter("Students"); Greeter g2 = g1; int v[] = new int[100];
Statement Type | Keyword |
---|---|
looping |
while , do-while , for
|
decision making |
if-else , switch-case
|
exception handling |
try-catch-finally , throw
|
branching |
break , continue , label: , return
|
if (logical condition) { // condition is true } else { // condition is false }
Employee emp; ..... if (emp.salary() < 18000) { tax = 0.10; } else { tax = 0.15; }
while (logical condition) { // repeat while condition is true }Example: :
int n = 100; int sum = 0; while (n > 0) { sum += n; n--; }
do { // repeat statement block between { and } while condition is true } while (condition);Example:
int n = 100; int sum = 0; do { sum += n; n--; } while (n > 0);
for (initializers; condition; updates) { // repeat statements while condition is true }
Variable can be declared in
for loop:
for (int i = 1; i <= n; i++)
{
. . .
}
// i no longer defined here
Greeter worldGreeter = new Greeter("World");An object reference describes the location in JVM memory of an object
Greeter anotherGreeter = worldGreeter;
anotherGreeter.setName("Dave");changes the object referred by both worldGreeter and anotherGreeter.
// now worldGreeter.sayHello() returns "Hello, Dave!"
protected Object clone() throws CloneNotSupportedException
// new Date object with current time Date dateNow = new Date(); ... // create identical copy of nowDate Date dateCopy = (Date) dateNow.clone();dateNow and dateCopy reference each a different object,
worldGreeter = null;
if (worldGreeter == null) . . .
... worldGreeter = null; ... worldGreeter.sayHello(); // this statement causes the exception
public boolean equals(Greeter other)
{
if (this == other) return true;
return name.equals(other.name);
}
public Greeter(String name)Note that instance variables is qualified with this to avoid name clashes with method parameters.
{
this.name = name;
}
new
operator.
new
returns a reference to the new object.garbage collector
. (quick intro
here).finalize()
method, Object
. This method may implement custom
code for deallocating System.gc();
method call.
public class DB // ineffective method to calculate dB: public static void toDecibell(double x) { x = 10.0 * Math.log10(x); // change formal parameter value } }; ....... power = 100.0; // 100 Watts. DB.toDecibell(power); // conversion to dBW fails. power == 100 after call
public void copyNameTo(Greeter other) { other.name = this.name; } ...... Greeter worldGreeter = new Greeter("World");
Greeter daveGreeter = new Greeter("Dave");
worldGreeter.copyNameTo(daveGreeter);
public void copyLengthTo(int n)
{
n = name.length();
}
public void copyGreeterTo(Greeter other)
{
other = new Greeter(name);
}
int length = 0;
worldGreeter.copyLengthTo(length); // length still 0
worldGreeter.copyGreeterTo(daveGreeter) // daveGreeter unchanged
java.util
javax.swing
com.sun.misc
edu.sjsu.cs.cs151.alice
package edu.sjsu.cs.cs151.alice;
public class Greeter { . . . }
java.util.ArrayList
javax.swing.JOptionPane
import java.util.Scanner;
. . .
Scanner a; // i.e. java.util.Scanner
import java.util.*;
import java.*.*; // NO
import java.util.*;
import java.sql.*;
. . .
java.util.Date d; // Date also occurs in java.sql
edu.sjsu.cs.sjsu.cs151.alice.Greetermust be in subdirectory
basedirectory/edu/sjsu/cs/sjsu/cs151/alice
javac edu/sjsu/cs/sjsu/cs151/alice/Greeter.javaor
javac edu\sjsu\cs\sjsu\cs151\alice\Greeter.java
java edu.sjsu.cs.cs151.alice.GreeterTest
java-code/Ch1/hw-packaged/
. javac edu\sjsu\cs\cs151\alice\Greeter.java
java-code/Ch1/hw-packaged/
. javac edu\fau\cse\cop4331\GreeterTest.java
java edu.fau.cse.cop4331.GreeterTest
javadoc -d javadocs -private edu\sjsu\cs\cs151\alice\Greeter.java edu\fau\cse\cop4331\GreeterTest.java
.
String name = null;
int n = name.length(); // ERROR
Exception in thread "main" java.lang.NullPointerException
at Greeter.sayHello(Greeter.java:25)
at GreeterTest.main(GreeterTest.java:6)
public double sqrt(double x) { if (x < 0.0) throw new IllegalArgumentException("invalid parameter: negative value"); .... }
java.lang.Exception
IOException, FileNotFoundException
,
...)
IndexOutOfBoundsException
are not checked.
public void read(String filename) throws FileNotFoundException
{
FileReader reader = new FileReader(filename);
. . .
}
public void read(String filename)
throws IOException, ClassNotFoundException
public static void main(String[] args)
throws IOException, ClassNotFoundException
try
{
code that might throw an IOException
}
catch (IOException exception)
{
take corrective action
}
exception.printStackTrace();
System.exit(1);
FileReader reader = null;
try
{
reader = new FileReader(name);
...
}
finally
{
if (reader != null) reader.close();
}
UrlDump
UrlDumpException
from
except/UrlDumpException.java
UrlDump
from
except/UrlDump.java
except/javadocs/index.html
.
String
objects are immutable.
"Hello, " + name
int n = 7;
String greeting = "Hello, " + n;
// yields "Hello, 7"
Date now = new Date();
String greeting = "Hello, " + now;
// concatenates now.toString()
// yields "Hello, Wed Jan 17 16:57:18 PST 2001"
String input = "7";
int n = Integer.parseInt(input);
// yields integer 7
ArrayList<String> countries = new ArrayList<String>();
countries.add("Belgium");
countries.add("Italy");
countries.add("Thailand");
ArrayList<String> countries = new ArrayList<>();
countries.add("Belgium");
countries.add("Italy");
countries.add("Thailand");
for (String country : countries) . . .
LinkedList<String> countries = new LinkedList<String>();
countries.add("Belgium");
countries.add("Italy");
countries.add("Thailand");
for (int i = 0; i < numbers.length; i++)
numbers = new int[0];
int[][] table = new int[10][20];
int t = table[i][j];
public class Greeter
{
. . .
private static Random generator;
}
public class Math
{
. . .
public static final double PI = 3.14159265358979323846;
}
public static Greeter getRandomInstance()
{
if (generator.nextBoolean()) // note: generator is static field
return new Greeter("Mars");
else
return new Greeter("Venus");
}
Greeter g = Greeter.getRandomInstance();
name
sayHello
Greeter
ArrayList
PI
MAX_VALUE
String getName()
void setName(String newValue)
public boolean isPolite()
public void setPolite(boolean newValue)
public String sayHello()
{
return "Hello, " + name + "!";
}
public String sayHello() {
return "Hello, " + name + "!";
}
public class Greeter
{
private String name;
public Greeter(String aName) { . . . }
. . .
}
Good: if (x > Math.sqrt(y))
Bad: if(x>Math.sqrt (y))
Good: int[] numbers
Bad: int numbers[]
Good: h = HASH_MULTIPLIER * h + val[off];
Bad: h = 31 * h + val[off];