Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Java
Features
• strongly-typed language
• object-oriented
• encapsulation enforced
• compiled before executed
• more difficult to learn than Python, but
safer for large program development and
maintenance
Hello World!
public class HelloWorld {
public static void main (String[] args) {
System.out.println(“Hello World!”);
}
}
How to run on fissure
save in file: HelloWorld.java
compile with: javac HelloWorld.java
execute with: java HelloWorld
output (sent to screen):
Hello World!
Contrast to Python
from within the interpreter:
print “Hello World!”
or save in file: HelloWorld.py
and execute with: python HelloWorld.py
Java: so complicated?
all code must belong to a class
program execution begins in method
main() of the “main” class
classes and methods have visibility
modifiers (encapsulation)
method return value must be declared
… not really.
public class HelloWorld {
public static void main (String[ ] args) {
System.out.println(“Hello World!”);
}
}
Some minor points
class and method bodies must be
enclosed by left { and right } brackets
statements must end with a semi-colon ;
no problem, the javac compiler will
complain if you forget, and some IDEs
help you get it right
good news: indentation not important
other than for style
Compiler checks these
public class HelloWorld {
public static void main (String[ ] args) {
System.out.println(“Hello World!”);
}
}
Another example
class Counter:
# from Python Review #1
def __init__(self):
self.value = 0
# dynamic typing
def step(self):
self.value += 1
def current(self):
return self.value
Testing Counter
# Testing the class definition:
c = Counter()
print “initial value”, c.current()
c.step()
print “after one step”, c.current()
# or ...
print “after one step”, c.value
# ... because Python does not enforce encapsulation!
Counter in Java
public class Counter {
private int value;
public Counter () {
this.value = 0;
}
public void step() {
this.value += 1;
}
public int current() {
return this.value;
}
}
// static typing
// encapsulation enforced
TestCounter in Java
public class TestCounter {
public static void main (String[] args) {
Counter c = new Counter();
System.out.println(“initial value ” + c.current());
c.step();
System.out.println(“after one step ” + c.current());
// but not ...
// System.out.println(“after one step ” + c.value);
}
// ... because Java enforces encapsulation!
}
Compile, then execute
# note the order of compilation
javac Counter.java TestCounter.java
# class with main() is executed
java TestCounter