Java Tutorial for
Complete Beginners (John Purcell)
Section 2
Lecture 5 : A Hello World Program
public class Application {
public static void main(String[] args) {
[Link]("Hello World!");
Lecture 6 : Using Variables
public class Application {
public static void main(String[] args) {
int myNumber = 88;
short myShort = 847;
long myLong = 9797;
double myDouble = 7.3243;
float myFloat = 324.3f;
char myChar = 'y';
boolean myBoolean = false;
byte myByte = 127;
[Link](myNumber);
[Link](myShort);
[Link](myLong);
[Link](myDouble);
[Link](myFloat);
[Link](myChar);
[Link](myBoolean);
[Link](myByte);
Lecture 7: Strings: Working With Text
public class Application {
public static void main(String[] args) {
int myInt = 7;
String text = "Hello";
String blank = " ";
String name = "Bob";
String greeting = text + blank + name;
[Link](greeting);
[Link]("Hello" + " " + "Bob");
[Link]("My integer is: " + myInt);
double myDouble = 7.8;
[Link]("My number is: " + myDouble + ".");
Output: Hello Bob
Hello Bob
My integer is: 7
My number is: 7.8.
Lecture 8: While Loops
public class Application {
public static void main(String[] args) {
int value = 0;
while(value < 10)
[Link]("Hello " + value);
value = value + 1;
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
Hello 6
Hello 7
Hello 8
Hello 9
Lecture 9: For Loops
public class Application {
public static void main(String[] args) {
for(int i=0; i < 5; i++) {
[Link]("The value of i is: %dn", i);
}
}
}
The value of i is: 0
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
Lecture 10: If
public class Application {
public static void main(String[] args) {
// Some useful conditions:
[Link](5 == 5);
[Link](10 != 11);
[Link](3 < 6);
[Link](10 > 100);
// Using loops with "break":
int loop = 0;
while(true) {
[Link]("Looping: " + loop);
if(loop == 3) {
break;
}
loop++;
[Link]("Running");
}
}
}
true
true
true
false
Looping: 0
Running
Looping: 1
Running
Looping: 2
Running
Looping: 3
Lecture 11: Getting User input
import [Link];
public class App {
public static void main(String[] args) {
// Create scanner object
Scanner input = new Scanner([Link]);
// Output the prompt
[Link]("Enter a floating point value: ");
// Wait for the user to enter something.
double value = [Link]();
// Tell them what they entered.
[Link]("You entered: " + value);
Enter a floating point value:
5,6
You entered: 5.6
Lecture 12: Do…While
import [Link];
public class App {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
/*
[Link]("Enter a number: ");
int value = [Link]();
while(value != 5) {
[Link]("Enter a number: ");
value = [Link]();
}
*/
int value = 0;
do {
[Link]("Enter a number: ");
value = [Link]();
}
while(value != 5);
[Link]("Got 5!");
}
}
Lecture 13: Switch
import [Link];
public class Application {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Please enter a command: ");
String text = [Link]();
switch (text) {
case "start":
[Link]("Machine started!");
break;
case "stop":
[Link]("Machine stopped.");
break;
default:
[Link]("Command not recognized");
}
}
Lecture 14: Arrays
public class App {
public static void main(String[] args) {
int value = 7;
int[] values;
values = new int[3];
[Link](values[0]);
values[0] = 10;
values[1] = 20;
values[2] = 30;
[Link](values[0]);
[Link](values[1]);
[Link](values[2]);
for(int i=0; i < [Link]; i++) {
[Link](values[i]);
}
int[] numbers = {5, 6, 7};
for(int i=0; i < [Link]; i++) {
[Link](numbers[i]);
}
}
0
10
20
30
10
20
30
5
6
7
Lecture 15: Arrays of Strings
public class App {
public static void main(String[] args) {
// Declare array of (references to) strings.
String[] words = new String[3];
// Set the array elements (point the references
// at strings)
words[0] = "Hello";
words[1] = "to";
words[2] = "you";
// Access an array element and print it.
[Link](words[2]);
// Simultaneously declare and initialize an array of strings
String[] fruits = {"apple", "banana", "pear", "kiwi"};
// Iterate through an array
for(String fruit: fruits) {
[Link](fruit);
}
// "Default" value for an integer
int value = 0;
// Default value for a reference is "null"
String text = null;
[Link](text);
// Declare an array of strings
String[] texts = new String[2];
// The references to strings in the array
// are initialized to null.
[Link](texts[0]);
// ... But of course we can set them to actual strings.
texts[0] = "one";
}
you
apple
banana
pear
kiwi
null
null
Lecture 16: Multy-dimensional Arrays
public class App {
public static void main(String[] args) {
// 1D array
int[] values = {3, 5, 2343};
// Only need 1 index to access values.
[Link](values[2]);
// 2D array (grid or table)
int[][] grid = {
{3, 5, 2343},
{2, 4},
{1, 2, 3, 4}
};
// Need 2 indices to access values
[Link](grid[1][1]);
[Link](grid[0][2]);
// Can also create without initializing.
String[][] texts = new String[2][3];
texts[0][1] = "Hello there";
[Link](texts[0][1]);
// How to iterate through 2D arrays.
// first iterate through rows, then for each row
// go through the columns.
for(int row=0; row < [Link]; row++) {
for(int col=0; col < grid[row].length; col++) {
[Link](grid[row][col] + "\t");
}
[Link]();
}
// The last array index is optional.
String[][] words = new String[2][];
// Each sub-array is null.
[Link](words[0]);
// We can create the subarrays 'manually'.
words[0] = new String[3];
// Can set a values in the sub-array we
// just created.
words[0][1] = "hi there";
[Link](words[0][1]);
}
}
2343
4
2343
Hello there
3 5 2343
2 4
1 2 3 4
null
hi there
Lecture 17: Classes and Objects
class Person {
// Instance variables (data or "state")
String name;
int age;
// Classes can contain
// 1. Data
// 2. Subroutines (methods)
}
public class App {
public static void main(String[] args) {
// Create a Person object using the Person class
Person person1 = new Person();
[Link] = "Joe Bloggs";
[Link] = 37;
// Create a second Person object
Person person2 = new Person();
[Link] = "Sarah Smith";
[Link] = 20;
[Link]([Link]);
Joe Bloggs
Lecture 18: Methods
class Person {
// Instance variables (data or "state")
String name;
int age;
// Classes can contain
// 1. Data
// 2. Subroutines (methods)
void speak() {
for(int i=0; i<3; i++) {
[Link]("My name is: " + name + " and I am " + age + " years o
ld ");
}
}
void sayHello() {
[Link]("Hello there!");
}
}
public class App {
public static void main(String[] args) {
// Create a Person object using the Person class
Person person1 = new Person();
[Link] = "Joe Bloggs";
[Link] = 37;
[Link]();
[Link]();
// Create a second Person object
Person person2 = new Person();
[Link] = "Sarah Smith";
[Link] = 20;
[Link]();
[Link]();
[Link]([Link]);
}
}
My name is: Joe Bloggs and I am 37 years old
My name is: Joe Bloggs and I am 37 years old
My name is: Joe Bloggs and I am 37 years old
Hello there!
My name is: Sarah Smith and I am 20 years old
My name is: Sarah Smith and I am 20 years old
My name is: Sarah Smith and I am 20 years old
Hello there!
Joe Bloggs
Lecture 19: Getters and Return Values
class Person {
String name;
int age;
void speak() {
[Link]("My name is: " + name);
}
int calculateYearsToRetirement() {
int yearsLeft = 65 - age;
return yearsLeft;
}
int getAge() {
return age;
}
String getName() {
return name;
}
}
public class App {
public static void main(String[] args) {
Person person1 = new Person();
[Link] = "Joe";
[Link] = 25;
// [Link]();
int years = [Link]();
[Link]("Years till retirements " + years);
int age = [Link]();
String name = [Link]();
[Link]("Name is: " + name);
[Link]("Age is: " + age);
}
Years till retirements 40
Name is: Joe
Age is: 25
Lecture 20: Methos Parameters
class Robot {
public void speak(String text) {
[Link](text);
}
public void jump(int height) {
[Link]("Jumping: " + height);
}
public void move(String direction, double distance) {
[Link]("Moving " + distance + " in direction " + direction);
}
}
public class App {
public static void main(String[] args) {
Robot sam = new Robot();
[Link]("Hi I'm Sam");
[Link](7);
[Link]("West", 12.2);
String greeting = "Hello there";
[Link](greeting);
int value = 14;
[Link](value);
Hi I'm Sam.
Jumping: 7
Moving 12.2 metres in direction West
Hello there.
Jumping: 14
Lecture 21: Setters and this
class Frog {
private String name;
private int age;
public void setName(String name) {
[Link] = name;
}
public void setAge(int age) {
[Link] = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setInfo(String name, int age) {
setName(name);
setAge(age);
}
}
public class App {
public static void main(String[] args) {
Frog frog1 = new Frog();
//[Link] = "Bertie";
//[Link] = 1;
[Link]("Bertie");
[Link](1);
[Link]([Link]());
}
Bertie
Lecture 22: Constructors
class Machine {
private String name;
private int code;
public Machine() {
this("Arnie", 0);
[Link]("Constructor running!");
}
public Machine(String name) {
this(name, 0);
[Link]("Second constructor running");
// No longer need following line, since we're using the other constructor abo
ve.
//[Link] = name;
}
public Machine(String name, int code) {
[Link]("Third constructor running");
[Link] = name;
[Link] = code;
}
}
public class App {
public static void main(String[] args) {
Machine machine1 = new Machine();
Machine machine2 = new Machine("Bertie");
Machine machine3 = new Machine("Chalky", 7);
}
Third constructor running
Constructor running!
Third constructor running
Second constructor running
Third constructor running
Lecture 23: Static (and Final)
class Thing {
public final static int LUCKY_NUMBER = 7;
public String name;
public static String description;
public static int count = 0;
public int id;
public Thing() {
id = count;
count++;
}
public void showName() {
[Link]("Object id: " + id + ", " + description + ": " + name);
}
public static void showInfo() {
[Link](description);
// Won't work: [Link](name);
}
}
public class App {
public static void main(String[] args) {
[Link] = "I am a thing";
[Link]();
[Link]("Before creating objects, count is: " + [Link]);
Thing thing1 = new Thing();
Thing thing2 = new Thing();
[Link]("After creating objects, count is: " + [Link]);
[Link] = "Bob";
[Link] = "Sue";
[Link]();
[Link]();
[Link]([Link]);
[Link](Thing.LUCKY_NUMBER);
}
I am a thing
Before creating objects, count is: 0
After creating objects, count is: 2
Object id: 0, I am a thing: Bob
Object id: 1, I am a thing: Sue
3.141592653589793
7
Lecture 24: StringBuilder and String Formatting
public class App {
public static void main(String[] args) {
// Inefficient
String info = "";
info += "My name is Bob.";
info += " ";
info += "I am a builder.";
[Link](info);
// More efficient.
StringBuilder sb = new StringBuilder("");
[Link]("My name is Sue.");
[Link](" ");
[Link]("I am a lion tamer.");
[Link]([Link]());
// The same as above, but nicer ....
StringBuilder s = new StringBuilder();
[Link]("My name is Roger.")
.append(" ")
.append("I am a skydiver.");
[Link]([Link]());
///// Formatting //////////////////////////////////
// Outputting newlines and tabs
[Link]("Here is some [Link] was a [Link] was a newline.");
[Link](" More text.");
// Formatting integers
// %-10d means: output an integer in a space ten characters wide,
// padding with space and left-aligning (%10d would right-align)
[Link]("Total cost %-10d; quantity is %dn", 5, 120);
// Demo-ing integer and string formatting control sequences
for(int i=0; i<20; i++) {
[Link]("%-2d: %sn", i, "here is some text");
}
// Formatting floating point value
// Two decimal place:
[Link]("Total value: %.2fn", 5.6874);
// One decimal place, left-aligned in 6-character field:
[Link]("Total value: %-6.1fn", 343.23423);
// You can also use the [Link]() method if you want to retrieve
// a formatted string.
String formatted = [Link]("This is a floating-point value: %.3f", 5.12
345);
[Link](formatted);
// Use double %% for outputting a % sign.
[Link]("Giving it %d%% is physically impossible.", 100);
}
My name is Bob. I am a builder.
My name is Sue. I am a lion tamer.
My name is Roger. I am a skydiver.
Here is some text. That was a tab.
That was a newline. More text.
Total cost 5 ; quantity is 120
0 : here is some text
1 : here is some text
2 : here is some text
3 : here is some text
4 : here is some text
5 : here is some text
6 : here is some text
7 : here is some text
8 : here is some text
9 : here is some text
10: here is some text
11: here is some text
12: here is some text
13: here is some text
14: here is some text
15: here is some text
16: here is some text
17: here is some text
18: here is some text
19: here is some text
Total value: 5.69
Total value: 343.2
This is a floating-point value: 5.123
Giving it 100% is physically impossible.
Lecture 25: toString
class Frog {
private int id;
private String name;
public Frog(int id, String name) {
[Link] = id;
[Link] = name;
}
public String toString() {
return [Link]("%-4d: %s", id, name);
/*
StringBuilder sb = new StringBuilder();
[Link](id).append(": ").append(name);
return [Link]();
*/
}
}
public class App {
public static void main(String[] args) {
Frog frog1 = new Frog(7, "Freddy");
Frog frog2 = new Frog(5, "Roger");
[Link](frog1);
[Link](frog2);
}
}
7 : Freddy
5 : Roger
Lecture 26: Inheritance
public class App {
public static void main(String[] args) {
Machine mach1 = new Machine();
[Link]();
[Link]();
Car car1 = new Car();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]:
public class Machine {
protected String name = "Machine Type 1";
public void start() {
[Link]("Machine started.");
}
public void stop() {
[Link]("Machine stopped.");
}
}
[Link]:
public class Car extends Machine {
@Override
public void start() {
[Link]("Car started");
}
public void wipeWindShield() {
[Link]("Wiping windshield");
}
public void showInfo() {
[Link]("Car name: " + name);
}
}
Machine started.
Machine stopped.
Car started
Wiping windshield
Car name: Machine Type 1
Machine stopped.
Lecture 27: Packages
[Link]:
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
Fish fish = new Fish();
Seaweed weed = new Seaweed();
}
[Link]:
package ocean;
public class Fish {
[Link]:
package [Link];
public class Algae {
}
[Link]:
package [Link];
public class Seaweed {
[Link]:
package [Link];
public class Aquarium {
Lecture 28: Interfaces
[Link]:
public class App {
public static void main(String[] args) {
Machine mach1 = new Machine();
[Link]();
Person person1 = new Person("Bob");
[Link]();
Info info1 = new Machine();
[Link]();
Info info2 = person1;
[Link]();
[Link]();
outputInfo(mach1);
outputInfo(person1);
}
private static void outputInfo(Info info) {
[Link]();
}
[Link]:
public class Machine implements Info {
private int id = 7;
public void start() {
[Link]("Machine started.");
}
public void showInfo() {
[Link]("Machine ID is: " + id);
}
}
[Link]:
public class Person implements Info {
private String name;
public Person(String name) {
[Link] = name;
}
public void greet() {
[Link]("Hello there.");
}
@Override
public void showInfo() {
[Link]("Person name is: " + name);
}
}
[Link]:
public interface Info {
public void showInfo();
}
[Link]:
public interface IStartable {
public void start();
public void stop();
}
Machine started.
Hello there.
Machine ID is: 7
Person name is: Bob
Machine ID is: 7
Person name is: Bob
Lecture 29: Public, Private, Protected
[Link]:
import [Link];
/*
* private --- only within same class
* public --- from anywhere
* protected -- same class, subclass, and same package
* no modifier -- same package only
*/
public class App {
public static void main(String[] args) {
Plant plant = new Plant();
[Link]([Link]);
[Link]([Link]);
// Won't work --- type is private
//[Link]([Link]);
// size is protected; App is not in the same package as Plant.
// Won't work
// [Link]([Link]);
// Won't work; App and Plant in different packages, height has package-level
visibility.
//[Link]([Link]);
[Link]:
import [Link];
public class Grass extends Plant {
public Grass() {
// Won't work --- Grass not in same package as plant, even though it's a subc
lass
// [Link]([Link]);
}
}
[Link]:
package world;
public class Field {
private Plant plant = new Plant();
public Field() {
// size is protected; Field is in the same package as Plant.
[Link]([Link]);
}
}
[Link]:
package world;
public class Oak extends Plant {
public Oak() {
// Won't work -- type is private
// type = "tree";
// This works --- size is protected, Oak is a subclass of plant.
[Link] = "large";
// No access specifier; works because Oak and Plant in same package
[Link] = 10;
}
[Link]:
package world;
class Something {
public class Plant {
// Bad practice
public String name;
// Accepetable practice --- it's final.
public final static int ID = 8;
private String type;
protected String size;
int height;
public Plant() {
[Link] = "Freddy";
[Link] = "plant";
[Link] = "medium";
[Link] = 8;
}
}
Lecture 30: Polymorphism
public class App {
public static void main(String[] args) {
Plant plant1 = new Plant();
// Tree is a kind of Plant (it extends Plant)
Tree tree = new Tree();
// Polymorphism guarantees that we can use a child class
// wherever a parent class is expected.
Plant plant2 = tree;
// plant2 references a Tree, so the Tree grow() method is called.
[Link]();
// The type of the reference decided what methods you can actually call;
// we need a Tree-type reference to call tree-specific methods.
[Link]();
// ... so this won't work.
//[Link]();
// Another example of polymorphism.
doGrow(tree);
}
public static void doGrow(Plant plant) {
[Link]();
}
[Link]:
public class Plant {
public void grow() {
[Link]("Plant growing");
}
}
[Link]:
public class Tree extends Plant {
@Override
public void grow() {
[Link]("Tree growing");
}
public void shedLeaves() {
[Link]("Leaves shedding.");
}
Lecture 31: Encapsulation and the API Docs
[Link]:
class Plant {
// Usually only static final members are public
public static final int ID = 7;
// Instance variables should be declared private,
// or at least protected.
private String name;
// Only methods intended for use outside the class
// should be public. These methods should be documented
// carefully if you distribute your code.
public String getData() {
String data = "some stuff" + calculateGrowthForecast();
return data;
}
// Methods only used the the class itself should
// be private or protected.
private int calculateGrowthForecast() {
return 9;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public class App {
public static void main(String[] args) {
}
Lecture 32: Casting Numerical Values
[Link]:
public class App {
/**
* @param args
*/
public static void main(String[] args) {
byte byteValue = 20;
short shortValue = 55;
int intValue = 888;
long longValue = 23355;
float floatValue = 8834.8f;
float floatValue2 = (float)99.3;
double doubleValue = 32.4;
[Link](Byte.MAX_VALUE);
intValue = (int)longValue;
[Link](intValue);
doubleValue = intValue;
[Link](doubleValue);
intValue = (int)floatValue;
[Link](intValue);
// The following won't work as we expect it to!!
// 128 is too big for a byte.
byteValue = (byte)128;
[Link](byteValue);
Lecture 33: UpCasting and DownCasting
class Machine {
public void start() {
[Link]("Machine started.");
class Camera extends Machine {
public void start() {
[Link]("Camera started.");
public void snap() {
[Link]("Photo taken.");
public class App {
public static void main(String[] args) {
Machine machine1 = new Machine();
Camera camera1 = new Camera();
[Link]();
[Link]();
[Link]();
// Upcasting
Machine machine2 = camera1;
[Link]();
// error: [Link]();
// Downcasting
Machine machine3 = new Camera();
Camera camera2 = (Camera)machine3;
[Link]();
[Link]();
// Doesn't work --- runtime error.
Machine machine4 = new Machine();
// Camera camera3 = (Camera)machine4;
// [Link]();
// [Link]();
Lecture 34: Using Generics
[Link]:
import [Link];
import [Link];
class Animal {
public class App {
public static void main(String[] args) {
/////////////////// Before Java 5 ////////////////////////
ArrayList list = new ArrayList();
[Link]("apple");
[Link]("banana");
[Link]("orange");
String fruit = (String)[Link](1);
[Link](fruit);
/////////////// Modern style //////////////////////////////
ArrayList<String> strings = new ArrayList<String>();
[Link]("cat");
[Link]("dog");
[Link]("alligator");
String animal = [Link](1);
[Link](animal);
///////////// There can be more than one type argument ////////////////////
HashMap<Integer, String> map = new HashMap<Integer, String>();
//////////// Java 7 style /////////////////////////////////
ArrayList<Animal> someList = new ArrayList<>();
}
Lecture 35: Generic and Wildcards
[Link]:
import [Link];
class Machine {
@Override
public String toString() {
return "I am a machine";
}
public void start() {
[Link]("Machine starting.");
}
class Camera extends Machine {
@Override
public String toString() {
return "I am a camera";
}
public void snap() {
[Link]("snap!");
}
}
public class App {
public static void main(String[] args) {
ArrayList<Machine> list1 = new ArrayList<Machine>();
[Link](new Machine());
[Link](new Machine());
ArrayList<Camera> list2 = new ArrayList<Camera>();
[Link](new Camera());
[Link](new Camera());
showList(list2);
showList2(list1);
showList3(list1);
}
public static void showList(ArrayList<? extends Machine> list) {
for (Machine value : list) {
[Link](value);
[Link]();
}
public static void showList2(ArrayList<? super Camera> list) {
for (Object value : list) {
[Link](value);
}
}
public static void showList3(ArrayList<?> list) {
for (Object value : list) {
[Link](value);
}
}
}
Lecture 36: Anonymous Classes
[Link]:
class Machine {
public void start() {
[Link]("Starting machine ...");
}
}
interface Plant {
public void grow();
}
public class App {
public static void main(String[] args) {
// This is equivalent to creating a class that "extends"
// Machine and overrides the start method.
Machine machine1 = new Machine() {
@Override public void start() {
[Link]("Camera snapping ....");
}
};
[Link]();
// This is equivalent to creating a class that "implements"
// the Plant interface
Plant plant1 = new Plant() {
@Override
public void grow() {
[Link]("Plant growing");
}
};
[Link]();
}
}
Lecture 37: Reading Files Using Scanner
[Link]:
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) throws FileNotFoundException {
//String fileName = "C:/Users/John/Desktop/[Link]";
String fileName = "[Link]";
File textFile = new File(fileName);
Scanner in = new Scanner(textFile);
int value = [Link]();
[Link]("Read value: " + value);
[Link]();
int count = 2;
while([Link]()) {
String line = [Link]();
[Link](count + ": " + line);
count++;
}
[Link]();
}
Lecture 38: Handling Exceptions
demo1/[Link]:
package demo1;
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("[Link]");
FileReader fr = new FileReader(file);
}
demo2/[Link]:
package demo2;
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
File file = new File("[Link]");
try {
FileReader fr = new FileReader(file);
// This will not be executed if an exception is thrown.
[Link]("Continuing ....");
} catch (FileNotFoundException e) {
[Link]("File not found: " + [Link]());
}
[Link]("Finished.");
}
demo3/[Link]:
package demo3;
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
try {
openFile();
} catch (FileNotFoundException e) {
// PS. This message is too vague : )
[Link]("Could not open file");
}
}
public static void openFile() throws FileNotFoundException {
File file = new File("[Link]");
FileReader fr = new FileReader(file);
Lecture 40: Multiple Exceptions
[Link]:
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
Test test = new Test();
// Multiple catch blocks
try {
[Link]();
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
} catch (ParseException e) {
[Link]("Couldn't parse command file.");
}
// Try multi-catch (Java 7+ only)
try {
[Link]();
} catch (IOException | ParseException e) {
// TODO Auto-generated catch block
[Link]();
}
// Using polymorphism to catch the parent of all exceptions
try {
[Link]();
} catch (Exception e) {
// TODO Auto-generated catch block
[Link]();
}
// Important to catch exceptions in the right order!
// IOException cannot come first, because it's the parent
// of FileNotFoundException, so would catch both exceptions
// in this case.
try {
[Link]();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
[Link]();
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
}
}
}
[Link]:
import [Link];
import [Link];
import [Link];
public class Test {
public void run() throws IOException, ParseException {
//throw new IOException();
throw new ParseException("Error in command list.", 2);
public void input() throws IOException, FileNotFoundException {
}
}
Lecture 40: Runtime vs, Checked Exceptions
[Link]:
public class App {
public static void main(String[] args) {
// Null pointer exception ....
String text = null;
[Link]([Link]());
// Arithmetic exception ... (divide by zero)
int value = 7/0;
// You can actually handle RuntimeExceptions if you want to;
// for example, here we handle an ArrayIndexOutOfBoundsException
String[] texts = { "one", "two", "three" };
try {
[Link](texts[3]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]([Link]());
}
}
}
Lecture 41: Abstract Classes
[Link]:
public class App {
public static void main(String[] args) {
Camera cam1 = new Camera();
[Link](5);
Car car1 = new Car();
[Link](4);
[Link]();
//Machine machine1 = new Machine();
}
[Link]:
public abstract class Machine {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
[Link] = id;
}
public abstract void start();
public abstract void doStuff();
public abstract void shutdown();
public void run() {
start();
doStuff();
shutdown();
}
}
[Link]:
public class Camera extends Machine {
@Override
public void start() {
[Link]("Starting camera.");
}
@Override
public void doStuff() {
[Link]("Taking a photo");
@Override
public void shutdown() {
[Link]("Shutting down the camera.");
[Link]:
public class Car extends Machine {
@Override
public void start() {
[Link]("Starting ignition...");
@Override
public void doStuff() {
[Link]("Driving...");
}
@Override
public void shutdown() {
[Link]("Switch off ignition.");
Lecture 42: Reading Files with FileReader
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
File file = new File("[Link]");
BufferedReader br = null;
try {
FileReader fr = new FileReader(file);
br = new BufferedReader(fr);
String line;
while( (line = [Link]()) != null ) {
[Link](line);
} catch (FileNotFoundException e) {
[Link]("File not found: " + [Link]());
} catch (IOException e) {
[Link]("Unable to read file: " + [Link]());
finally {
try {
[Link]();
} catch (IOException e) {
[Link]("Unable to close file: " + [Link]());
catch(NullPointerException ex) {
// File was probably never opened!
Lecture 43: Try with Resources
[Link]:
class Temp implements AutoCloseable {
@Override
public void close() throws Exception {
[Link]("Closing!");
throw new Exception("oh no!");
}
}
public class App {
public static void main(String[] args) {
try(Temp temp = new Temp()) {
} catch (Exception e) {
// TODO Auto-generated catch block
[Link]();
}
[Link]:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class App2 {
public static void main(String[] args) {
File file = new File("[Link]");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (FileNotFoundException e) {
[Link]("Can't find file " + [Link]());
} catch (IOException e) {
[Link]("Unable to read file " + [Link]());
}
Lecture 44: Creating and writing Text Files
[Link]:
import [Link];
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
File file = new File("[Link]");
try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) {
[Link]("This is line one");
[Link]();
[Link]("This is line two");
[Link]();
[Link]("Last line.");
} catch (IOException e) {
[Link]("Unable to read file " + [Link]());
}
Lecture 46: Inner Classes
[Link]:
public class App {
public static void main(String[] args) {
Robot robot = new Robot(7);
[Link]();
// The syntax below will only work if Brain is
// declared public. It is quite unusual to do this.
// [Link] brain = [Link] Brain();
// [Link]();
// This is very typical Java syntax, using
// a static inner class.
[Link] battery = new [Link]();
[Link]();
}
[Link]:
public class Robot {
private int id;
// Non-static nested classes have access to the enclosing
// class's instance data. E.g. implement Iterable
// [Link]
k-video-tutorial-part-11/
// Use them to group functionality.
private class Brain {
public void think() {
[Link]("Robot " + id + " is thinking.");
}
}
// static inner classes do not have access to instance data.
// They are really just like "normal" classes, except that they are grouped
// within an outer class. Use them for grouping classes together.
public static class Battery {
public void charge() {
[Link]("Battery charging...");
}
}
public Robot(int id) {
[Link] = id;
}
public void start() {
[Link]("Starting robot " + id);
// Use Brain. We don't have an instance of brain
// until we create one. Instances of brain are
// always associated with instances of Robot (the
// enclosing class).
Brain brain = new Brain();
[Link]();
final String name = "Robert";
// Sometimes it's useful to create local classes
// within methods. You can use them only within the method.
class Temp {
public void doSomething() {
[Link]("ID is: " + id);
[Link]("My name is " + name);
}
}
Temp temp = new Temp();
[Link]();
}
}
Lecture 47: Enum Types
[Link]:
public class App {
public static void main(String[] args) {
Animal animal = [Link];
switch(animal) {
case CAT:
[Link]("Cat");
break;
case DOG:
[Link]("Dog");
break;
case MOUSE:
break;
default:
break;
[Link]([Link]);
[Link]("Enum name as a string: " + [Link]());
[Link]([Link]());
[Link]([Link] instanceof Enum);
[Link]([Link]());
Animal animal2 = [Link]("CAT");
[Link](animal2);
}
[Link]:
public enum Animal {
CAT("Fergus"), DOG("Fido"), MOUSE("Jerry");
private String name;
Animal(String name) {
[Link] = name;
}
public String getName() {
return name;
}
public String toString() {
return "This animal is called: " + name;
}
}
Lecture 48: Recursion
[Link]:
(Note: I didn't trouble to handle the value 0 here, so fix it before using this code in an
exam :)
public class App {
public static void main(String[] args) {
// E.g. 4! = 4*3*2*1 (factorial 4)
[Link](factorial(5));
}
private static int factorial(int value) {
//[Link](value);
if(value == 1) {
return 1;
}
return factorial(value - 1) * value;
}
Lecture 49: Serialization
[Link]:
import [Link];
public class Person implements Serializable {
private static final long serialVersionUID = 4801633306273802062L;
private int id;
private String name;
public Person(int id, String name) {
[Link] = id;
[Link] = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}
}
// [Link]
[Link]:
import [Link];
import [Link];
import [Link];
import [Link];
public class WriteObjects {
public static void main(String[] args) {
[Link]("Writing objects...");
Person mike = new Person(543, "Mike");
Person sue = new Person(123, "Sue");
[Link](mike);
[Link](sue);
try(FileOutputStream fs = new FileOutputStream("[Link]")) {
ObjectOutputStream os = new ObjectOutputStream(fs);
[Link](mike);
[Link](sue);
[Link]();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
[Link]();
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
}
}
import [Link];
import [Link];
import [Link];
import [Link];
public class ReadObjects {
public static void main(String[] args) {
[Link]("Reading objects...");
try(FileInputStream fi = new FileInputStream("[Link]")) {
ObjectInputStream os = new ObjectInputStream(fi);
Person person1 = (Person)[Link]();
Person person2 = (Person)[Link]();
[Link]();
[Link](person1);
[Link](person2);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
[Link]();
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
[Link]();
}
Lecture 50: Serialization Arrays
[Link]:
import [Link];
public class Person implements Serializable {
private static final long serialVersionUID = 4801633306273802062L;
private int id;
private String name;
public Person(int id, String name) {
[Link] = id;
[Link] = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}
}
// [Link]
[Link]:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class WriteObjects {
public static void main(String[] args) {
[Link]("Writing objects...");
Person[] people = {new Person(1, "Sue"), new Person(99, "Mike"), new Person(7
, "Bob")};
ArrayList<Person> peopleList = new ArrayList<Person>([Link](people));
try (FileOutputStream fs = new FileOutputStream("[Link]"); ObjectOutputStre
am os = new ObjectOutputStream(fs)) {
// Write entire array
[Link](people);
// Write arraylist
[Link](peopleList);
// Write objects one by one
[Link]([Link]());
for(Person person: peopleList) {
[Link](person);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
[Link]();
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
}
[Link]:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class ReadObjects {
public static void main(String[] args) {
[Link]("Reading objects...");
try (FileInputStream fi = new FileInputStream("[Link]"); ObjectInputStream
os = new ObjectInputStream(fi)) {
// Read entire array
Person[] people = (Person[])[Link]();
// Read entire arraylist
@SuppressWarnings("unchecked")
ArrayList<Person> peopleList = (ArrayList<Person>)[Link]();
for(Person person: people) {
[Link](person);
}
for(Person person: peopleList) {
[Link](person);
}
// Read objects one by one.
int num = [Link]();
for(int i=0; i<num; i++) {
Person person = (Person)[Link]();
[Link](person);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
[Link]();
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
[Link]();
}
Lecture 51: The Transient keyword and more serialization
[Link]:
import [Link];
public class Person implements Serializable {
private static final long serialVersionUID = -1150098568783815480L;
private transient int id;
private String name;
private static int count;
public Person() {
[Link]("Default constructor");
}
public Person(int id, String name) {
[Link] = id;
[Link] = name;
[Link]("Two-argument constructor");
}
public static int getCount() {
return count;
}
public static void setCount(int count) {
[Link] = count;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "] Count is: " + count;
}
}
// [Link]
[Link]:
import [Link];
import [Link];
import [Link];
import [Link];
public class WriteObjects {
public static void main(String[] args) {
[Link]("Writing objects...");
try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("tes
[Link]"))) {
Person person = new Person(7, "Bob");
[Link](88);
[Link](person);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
[Link]();
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
}
[Link]:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class ReadObjects {
public static void main(String[] args) {
[Link]("Reading objects...");
try (ObjectInputStream os = new ObjectInputStream(new FileInputStream("test.s
er"))) {
Person person = (Person)[Link]();
[Link](person);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
[Link]();
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
[Link]();
}