CS 110 -- Introduction to Computer Science JAVA Programming Basics Form of a JAVA Program Header Comment Import statements Class definition { Main Method declaration { Scanner definition Declare statements Programming Statements } } Import statement Æ brings in JAVA library elements Class definition Æ class name must match the filename filename must be .java class name follows identifier rules except it starts with upper case (style convention) Declare statements Æ form: datatype identifierName; Defines variables which name memory locations used to store information Identifier names start with lower case, use uppercase at word change (style convention) meaningful names Constant declaration: final datatype identifiername = value; User defined constants: all upper case (style convention) Assignment Statements Æ variable = expression; variables must be declared before they can be used evaluate the expression and store its value in the variable Operator precedence rules ( ) * / % + - Operators of equal precedence are evaluated left to rightOutput Æ System.out or System.err print (expression) println(expression) flush() expression Æ literals + variables or expressions string literal enclosed in “ “ character literal enclosed in ‘ ‘ literals are displayed exactly as they exist value of variables or expressions are displayed Input Æ System.in Must import Scanner from library Requires a Scanner object is declared and associated with System.in String Æ next() delimeter blank String Æ nextLine(); delimeter is carriage return Integer Æ nextInt() Float Æ nextFloat() Double Æ nextDouble(); Char Æ next().charAt(0); Exceptions on Input Program error terminates when incompatible data is entered InputMismatchException Reading into int -Æ user enters decimal or character data Reading into a double Æ user enters character data Does not occur when reading into a
View Full Document