CIT111: Java Session 2
Variables, operators, and basics
Session Overview
We gained some exposure to the core ways in which Java code "flows" and works with the Car Fob example. Now we want to step back a tad and make sure we have essentials down before expanding.
Learning Objectives
- Correctly create variable and class names that are descriptive and are not reserved or keywords.
- Interalize the idea of a java primitive and non-primitive type with the use of a method on the String class.
- Experience the concept of error types through the notion of type safety in variable names.
- Use an existing class in the Java library to gather input from the user for processing.
- Create a value converter using constants and variables and user input.
- Share a value converter object with peers.
Activity 1: The Java language essentials
All text that we write in a Java program is parsed by the compiler into categories of symbols that have meaning to the computer. These core categories are:
- Java keywords or reserved words
- Primitive type names
- Identifiers
- Primitive variable names
- Object/class names
- Method and class member (field) names
- Operators
- Literals
Activity 2: Gathering user input
Our goal is to retrieve a text value from the user and store it in a String type variable for processing by the computer and display to the user.
package essentials;
import java.util.Scanner;
public class GreetingMachine {
public static void main(String[] args) {
System.out.println("Please enter your name");
Scanner scan = new Scanner(System.in);
String name = scan.next();
System.out.println("Whoa, " + name + " What an interesting name card you have!");
} // Close main()
} // close class GreetingMachine
- Create a class file in a new project called GreetingMachine and paste in this code so that it compiles.
- Indent the code properly so lines that make up a block are grouped by indentation
- Change the greeting to something interesting and create a neat String art
Activity 3: Converters
Sudy this converter code
package essentials;
import java.util.Scanner;
/**
* Class which converts a value entered by the user into a new type of data
* @author delores
*/
public class Converter {
public static void main(String[] args){
// Basic prompt
System.out.println("Enter a number of days:");
// Create a scanner object that reads input
Scanner scan = new Scanner(System.in);
// now gather input and store it in the local variable days
int days = scan.nextInt();
// Send das to our converter method which will convert and display values
convertDaysToSeconds(days);
} // close main()
public static void convertDaysToSeconds(int days){
final int SECONDS_PER_HOUR = 60 * 60;
int seconds = days * SECONDS_PER_HOUR;
System.out.println(days + " days is the equivalent of " + seconds + " seconds");
} // close convertDaysToSeconds()
} // close Class