0% found this document useful (0 votes)
167 views

Java Tutorial For Beginner

The document provides a summary of 15 lectures on Java programming concepts for beginners. It covers topics like writing a basic "Hello World" program, using variables of different types, strings, control structures like if/else, while and for loops, getting user input, arrays, classes and objects, and defining methods. Code examples are provided for each topic to demonstrate the concepts covered in each lecture.

Uploaded by

Claudia Barsan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
167 views

Java Tutorial For Beginner

The document provides a summary of 15 lectures on Java programming concepts for beginners. It covers topics like writing a basic "Hello World" program, using variables of different types, strings, control structures like if/else, while and for loops, getting user input, arrays, classes and objects, and defining methods. Code examples are provided for each topic to demonstrate the concepts covered in each lecture.

Uploaded by

Claudia Barsan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 83

Java Tutorial for

Complete Beginners (John Purcell)

Section 2
Lecture 5 : A Hello World Program

public class Application {

public static void main(String[] args) {

System.out.println("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;

System.out.println(myNumber);

System.out.println(myShort);

System.out.println(myLong);

System.out.println(myDouble);

System.out.println(myFloat);

System.out.println(myChar);

System.out.println(myBoolean);

System.out.println(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;

System.out.println(greeting);

System.out.println("Hello" + " " + "Bob");

System.out.println("My integer is: " + myInt);

double myDouble = 7.8;

System.out.println("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)

System.out.println("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++) {


System.out.printf("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:


System.out.println(5 == 5);
System.out.println(10 != 11);
System.out.println(3 < 6);
System.out.println(10 > 100);

// Using loops with "break":


int loop = 0;

while(true) {
System.out.println("Looping: " + loop);

if(loop == 3) {
break;
}

loop++;
System.out.println("Running");
}
}
}
true
true
true
false
Looping: 0
Running
Looping: 1
Running
Looping: 2
Running
Looping: 3

Lecture 11: Getting User input


import java.util.Scanner;

public class App {

public static void main(String[] args) {

// Create scanner object

Scanner input = new Scanner(System.in);

// Output the prompt

System.out.println("Enter a floating point value: ");


// Wait for the user to enter something.

double value = input.nextDouble();

// Tell them what they entered.

System.out.println("You entered: " + value);

Enter a floating point value:


5,6
You entered: 5.6

Lecture 12: Do…While


import java.util.Scanner;

public class App {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

/*
System.out.println("Enter a number: ");
int value = scanner.nextInt();

while(value != 5) {
System.out.println("Enter a number: ");
value = scanner.nextInt();
}
*/

int value = 0;
do {
System.out.println("Enter a number: ");
value = scanner.nextInt();
}
while(value != 5);

System.out.println("Got 5!");
}
}

Lecture 13: Switch


import java.util.Scanner;

public class Application {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Please enter a command: ");

String text = input.nextLine();

switch (text) {

case "start":

System.out.println("Machine started!");

break;

case "stop":

System.out.println("Machine stopped.");

break;

default:

System.out.println("Command not recognized");

}
}

Lecture 14: Arrays


public class App {
public static void main(String[] args) {

int value = 7;

int[] values;
values = new int[3];

System.out.println(values[0]);

values[0] = 10;
values[1] = 20;
values[2] = 30;

System.out.println(values[0]);
System.out.println(values[1]);
System.out.println(values[2]);

for(int i=0; i < values.length; i++) {


System.out.println(values[i]);
}

int[] numbers = {5, 6, 7};

for(int i=0; i < numbers.length; i++) {


System.out.println(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.


System.out.println(words[2]);
// Simultaneously declare and initialize an array of strings
String[] fruits = {"apple", "banana", "pear", "kiwi"};

// Iterate through an array


for(String fruit: fruits) {
System.out.println(fruit);
}

// "Default" value for an integer


int value = 0;

// Default value for a reference is "null"


String text = null;

System.out.println(text);

// Declare an array of strings


String[] texts = new String[2];

// The references to strings in the array


// are initialized to null.
System.out.println(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.


System.out.println(values[2]);

// 2D array (grid or table)


int[][] grid = {
{3, 5, 2343},
{2, 4},
{1, 2, 3, 4}
};

// Need 2 indices to access values


System.out.println(grid[1][1]);
System.out.println(grid[0][2]);

// Can also create without initializing.


String[][] texts = new String[2][3];
texts[0][1] = "Hello there";

System.out.println(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 < grid.length; row++) {
for(int col=0; col < grid[row].length; col++) {
System.out.print(grid[row][col] + "\t");
}

System.out.println();
}

// The last array index is optional.


String[][] words = new String[2][];

// Each sub-array is null.


System.out.println(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";

System.out.println(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();
person1.name = "Joe Bloggs";
person1.age = 37;

// Create a second Person object


Person person2 = new Person();
person2.name = "Sarah Smith";
person2.age = 20;

System.out.println(person1.name);

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++) {
System.out.println("My name is: " + name + " and I am " + age + " years o
ld ");
}
}

void sayHello() {
System.out.println("Hello there!");
}
}

public class App {

public static void main(String[] args) {

// Create a Person object using the Person class


Person person1 = new Person();
person1.name = "Joe Bloggs";
person1.age = 37;
person1.speak();
person1.sayHello();

// Create a second Person object


Person person2 = new Person();
person2.name = "Sarah Smith";
person2.age = 20;
person2.speak();
person1.sayHello();

System.out.println(person1.name);

}
}

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() {
System.out.println("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();

person1.name = "Joe";
person1.age = 25;

// person1.speak();

int years = person1.calculateYearsToRetirement();

System.out.println("Years till retirements " + years);

int age = person1.getAge();


String name = person1.getName();

System.out.println("Name is: " + name);


System.out.println("Age is: " + age);
}

Years till retirements 40


Name is: Joe
Age is: 25

Lecture 20: Methos Parameters


class Robot {
public void speak(String text) {
System.out.println(text);
}

public void jump(int height) {


System.out.println("Jumping: " + height);
}

public void move(String direction, double distance) {


System.out.println("Moving " + distance + " in direction " + direction);
}
}

public class App {

public static void main(String[] args) {


Robot sam = new Robot();

sam.speak("Hi I'm Sam");


sam.jump(7);

sam.move("West", 12.2);

String greeting = "Hello there";


sam.speak(greeting);
int value = 14;
sam.jump(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) {


this.name = name;
}

public void setAge(int age) {


this.age = 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();

//frog1.name = "Bertie";
//frog1.age = 1;

frog1.setName("Bertie");
frog1.setAge(1);

System.out.println(frog1.getName());
}

Bertie

Lecture 22: Constructors


class Machine {
private String name;
private int code;

public Machine() {
this("Arnie", 0);

System.out.println("Constructor running!");
}

public Machine(String name) {


this(name, 0);

System.out.println("Second constructor running");


// No longer need following line, since we're using the other constructor abo
ve.
//this.name = name;
}

public Machine(String name, int code) {

System.out.println("Third constructor running");


this.name = name;
this.code = 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() {


System.out.println("Object id: " + id + ", " + description + ": " + name);
}

public static void showInfo() {


System.out.println(description);
// Won't work: System.out.println(name);
}
}

public class App {

public static void main(String[] args) {

Thing.description = "I am a thing";

Thing.showInfo();

System.out.println("Before creating objects, count is: " + Thing.count);

Thing thing1 = new Thing();


Thing thing2 = new Thing();

System.out.println("After creating objects, count is: " + Thing.count);

thing1.name = "Bob";
thing2.name = "Sue";

thing1.showName();
thing2.showName();

System.out.println(Math.PI);

System.out.println(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.";

System.out.println(info);

// More efficient.
StringBuilder sb = new StringBuilder("");
sb.append("My name is Sue.");
sb.append(" ");
sb.append("I am a lion tamer.");

System.out.println(sb.toString());

// The same as above, but nicer ....

StringBuilder s = new StringBuilder();

s.append("My name is Roger.")


.append(" ")
.append("I am a skydiver.");

System.out.println(s.toString());

///// Formatting //////////////////////////////////

// Outputting newlines and tabs


System.out.print("Here is some text.tThat was a tab.nThat was a newline.");
System.out.println(" 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)
System.out.printf("Total cost %-10d; quantity is %dn", 5, 120);

// Demo-ing integer and string formatting control sequences


for(int i=0; i<20; i++) {
System.out.printf("%-2d: %sn", i, "here is some text");
}

// Formatting floating point value


// Two decimal place:
System.out.printf("Total value: %.2fn", 5.6874);

// One decimal place, left-aligned in 6-character field:


System.out.printf("Total value: %-6.1fn", 343.23423);

// You can also use the String.format() method if you want to retrieve
// a formatted string.
String formatted = String.format("This is a floating-point value: %.3f", 5.12
345);
System.out.println(formatted);

// Use double %% for outputting a % sign.


System.out.printf("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) {


this.id = id;
this.name = name;
}

public String toString() {

return String.format("%-4d: %s", id, name);


/*
StringBuilder sb = new StringBuilder();
sb.append(id).append(": ").append(name);

return sb.toString();
*/
}
}

public class App {

public static void main(String[] args) {


Frog frog1 = new Frog(7, "Freddy");
Frog frog2 = new Frog(5, "Roger");

System.out.println(frog1);
System.out.println(frog2);
}
}

7 : Freddy
5 : Roger

Lecture 26: Inheritance


public class App {

public static void main(String[] args) {


Machine mach1 = new Machine();

mach1.start();
mach1.stop();
Car car1 = new Car();

car1.start();
car1.wipeWindShield();
car1.showInfo();
car1.stop();

Machine.java:

public class Machine {

protected String name = "Machine Type 1";

public void start() {


System.out.println("Machine started.");
}

public void stop() {


System.out.println("Machine stopped.");
}
}

Car.java:
public class Car extends Machine {

@Override
public void start() {
System.out.println("Car started");
}

public void wipeWindShield() {


System.out.println("Wiping windshield");
}

public void showInfo() {


System.out.println("Car name: " + name);
}
}

Machine started.
Machine stopped.
Car started
Wiping windshield
Car name: Machine Type 1
Machine stopped.

Lecture 27: Packages


App.java:
import ocean.Fish;
import ocean.plants.Seaweed;

public class App {

public static void main(String[] args) {


Fish fish = new Fish();
Seaweed weed = new Seaweed();
}

Fish.java:

package ocean;

public class Fish {

Algae.java:

package ocean.plants;

public class Algae {

}
Seaweed.java:

package ocean.plants;

public class Seaweed {

Aquarium.java:

package com.caveofprogramming.oceangame;

public class Aquarium {

Lecture 28: Interfaces


App.java:

public class App {

public static void main(String[] args) {

Machine mach1 = new Machine();


mach1.start();
Person person1 = new Person("Bob");
person1.greet();

Info info1 = new Machine();


info1.showInfo();

Info info2 = person1;


info2.showInfo();

System.out.println();

outputInfo(mach1);
outputInfo(person1);
}

private static void outputInfo(Info info) {


info.showInfo();
}

Machine.java:

public class Machine implements Info {

private int id = 7;

public void start() {


System.out.println("Machine started.");
}
public void showInfo() {
System.out.println("Machine ID is: " + id);
}
}

Person.java:

public class Person implements Info {

private String name;

public Person(String name) {


this.name = name;
}

public void greet() {


System.out.println("Hello there.");
}

@Override
public void showInfo() {
System.out.println("Person name is: " + name);
}
}

Info.java:
public interface Info {
public void showInfo();
}

IStartable.java:

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


App.java:

import world.Plant;
/*
* 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();

System.out.println(plant.name);

System.out.println(plant.ID);

// Won't work --- type is private


//System.out.println(plant.type);

// size is protected; App is not in the same package as Plant.


// Won't work
// System.out.println(plant.size);

// Won't work; App and Plant in different packages, height has package-level
visibility.
//System.out.println(plant.height);

Grass.java:
import world.Plant;

public class Grass extends Plant {


public Grass() {

// Won't work --- Grass not in same package as plant, even though it's a subc
lass
// System.out.println(this.height);
}
}

Field.java:

package world;

public class Field {


private Plant plant = new Plant();

public Field() {

// size is protected; Field is in the same package as Plant.


System.out.println(plant.size);
}
}

Oak.java:
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.


this.size = "large";

// No access specifier; works because Oak and Plant in same package


this.height = 10;
}

Plant.java:

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() {
this.name = "Freddy";
this.type = "plant";
this.size = "medium";
this.height = 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.


plant2.grow();

// The type of the reference decided what methods you can actually call;
// we need a Tree-type reference to call tree-specific methods.
tree.shedLeaves();

// ... so this won't work.


//plant2.shedLeaves();

// Another example of polymorphism.


doGrow(tree);
}

public static void doGrow(Plant plant) {


plant.grow();
}

Plant.java:

public class Plant {


public void grow() {
System.out.println("Plant growing");
}
}
Tree.java:

public class Tree extends Plant {

@Override
public void grow() {
System.out.println("Tree growing");
}

public void shedLeaves() {


System.out.println("Leaves shedding.");
}

Lecture 31: Encapsulation and the API Docs


App.java:

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) {


this.name = name;
}

public class App {

public static void main(String[] args) {


}

Lecture 32: Casting Numerical Values


App.java:

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;

System.out.println(Byte.MAX_VALUE);

intValue = (int)longValue;

System.out.println(intValue);

doubleValue = intValue;
System.out.println(doubleValue);

intValue = (int)floatValue;
System.out.println(intValue);

// The following won't work as we expect it to!!


// 128 is too big for a byte.
byteValue = (byte)128;
System.out.println(byteValue);

Lecture 33: UpCasting and DownCasting

class Machine {

public void start() {

System.out.println("Machine started.");

class Camera extends Machine {

public void start() {

System.out.println("Camera started.");

public void snap() {


System.out.println("Photo taken.");

public class App {

public static void main(String[] args) {

Machine machine1 = new Machine();

Camera camera1 = new Camera();

machine1.start();

camera1.start();

camera1.snap();

// Upcasting

Machine machine2 = camera1;

machine2.start();

// error: machine2.snap();

// Downcasting

Machine machine3 = new Camera();

Camera camera2 = (Camera)machine3;

camera2.start();

camera2.snap();

// Doesn't work --- runtime error.

Machine machine4 = new Machine();


// Camera camera3 = (Camera)machine4;

// camera3.start();

// camera3.snap();

Lecture 34: Using Generics


App.java:

import java.util.ArrayList;
import java.util.HashMap;

class Animal {

public class App {

public static void main(String[] args) {

/////////////////// Before Java 5 ////////////////////////


ArrayList list = new ArrayList();

list.add("apple");
list.add("banana");
list.add("orange");
String fruit = (String)list.get(1);

System.out.println(fruit);

/////////////// Modern style //////////////////////////////

ArrayList<String> strings = new ArrayList<String>();

strings.add("cat");
strings.add("dog");
strings.add("alligator");

String animal = strings.get(1);

System.out.println(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


App.java:
import java.util.ArrayList;

class Machine {

@Override
public String toString() {
return "I am a machine";
}

public void start() {


System.out.println("Machine starting.");
}

class Camera extends Machine {


@Override
public String toString() {
return "I am a camera";
}

public void snap() {


System.out.println("snap!");
}
}

public class App {

public static void main(String[] args) {

ArrayList<Machine> list1 = new ArrayList<Machine>();


list1.add(new Machine());
list1.add(new Machine());

ArrayList<Camera> list2 = new ArrayList<Camera>();

list2.add(new Camera());
list2.add(new Camera());

showList(list2);
showList2(list1);
showList3(list1);
}

public static void showList(ArrayList<? extends Machine> list) {


for (Machine value : list) {
System.out.println(value);
value.start();
}

public static void showList2(ArrayList<? super Camera> list) {


for (Object value : list) {
System.out.println(value);
}
}

public static void showList3(ArrayList<?> list) {


for (Object value : list) {
System.out.println(value);
}
}
}

Lecture 36: Anonymous Classes


App.java:

class Machine {
public void start() {
System.out.println("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() {
System.out.println("Camera snapping ....");
}
};

machine1.start();
// This is equivalent to creating a class that "implements"
// the Plant interface
Plant plant1 = new Plant() {
@Override
public void grow() {
System.out.println("Plant growing");

}
};

plant1.grow();
}
}

Lecture 37: Reading Files Using Scanner


App.java:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class App {

public static void main(String[] args) throws FileNotFoundException {


//String fileName = "C:/Users/John/Desktop/example.txt";
String fileName = "example.txt";

File textFile = new File(fileName);


Scanner in = new Scanner(textFile);

int value = in.nextInt();


System.out.println("Read value: " + value);

in.nextLine();

int count = 2;
while(in.hasNextLine()) {
String line = in.nextLine();

System.out.println(count + ": " + line);


count++;
}

in.close();
}

Lecture 38: Handling Exceptions


demo1/App.java:

package demo1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class App {

public static void main(String[] args) throws FileNotFoundException {

File file = new File("test.txt");

FileReader fr = new FileReader(file);


}

demo2/App.java:

package demo2;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class App {

public static void main(String[] args) {


File file = new File("test.txt");

try {
FileReader fr = new FileReader(file);

// This will not be executed if an exception is thrown.


System.out.println("Continuing ....");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + file.toString());
}

System.out.println("Finished.");
}

demo3/App.java:

package demo3;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class App {

public static void main(String[] args) {


try {
openFile();
} catch (FileNotFoundException e) {
// PS. This message is too vague : )
System.out.println("Could not open file");
}
}

public static void openFile() throws FileNotFoundException {


File file = new File("test.txt");

FileReader fr = new FileReader(file);

Lecture 40: Multiple Exceptions


App.java:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;

public class App {

public static void main(String[] args) {


Test test = new Test();

// Multiple catch blocks


try {
test.run();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
System.out.println("Couldn't parse command file.");
}
// Try multi-catch (Java 7+ only)
try {
test.run();
} catch (IOException | ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// Using polymorphism to catch the parent of all exceptions


try {
test.run();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// 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 {
test.input();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

Test.java:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;

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


App.java:

public class App {


public static void main(String[] args) {

// Null pointer exception ....


String text = null;

System.out.println(text.length());

// 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 {
System.out.println(texts[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.toString());
}
}
}

Lecture 41: Abstract Classes


App.java:

public class App {

public static void main(String[] args) {


Camera cam1 = new Camera();
cam1.setId(5);

Car car1 = new Car();


car1.setId(4);

car1.run();

//Machine machine1 = new Machine();


}

Machine.java:

public abstract class Machine {


private int id;

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public abstract void start();


public abstract void doStuff();
public abstract void shutdown();

public void run() {


start();
doStuff();
shutdown();
}
}

Camera.java:

public class Camera extends Machine {

@Override
public void start() {
System.out.println("Starting camera.");
}

@Override
public void doStuff() {
System.out.println("Taking a photo");

@Override
public void shutdown() {
System.out.println("Shutting down the camera.");

Car.java:
public class Car extends Machine {

@Override
public void start() {
System.out.println("Starting ignition...");

@Override
public void doStuff() {
System.out.println("Driving...");
}

@Override
public void shutdown() {
System.out.println("Switch off ignition.");

Lecture 42: Reading Files with FileReader


import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;
import java.io.IOException;

public class App {

public static void main(String[] args) {

File file = new File("test.txt");

BufferedReader br = null;

try {

FileReader fr = new FileReader(file);

br = new BufferedReader(fr);

String line;

while( (line = br.readLine()) != null ) {

System.out.println(line);

} catch (FileNotFoundException e) {

System.out.println("File not found: " + file.toString());

} catch (IOException e) {

System.out.println("Unable to read file: " + file.toString());

finally {

try {
br.close();

} catch (IOException e) {

System.out.println("Unable to close file: " + file.toString());

catch(NullPointerException ex) {

// File was probably never opened!

Lecture 43: Try with Resources


App.java:

class Temp implements AutoCloseable {

@Override
public void close() throws Exception {
System.out.println("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
e.printStackTrace();
}

App2.java:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class App2 {

public static void main(String[] args) {


File file = new File("test.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;

while ((line = br.readLine()) != null) {


System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("Can't find file " + file.toString());
} catch (IOException e) {
System.out.println("Unable to read file " + file.toString());
}

Lecture 44: Creating and writing Text Files


App.java:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class App {

public static void main(String[] args) {


File file = new File("test.txt");
try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) {
br.write("This is line one");
br.newLine();
br.write("This is line two");
br.newLine();
br.write("Last line.");
} catch (IOException e) {
System.out.println("Unable to read file " + file.toString());
}

Lecture 46: Inner Classes


App.java:

public class App {

public static void main(String[] args) {

Robot robot = new Robot(7);


robot.start();

// The syntax below will only work if Brain is


// declared public. It is quite unusual to do this.
// Robot.Brain brain = robot.new Brain();
// brain.think();

// This is very typical Java syntax, using


// a static inner class.
Robot.Battery battery = new Robot.Battery();
battery.charge();
}

Robot.java:

public class Robot {

private int id;

// Non-static nested classes have access to the enclosing


// class's instance data. E.g. implement Iterable
// http://www.caveofprogramming.com/java/using-iterable-java-collections-framewor
k-video-tutorial-part-11/
// Use them to group functionality.
private class Brain {
public void think() {
System.out.println("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() {
System.out.println("Battery charging...");
}
}

public Robot(int id) {


this.id = id;
}

public void start() {


System.out.println("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();
brain.think();

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() {
System.out.println("ID is: " + id);
System.out.println("My name is " + name);
}
}

Temp temp = new Temp();


temp.doSomething();
}
}

Lecture 47: Enum Types


App.java:

public class App {

public static void main(String[] args) {

Animal animal = Animal.DOG;

switch(animal) {
case CAT:
System.out.println("Cat");
break;
case DOG:
System.out.println("Dog");
break;
case MOUSE:
break;
default:
break;

System.out.println(Animal.DOG);
System.out.println("Enum name as a string: " + Animal.DOG.name());

System.out.println(Animal.DOG.getClass());
System.out.println(Animal.DOG instanceof Enum);

System.out.println(Animal.MOUSE.getName());

Animal animal2 = Animal.valueOf("CAT");

System.out.println(animal2);
}

Animal.java:

public enum Animal {


CAT("Fergus"), DOG("Fido"), MOUSE("Jerry");

private String name;

Animal(String name) {
this.name = name;
}

public String getName() {


return name;
}

public String toString() {


return "This animal is called: " + name;
}
}
Lecture 48: Recursion
App.java:
(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)

System.out.println(factorial(5));
}

private static int factorial(int value) {


//System.out.println(value);

if(value == 1) {
return 1;
}

return factorial(value - 1) * value;


}

Lecture 49: Serialization


Person.java:

import java.io.Serializable;

public class Person implements Serializable {

private static final long serialVersionUID = 4801633306273802062L;

private int id;


private String name;

public Person(int id, String name) {


this.id = id;
this.name = name;
}

@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}
}

// www.caveofprogramming.com

WriteObjects.java:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class WriteObjects {

public static void main(String[] args) {


System.out.println("Writing objects...");

Person mike = new Person(543, "Mike");


Person sue = new Person(123, "Sue");

System.out.println(mike);
System.out.println(sue);

try(FileOutputStream fs = new FileOutputStream("people.bin")) {

ObjectOutputStream os = new ObjectOutputStream(fs);

os.writeObject(mike);
os.writeObject(sue);

os.close();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ReadObjects {

public static void main(String[] args) {


System.out.println("Reading objects...");

try(FileInputStream fi = new FileInputStream("people.bin")) {

ObjectInputStream os = new ObjectInputStream(fi);

Person person1 = (Person)os.readObject();


Person person2 = (Person)os.readObject();

os.close();

System.out.println(person1);
System.out.println(person2);

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Lecture 50: Serialization Arrays


Person.java:

import java.io.Serializable;

public class Person implements Serializable {

private static final long serialVersionUID = 4801633306273802062L;

private int id;


private String name;

public Person(int id, String name) {


this.id = id;
this.name = name;
}

@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}
}

// www.caveofprogramming.com

WriteObjects.java:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class WriteObjects {

public static void main(String[] args) {


System.out.println("Writing objects...");

Person[] people = {new Person(1, "Sue"), new Person(99, "Mike"), new Person(7
, "Bob")};

ArrayList<Person> peopleList = new ArrayList<Person>(Arrays.asList(people));

try (FileOutputStream fs = new FileOutputStream("test.ser"); ObjectOutputStre


am os = new ObjectOutputStream(fs)) {

// Write entire array


os.writeObject(people);

// Write arraylist
os.writeObject(peopleList);

// Write objects one by one


os.writeInt(peopleList.size());

for(Person person: peopleList) {


os.writeObject(person);
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

WriteObjects.java:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ReadObjects {

public static void main(String[] args) {


System.out.println("Reading objects...");

try (FileInputStream fi = new FileInputStream("test.ser"); ObjectInputStream


os = new ObjectInputStream(fi)) {

// Read entire array


Person[] people = (Person[])os.readObject();

// Read entire arraylist


@SuppressWarnings("unchecked")
ArrayList<Person> peopleList = (ArrayList<Person>)os.readObject();

for(Person person: people) {


System.out.println(person);
}

for(Person person: peopleList) {


System.out.println(person);
}

// Read objects one by one.


int num = os.readInt();

for(int i=0; i<num; i++) {


Person person = (Person)os.readObject();
System.out.println(person);
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Lecture 51: The Transient keyword and more serialization


Person.java:

import java.io.Serializable;

public class Person implements Serializable {

private static final long serialVersionUID = -1150098568783815480L;

private transient int id;


private String name;

private static int count;

public Person() {
System.out.println("Default constructor");
}

public Person(int id, String name) {


this.id = id;
this.name = name;

System.out.println("Two-argument constructor");
}

public static int getCount() {


return count;
}

public static void setCount(int count) {


Person.count = count;
}

@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "] Count is: " + count;
}
}

// www.caveofprogramming.com

WriteObjects.java:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class WriteObjects {


public static void main(String[] args) {
System.out.println("Writing objects...");

try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("tes


t.ser"))) {

Person person = new Person(7, "Bob");


Person.setCount(88);
os.writeObject(person);

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

ReadObjects.java:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

public class ReadObjects {


public static void main(String[] args) {
System.out.println("Reading objects...");

try (ObjectInputStream os = new ObjectInputStream(new FileInputStream("test.s


er"))) {

Person person = (Person)os.readObject();


System.out.println(person);

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

You might also like