Java Switch Statement Example

I don’t see the switch statement used very much, but it’s on your syllabus so let’s take a look at it:

String grade = input(); // assume that input method exists
String msg;
switch (grade) {
	case "A":
		 msg += "Very ";
	case "B":
		 msg += "Good ";
	case "C": 
		 msg += "Pass";
		 break;
	case "D":
		 msg = "Borderline ";
	case "F":
		 msg = "Fail";
		 break;
	default: 
		 msg = "Invalid Grade";
}
System.out.println(msg);

The outputs are as follows:

grade = “A” -> “Very Good Pass”
grade = “B” -> “Good Pass”
grade = “C” -> “Pass”
grade = “D” -> “Borderline Fail”
grade = “F” -> “Fail”
Anything else -> “Invalid Grade”

Notes:

  • You have to have the break statement otherwise you “fall through” to the next case. It’s normal to have a break statement at the end of every case. The example I’ve provided is contrived to show you the functionality, but in 25 years of programming Java I can’t remember genuinely using a switch statement like this!
  • The default case is executed if none of the other cases are executed.
  • The ability to use a switch statement on String objects was introduced in Java 7.

Java Generics: A simple example

Sometimes you will see funny angle brackets in Java code. Although Java’s generic types are not mentioned in the IB syllabus, this is a brief example of their use.

The output of this code is:

Hello
5
java.util.Random@7852e922
Anything object: Fred, 5
Anything object: Second, 2

package genericsdemo;
import java.util.List;
import java.util.ArrayList;
/**
 *
 * @author justin
 */
public class GenericsDemo {

    public static void main(String[] args) {
        /* Here we create four MyContainer objects and show that we can put
         * any type into them. Note that the generic type has to be a reference
         * type; we couldn't put a primitive in there.
         */
        MyContainer<String> container1 = new MyContainer("Hello");
        MyContainer<Integer> container2 = new MyContainer(5);
        MyContainer<java.util.Random> container3 = new MyContainer(new java.util.Random());
        MyContainer<Anything> container4 = new MyContainer(new Anything("Fred", 5));
        
        System.out.println(container1.get());
        System.out.println(container2.get());
        System.out.println(container3.get());
        System.out.println(container4.get());
        
        /* It is probably rare that you will use Java Generics to create
         * your own containers. Much more likely you will use it to specify  
         * the type of object to be held in a list object from the Java
         * library.
         */
        List<Anything> myList = new ArrayList();
        myList.add(new Anything("First", 1));
        myList.add(new Anything("Second", 2));
        myList.add(new Anything("Third", 3));
        System.out.println(myList.get(1));
    }
    
}

class MyContainer<T>{
    /* T is not a type, it is a type variable.
     * The variable t is an object of type T, even though we don't yet know 
     * what type T is. 
     */
    T t;
    public MyContainer(T t) {
        this.t = t;
    }
    
    T get(){
        return t;
    }
}

class Anything {
    String name;
    int number;
    
    public Anything(String name, int number) {
        this.name = name;
        this.number = number;
    }
    
    public String toString() {
        return "Anything object: " + name + ", " + number;
        
    }
}

Using JLists with the ListModel interface

Purists may prefer only to allow the View to communicate with the Model via the Controller but in the types of small applications that we do in schools I think it’s perfectly reasonable for the View to have a direct reference to the Model.

// In the Model
private Set people = new HashSet();
public List getPeople() {
     return new ArrayList(people);
}

// In the View
listModel.clear();
List people = model.getPeople();
for (Person person : people) {
     listModel.addElement(person);
}

 

Inserting Multiple Rows into a SQLite Database from Java

package sqlitetest;
import java.sql.*;

public class SqliteTest {

    public static void main(String args[]) {
        Connection connection = null;

        try {
            /* The next line will give a ClassNotFound error unless the
               sqlite jar is in the classpath. To add it in Netbeans, 
               right-click on the project, choose Properties, Libraries 
               and add the path to the jar file. On Linux I saved it in 
               /usr/local/sqlite/sqlite-jdbc-3.20.0.jar, but this will be
               different if you are using Mac or Windows.
            */
            Class.forName("org.sqlite.JDBC");
            connection = DriverManager.getConnection("jdbc:sqlite:test.db");

            // The database must already have a country table with these fields.
            // In my table there is also a CountryId primary key field, but the
            // database assigns values to that field automatically.
            String sql = "insert into Country (CountryName, Population) values (?, ?)";
            PreparedStatement ps = connection.prepareStatement(sql);


            // In larger applications you would probably loop through a list
            // of country objects. This is just a simple demo.

            ps.setString(1, "United States of America");
            ps.setString(2, "320000000");
            ps.addBatch();

            ps.setString(1, "China");
            ps.setString(2, "1400000000");
            ps.addBatch();

            ps.executeBatch();
            connection.close();

        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
        }
        System.out.println("Insert successful");
    }
}

Simple chat server in Python

Add the following code to server.py and run.

# server.py
#!/usr/bin/python

import socket

sock = socket.socket()
host = 'localhost' # Change this to "" to receive connections from any host
port = 12221  # Any unreserved port but must be same as client
sock.bind((host, port))

sock.listen(5)
conn = None

while True:
   if conn is None:
       # Halts
       print ('[Waiting for connection...]')
       conn, addr = sock.accept()
       print('Got connection from', addr)
   else:
       # Halts
       print ( '[Waiting for response...]')
       print (conn.recv(1024))
       msg = input("Enter something to this client: ")
       conn.send(msg.encode('UTF-8'))

Add the following code to client.py.

# client.py
#!/usr/bin/python

import socket

sock = socket.socket()
host = 'localhost' # Change this to remote ip as necessary
port = 12221 # Any unreserved port but must be same as server

sock.connect((host, port))
print ('Connected to', host)

while True:
msg = input("Enter something for the server: ")
sock.send(msg.encode('UTF-8'))
# Halts
print ('[Waiting for response...]')
print (sock.recv(1024))