Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Programming Fundamental I ACS-1903 Chapter 2 Basics of Java 1/18/2017 1 Basics of Java What we will learn literals variables primitive data types the String class input output The first three concepts are common in most of the programming languages The last three will help you to understand what is an “object-oriented” language like Java 1/18/2017 2 Literals Literals They are the formal names for constants in Java Examples include: 123, 123.45, 'a', "Gosling", true Most of the time numeric literals and Boolean literals are written in the same way we would normally write them down e.g. 123, 123.45, true, false For text literals single quotes to specify a single character (e.g. 'a') or double quotes to specify a text string (e.g. "Gosling") 1/18/2017 3 Variables Variable A fundamental concept in programming a piece of memory that holds a value that a program can use and change as it executes Java is strongly typed You MUST declare the type of each variable before you use it You cannot change this type later 1/18/2017 4 Variables Using a variable 1 /** 2 * This Java class declares 3 * an int variable named i, 4 * assigns the value 14 to i, 5 * and displays i. 6 */ 7 public class Variable 8{ 9 public static void main ( String [] args ){ 10 int i; 11 i = 14; 12 System.out.println (i); 13 i = 30; 14 System.out .println (i); 15 } 16 } 1/18/2017 5 Variables Naming Variables Choose names that are concise yet meaningful Names that can indicate the intent of its use Camel case The way a Java programmer will often name the variable if this name needs more than one word It is a style where words are catenated together the first word is all lower case, and the second and subsequent words have only the first letter capitalized 1/18/2017 6 Variables Java variable names are casesensitive NetPay and netPay are different variables You cannot use keywords for variable names Keywords are reserved for special purposes public, int, void, static, class, …, and more are coming 1/18/2017 7 Primitive Data Types The Java language contains eight primitive data types byte short int long float double char boolean 1/18/2017 8 Primitive Data Types Numeric Integers byte short int – 100, 234, 0 long – 100L, 234L, 0L Real numbers double – 100.12, 234.0, 0.0 float – 100.12f, 234.0f, 0.0f int and double are default types for numeric literals Individual characters Char – 'a‘, 'b', 'q', '$'. Logical values boolean – true and false 1/18/2017 9 Primitive Data Types Primitive Data Types: Byte/short/int/long These types differ with respect to the amount of memory used therefore minimum and maximum values 1/18/2017 10 Primitive Data Types Calculations Addition + Subtraction Multiplication * Division / Modulo % 1/18/2017 11 Primitive Data Types Integer Arithmetic If the operands of an arithmetic operation are both integers, the result is an integer Consider division - there is no remainder Modulo gives the remainder when the first operand is divided by the second operand 1/18/2017 12 Primitive Data Types 1 public class IntegerArithmetic 2{ 3 public static void main ( String [] args ) 4 { 5 // Use integer arithmetic 6 // Division : no remainder 7 // Modulo : yields the remainder 8 int number , digit ; 9 number = 1297; 10 // Get right - most digit 11 digit = number % 10; 12 System.out.println ( digit ); 13 // Decrease number by a factor of 10 14 // and get next digit 15 number = number / 10; 16 digit = number % 10; 17 System.out.println ( digit ); 18 } 19 } 1/18/2017 13 Primitive Data Types Numeric Data Types: float, double They are used to represent values that have decimal places They differ with respect to the number of significant digits they store approximately 7 for float and 16 for double the overall magnitude of a value that can be represented Just for comparison, it is estimated that the there are between 1078 to 1082 atoms in the known, observable universe 1/18/2017 14 Primitive Data Types Arithmetic calculations on doubles and floats Operators that we will discuss at this time include +, -, *, and / There is a mistake in above table! 1/18/2017 15 Primitive Data Types Doubles as approximations Programmers must be aware that not every number can be represented exactly as a double or float Think of ¼ and 1/3 Default Decimal Data Type double is the default data type for values with a decimal point If you want to use a float value then the suffix “f” needs to be used 100.25f Default numeric data types ? and ? 1/18/2017 16 Primitive Data Types Numeric Expressions Formed by operators and operands Operators For now: +, -, *, /, and % They are all binary operators, These operands all take two operands Expressions with these operands are written in an infix manner where one operand is on the left of the operator and the other operand in on the right Operands Literals Variables Sub-expressions The expressions enclosed in parentheses, “()” 1/18/2017 17 Primitive Data Types Operator Priorities Java gives each operator a priority It then uses those priorities to control the order of evaluation for an expression Higher priority operators are executed before lower priority operators You can use a sub-expression to override these priorities A sub-expression is always evaluated before the expression in which it is contained 1/18/2017 18 Primitive Data Types Operator Associativity When an expression involves more than one operator of the same priority, they are evaluated from left to right These operators are called left associative in programming term Mixed Mode Expressions Expressions that contain a mixture of types Java permits conversions between integer and floating-point types 1/18/2017 19 Primitive Data Types There are two types of conversions Widening The type being converted can contain all values of the other type Example: a value of the short type (a 2-byte integer) is converted as an int type (a 4-byte integer) 1/18/2017 /** * This Java class declares a short variable, * assigns it a value, and then assigns the * value to a variable of type int */ public class ShortToInt { public static void main(String[] args){ short s; int t; s = 100; t = s; System.out.println ("s is: "+s); System.out.println ("t is: "+t); } } 20 Primitive Data Types Java allows these widening conversions automatically: *from byte to short, int, or long, float, or double *from short to int, long, float, or double *from int to long, float, or double *from long to float or double *from float to double *from char to int, long, float, or double More examples … Narrowing Cases where there could be a loss of precision after conversion Examples: converting from a double to an int Cannot be performed automatically – you have to directly indicates that casting is to be performed (this will be discussed later) 1/18/2017 21 Primitive Data Types Unary operators the operators that takes one operand Unary minus is one that commonly used It is placed immediately in front of an expression to negate the value of the expression Its priority is higher than multiplication, division, and modulo 1/18/2017 22 Primitive Data Types boolean Data Types This type has only two values True False It can most often be used for control structures The operators for booleans and && or || not ! First two are binary, and the last one is unary 1/18/2017 23 Primitive Data Types 1/18/2017 24 Primitive Data Types Example: boolean xyz = true ; boolean found ; If (xyz) System.out.println(“the variable is true”); If (xyz && found ) ................ 1/18/2017 25 Primitive Data Types Operator priorities Java assigns priorities to boolean operators From high to low not and or 1/18/2017 26 Primitive Data Types Relational Operators The operators for comparing one value to another The operations with these operators evaluate to a boolean (true or false) They are summarized in the table below (assume x and y are of type int) Example of CompareNumber 1/18/2017 27 Primitive Data Types char Data Type char is used when you need to handle individual characters a char value is enclosed in single quotes How char values are stored Each char value is stored using two bytes of memory So a character can be represented by a bit sequences and corresponding integer value The corresponding integer value is called ASCII code http://www.ascii-code.com The table in the textbook is NOT correct Because of this we can apply the relational operators to char values too Example: CompareChar 1/18/2017 28 Primitive Data Types char Data Type char is used when you need to handle individual characters a char value is enclosed in single quotes How char values are stored Each char value is stored using two bytes of memory So a character can be represented by a bit sequences and corresponding integer value The corresponding integer value is called ASCII code http://www.ascii-code.com The table in the textbook is NOT correct Because of this we can apply the relational operators to char values too Example: CompareChar 1/18/2017 29 Operators Operators The operators that we have learned and those that are popularly used 1/18/2017 30 Operators Complex expression Expressions can be very complex Example: boolean answer = a+b > c+d && x<z You need to evaluate this expression based on the order of priorities shown in the previous slide You can use extra spaces and parentheses in expressions to make it easier to read the expressions – as long as you do not change the order of operations boolean answer = ((a+b)> (c+d)) && (x<z) 1/18/2017 Operators The assignment operator The assignment statement is really a Java expression followed by a semicolon The assignment operator is usually the last operator to be evaluated With a priority of 2 The assignment operator is right associative when several assignment operators appear in an expression they are evaluated/performed from right to left int q = (j=1)+1; int i = j = k = 1; 1/18/2017 The String Class The String Class The String class It is provided to facilitate the many things that programmers need to do with text strings String literals are written as a sequence of characters that are delimited by double quotes "this is a line of text“ 1/18/2017 The String Class Variable of type String (Capital!) How Java compiler allocates memory for a variable of type String The memory location for this variable will contain a reference (an address) to the storage location where the text string is actually stored Memory for primitive types is handled differently The memory location associated with a primitive type contains the value (not an address) of the variable 1/18/2017 The String Class 1/18/2017 The String Class Allocating strings The formal way to declare fullName and assign it a value is to use the "new" operator Since text strings are objects of type String String fullName = new String("Joe Smith") In general the new operator is used to instantiate (to create) an object Because text strings are so common Java provides the short cut for allocating a string String fullName = "Joe Smith“ The only way to work with objects is through the methods that are defined in the class from which the object is instantiated 1/18/2017 The String Class String class provides many methods Some are listed below: 1/18/2017 The String Class Checking the documentation of classes It is very easy in BlueJ Taste of “object-oriented” To use a String method you must reference the object and the method Example: to obtain the length of a variable s (of String class) you must use the expression s.length() The variable name is followed by a period which is followed by the method name and any arguments enclosed in parentheses In object-oriented terminology we are asking the object s to execute its length() method 1/18/2017 The String Class Examples of using String methods UsingStringLength UsingStringCharAt UsingStringEquals Catenation operator + The + operator can also be used to add (catenate) strings It is used very often in statements that generate output If at least one operand is a string then a result is formed by joining two strings When one operand is not a string then the equivalent string representing that non-string's value is generated, and then the catenation of two strings is carried out forming a new string Example: int x = 10; int y = 11; System.out.println("the total is "+x+y); 1/18/2017 Output System.out Generate output for the user So far we can use println(. . . ) print(. . . ) -- it does not automatically advance to a new line They are methods belonging to the pre-defined Java class named "System" and an object within System named "out" The output generated is said to go to the standard output device When you use this type of output with BlueJ you will see a window pop up named "Terminal Window" It contains the output produced by the program Example: UsingPrintln 1/18/2017 Output Redirecting System.out By default the println() and print() methods create output displayed on the standard output device also called the Console The default value of System.out is a PrintStream object directed to standard output In BlueJ it is the Terminal Window We can also redirect the output to a file What you need to do Create a new file: File f = new File (“<file name>"); Set a new FileOutputStream: FileOutputStream fs =new FileOutputStream (f); Set a new PrintStream PrintStream ps = new PrintStream (fs); Set the System’s setOut to ps: System.setOut (ps); Start the output using System.out.println Do not forget to close the file using ps.close () 1/18/2017 Output Example: RedirectOutputToFile Note the first 3 lines with the import statements JOptionPane In some situations you may want to use JOptionPane message dialogs in order to provide the user a more interactive experience It can display the output to the user and then the program waits for the user to respond with the click of a button When the pop-up window appears, the program is suspended until the user clicks the OK button Example: UsingDialogBox 1/18/2017 Input Get input from the user by using pre-defined Java classes Scanner class JOptionPane class Scanner class A Scanner object can be used with the standard input stream System.in A typical statement is: Scanner keyboard = new Scanner(System.in) 1/18/2017 Input System is a pre-defined Java class that has an object named “in” After a variable (like keyboard) is defined the programmer can use methods defined for a scanner object to get values the user has typed on the keyboard These values input by the user are referred to as tokens in Java Some of the most useful methods for scanner: 1/18/2017 Input System is a pre-defined Java class that has an object named “in” Example: UsingScannerForInput use next(), nextDouble(), and nextInt() to obtain a user's inputs (of different types!) JOptionPane class It provides a user with a more interactive experience One popular method defined in JOptionPane is showInputDialog() It prompts the user to enter text 1/18/2017 Input The text the user enters becomes the value of the method Example: String name = OptionPane.showInputDialog("Enter name"); Example: UsingJOptionPane – again, do not forget the import statement 1/18/2017