Lecture 2: Variables, Operators, Expressions, Statements, I/O

What You Will Learn Today

  1. basic C-like building blocks of the Java language, including:
    1. variables and data types
    2. naming and coding conventions
    3. operators and expressions
    4. statements and comments
  2. input and output
    1. using the System command
    2. using a dialog box
    3. using the console

Constants and Variables

Data Types

Characters

Declaration and Assignment

Keywords and Identifiers

Recommended Naming Conventions

Recommended Coding Style

Arithmetic, Logical and Comparison Operators

Unary, Binary and Ternary Operators

Incrementing and Decrementing

Assignment Operators

Type Conversion using Casts

Statements

Comments

Command-Line Text Output

Dialog Box Input

/**
get a string from the user using a dialog box
DialogString.java
@author Greg Vogl
2003-09-21
input: a string using a dialog box
output: the string
*/
import javax.swing.JOptionPane; // Swing is a Java SDK graphics library that contains the dialog box
public class DialogString
{
  public static void main (String[] args)
  {
    String input = JOptionPane.showInputDialog("Enter a string");
    System.out.println("You entered: " + input);
    System.exit(0); // needed to exit a program with a GUI thread
  }
}

Console Input

/**
get a string from the user using the command line
ConsoleString.java
@author Greg Vogl
2003-09-21
input: a string using the command line
output: the string
@throws IOException to handle bad strings
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class ConsoleString
{
  // main() must be able to throw an I/O exception to handle bad strings
  public static void main (String[] args) throws IOException 
  {
    System.out.println("Enter a string:");
    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
    String input = console.readLine(); // get a string from the user
    System.out.println("You entered: " + input); // display the string to the screen
  }
}

To Do After Class