Expressions, Data Types, Formatted Printing, Scanning CSC 123 Fall 2018 Howard Rosenthal

Size: px
Start display at page:

Download "Expressions, Data Types, Formatted Printing, Scanning CSC 123 Fall 2018 Howard Rosenthal"

Transcription

1 Expressions, Data Types, Formatted Printing, Scanning CSC 123 Fall 2018 Howard Rosenthal

2 Lesson Goals Review the basic constructs of a Java Program Review simple Java data types and the operations on those types Review the concept of casting Review formatted printing Understand how to declare and use variables in Java Programs Review how to formulate assignment statements Review how to read in data from a terminal Using the Scanner object for interactive input Compatibility and casting Note: This is meant to be a quick review, not a complete reteaching. Please ask questions if there is something you don t recognize or remember. 2

3 Key Terms and Program Structures 3

4 Key Terms and Definitions public class Hello { public static void main ( String[] args ) { System.out.println("Hello World!"); } } Above is a source program (source file) for a Java program. The purpose of this program is to type the characters Hello World! on the monitor. The file must be named Hello.java to match the name of the class. The upper and lower case characters of the file name are important. Each class is created in it s own file A program may consist of multiple classes On all computers, upper and lower case inside the program are important. Java is very case sensitive The first line class Hello says that this source program defines a class called Hello. A class is a section of a program. Small programs often consist of just one class. Most programs use multiple classes to create objects Some classes are are imported while other are created by the programmer Every class is contained within a set of braces 4

5 Key Terms and Definitions (2) When the program is compiled, the compiler will make a file of bytecodes called Hello.class. - This is the file that the JVM uses. If the file is named hello.java with a small h it will compile but hello.class won t exist if the code declares the class with a capital H It will create a class Hello.class that will work but keep it simple and follow the capitalization exactly Methods are built out of statements. The statements in a method are placed between braces { and } as in this example. A method is a section of a class that performs a specific task All programs start executing from the main method Each method is contained within a set of braces Braces For every left brace { there is a right brace } that matches. Usually there will be sets of matching braces inside other sets of matching braces. The first brace in a class (a left brace) will match the last brace in that class (a right brace). A brace can match just one other brace. Use indenting to show how the braces match (and thereby show the logic of the program). Look at the example. Increase the indenting by three spaces for statements inside a left and right brace. If another pair of braces is nested within those braces, increase the indenting for the statements they contain by another three spaces. Line up the braces vertically. With Notepad++ the indent levels for both braces and parentheses are color coded After a left brace an indent will be created for you automatically Make sure that you step back to align your left and right braces You can also indent when necessary by using the tab key 5

6 Key Terms and Definitions (3) Most classes contain many more lines than this one. Everything that makes up a class is placed between the first brace { and its matching last brace }. The name of the class (and therefore the name of the file) is up to you. By convention the first letter of a class is typically upper case. If the class has a compound name each word in the name starts with a uppercase letter i.e. NumberAdder A source file always end with.java in lower case. Therefore the file name is ClassName.java In programming, the name for something like a class, a method or a variable is called an identifier. An identifier consists of alphabetical characters and digits, plus the two characters '_' and '$' - underscore and dollar sign The first character must be alphabetical, the remaining characters can be mixed alphabetic characters and digits or _ or $. No spaces are allowed inside the name. An expression is a sequence of symbols (identifiers, operators, constants, etc.) that denote a value 3*(2*x+y)-6*z 6

7 Key Terms and Definitions (4) A reserved word is a word like class that has a special meaning to the system. For example, class means that a definition of a class immediately follows. You must use reserved words only for their intended purpose. (For example, you can't use the word class for any other purpose than defining a class.) Page 25 0f the text lists reserved words A statement in a programming language is a command for the computer to do something. It is like a sentence of the language. A statement in Java is always followed by a semicolon. A group of statements within a set of braces is called a block We will learn that each block level defines a scope for the variables defined within that scope The part "Hello World!" is called a String. A String is a sequence of characters within double quotes. This program writes a String to the monitor and then stops. 7

8 Reserved Keywords In Java The table below lists all the words that are reserved Java. Notice that all the reserved words are lower case abstract assert boolean break byte case catch char class const* continue default double do else enum extends false final finally float for goto* if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while *Even though goto and const are no longer used in the Java programming language, they still cannot be used as variable names. 8

9 Comments A single line comment begins with // This // can come at the beginning of the line or after a statement on the line : System.out.println("On a withered branch" ); // Write first line of the poem Multiline comments begin/* and end */ /* Program 1 Write out three lines of a poem. The poem describes a single moment in time, using 17 syllables. */ It is a good idea to fully comment your program This includes describing the logic, and defining your variables Using descriptive variable names makes this much easier 9

10 10

11 Data Types and Operators A data type is a set of values together with an associated set of operators for manipulating those values. Who can think of some basic data types in the numerical world? The logical world? When an identifier is used as a variable it always has a defined data type The meaning of the 0 s and 1 s in the computer depends on the data type being represented We will begin by defining the eight primitive data types byte, short, int, long, float, double, char and boolean all lower case 11

12 Data Types and Operators (2) All data in Java falls into one of two categories: primitive data types, and reference data types which refer to objects that are created from classes. There are only eight primitive data types - byte, short, int, long, float, double, char, and boolean. Reference data types are memory addresses that refer to objects Java has many different classes, and you can invent as many others as you need. Much more will be said about objects in future chapters (since Java is a object oriented programming language). The following is all you need to know, for now: A primitive data value uses a small, fixed number of bytes. There are only eight primitive data types. A programmer cannot create new primitive data types. 12

13 Some Notes on Objects An object is a big block of data. An object may use many bytes of memory. An object usually consists of many internal pieces. The data type of an object is called its class. Many classes are already defined in Java. A programmer can invent new classes to meet the particular needs of a program. We create classes and access the methods of those classes Some classes have static methods that are accessed without creating new objects We will see the differences as we move ahead In CSC 123 we learn how to create separate classes and how to instantiate objects from those classes 13

14 There Are Eight Primitive Data Types In Java 14

15 Primitive Numeric Data Types (1) Numbers are so important in Java that 6 of the 8 primitive data types are numeric types. There are both integer and floating point primitive types. There are 4 integer data types byte a single byte used for small integers short two bytes int 4 bytes all integers are assumed to be of type int long 8 bytes use for very large number 15

16 Primitive Numeric Data Types (2) There are two data types that are used for floating point numbers float - 4 bytes double - 8 bytes this is the default for all floating constants and is used in almost all cases for floating point arithmetic Floating point numbers, unlike integers, are not always precise. If you compare floating point numbers you can get errors or unexpected results when executing due to the way that they are represented in the computer Due to this lack of perfect precision we usually prefer to use double over float for real numbers that aren t integers, since the precision is greater, although still not perfect. As we will see shortly, there are casting issues when you mix numbers, especially with floating point numbers Java has advanced methods using objects to calculate numbers even more precisely This class called BigDecimal is used for very precise monetary and scientific calculations In the tables, E means "ten to the power of". So 3.5E38 means 3.5 x

17 Primitive Numeric Data Types (3) There is a fundamental difference between the the representations of integers and floating point numbers in the computer. Integer types have no fractional part; floating point types have a fractional part. On paper, integers have no decimal point, and floating point types do. But in main memory, there are no decimal points: even floating point values are represented with bit patterns. 17

18 Summary of Primitive Numeric Data Types Integer Primitive Data Types Type Size Range byte 1 byte (8 bits) -128 to +127 short 2 bytes (16 bits) -32,768 to +32,767 int long 4 bytes (32 bits) 8 bytes (64 bits) -2 billion to +2 billion (approximately) -9E18 to +9E18 (approximately) Remember: Integer data types reserve the leftmost bit to indicate positive (0) or negative (1) in two s complement format Floating Point Primitive Data Types Type Size Range float 4 bytes (32 bits) -3.4E38 to +3.4E38 double 8 bytes (64 bits) -1.7E308 to 1.7E308 In the tables, E means "ten to the power of". So 3.5E38 means 3.5 x

19 Numeric Operators (1) Operator Meaning Precedence - unary minus highest + unary plus highest * multiplication middle / division middle % remainder /modulus middle + addition low - subtraction low Precedence of operators can take the place of parentheses, but just as in algebra, you should use parentheses for clarity. Where there are no parentheses and equal precedence evaluation is from left to right 19

20 Numeric Operators (2) All of these operators can be used on floating point numbers and on integer numbers. The % operator is rarely used on floating point. (we won t be using it, but the remainder concept would be similar) When mixing floating point numbers and integer numbers, floating point takes precedence this is called casting An integer operation is always done with 32 bits or more. If one or both operand is 64 bits (data type long) then the operation is done with 64 bits. Otherwise the operation is done with 32 bits, even if both operands are of a lesser data type than 32 bits. For example, with 16 bit short variables, the arithmetic is done using 32 bits: 20

21 Exponents There is no exponent operator in java You can use Math.pow(x,y) to obtain the value of x y There is also a special method Math.sqrt(x) to obtain the square of x Math.sqrt(x) is equivalent to Math.pow(x,.5) Math.pow and Math.sqrt both are of type double 21

22 Arithmetic, Casting, etc. 22

23 Integer Arithmetic In integer arithmetic you always truncate 7/2 = 3 11/4 = 2 The modulus operator gives you the remainder 7%4 = 3 9%2 =? Any ideas on where the % can be helpful? Note: In Java the sign of the result of a%b is always the sign of a (the dividend). 23

24 Casting Java is a highly type sensitive language When evaluating any expression with operands of different types Java first promotes or casts the operand of the smaller data type By smaller we mean the range byte is smaller than short which is smaller than int which is smaller than long which is smaller than float which is smaller than double boolean expressions are never cast char automatically casts up to int, not to short You can only cast downwards explicitly, otherwise you may create an error Example : int a =10; short b =5; a = b; This is casting upwards it is implicit and automatic b = (short)(a); This is casting downwards must be explicit 24

25 Mixing Numeric Data Types (1) If both operands are integers, then the operation is an integer operation. If any operand is double, then the operation is double = = = 14.4 (15/2) +7.4 =? (15%2) =? The numbers are casted upwards This becomes more important in the next chapter when we learn about typing variables Note: Unless otherwise declared all decimals are assumed to be of type double 25

26 Mixing Numeric Data Types (2) Remember that without parentheses you follow the hierarchy Mixed integer/decimal addition is cast to decimal when the mixing occurs (10.0+5) = /4*(18.0) = 36.0 (5/9) *( ) = 0.0 Note: Integers can be of type byte, short, int, long, but default to int However you can directly assign an int to a short or byte variable (if it fits with the range) short b =5; works Floating point numbers can be of type double or float, but default to double Example: float z; z = ; this creates an error Why? Java doesn t allow the double to cast down because of precision issues z = (float)( ); - This is correct we explicitly cast down. 26

27 Relational Operators 27

28 Type boolean Type boolean identifiers can have only one of two values true or false. (1 or 0) A boolean value takes up a single byte. There are three operators && - means and both operands must be true for the value of the expression to be true - means or one of the operands must be true for the value of the expression to be true! - means not p q p&&q (and) p q (or)!p (not) true true true true false true false false true false false true false true true false false false false true 28

29 Type boolean Short Circuiting There are also boolean operators & and What s the difference? When you use && or the compiler is more efficient, it can shortcircuit when necessary This means that once it determines if a statement is true or false it stops evaluating i.e.: (true false) false it is evaluated true after the first is evaluated (true && false) && true same idea, but evaluates as false after first && So when is there a problem: If you try to assign a logical value (allowed) this might not take place if there is short circuiting: (true false) (a= true) a doesn t get assigned the value true (a= true) is allowed as the expression evaluates as true (true false) (a= true) a does get assigned the value true Don t use these types of assignment statements inside of boolean statements it will inevitably lead to errors 29

30 Relational Operators Operator Description Example (with A=2, B=5 == Checks if the value of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.!= > Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A!= B) is true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= <= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. (A <= B) is true. The result of applying a relational operator is a true or false value 30

31 The hierarchy is very similar to what you know from algebra When there is an equivalent hierarchy level and no parentheses you evaluate from left to right When in doubt use parentheses Operator Hierarchy Priority Operators Operation Associativity [ ] array index 1 () method call left. member access ++ pre- or postfix increment -- pre- or postfix decrement + - unary plus, minus 2 ~ bitwise NOT right! boolean (logical) NOT (type) type cast new object creation 3 * / % multiplication, division, remainder left + - addition, subtraction 4 left + String concatenation << signed bit shift left 5 >> signed bit shift right left >>> unsigned bit shift right < <= less than, less than or equal to 6 > >= greater than, greater than or equal to left instanceof reference test == equal to 7 left!= not equal to & bitwise AND 8 left & boolean (logical) AND ^ bitwise XOR 9 left ^ boolean (logical) XOR bitwise OR 10 left boolean (logical) OR 11 && boolean (logical) AND left 12 boolean (logical) OR left 13? : conditional right = assignment *= /= += -= %= 14 right <<= >>= combinated assignment >>>= &= ^= = 31

32 Some Extra Examples 5>4 true 4>5 false (5>4) (4>5) -? (5>4) && (4>5) -? 32

33 Evaluate as true or false true false && 3 < 4!(5==7) Another Example (true (false && (3 < 4)))!(5==7) putting in the parentheses correctly always helps (true (false && true))!false (true false) true true true true 33

34 34

35 Type char Type char is the set of all characters found on the standard keyboard, and thousands of other characters as well. char is a primitive data type Type char is denoted using single quotes A, 5 Java uses Unicode 2 byte representations that increases the number of characters that can be represented from 127 to 32,767 unique characters in actuality only 7 bits are used for ASCII characters and 15 bits are used for two byte Unicode, the leftmost bit is always zero. Note: Keyboard letters in ASCII Code and Unicode have the same value i.e. A = 65 i.e in ASCII or in Unicode You can add and subtract type char they are actually treated like integers when adding i.e. A +1 = 66 0r char would automatically cast up to int You could cast back down to char by saying (char)(66) which yields B They are added as type int 4bytes to accommodate all Unicode characters The most common characters and their Unicode values are found in Appendix B You can also compare type char values they compare based on their ASCII value ( A < B ) would evaluate as true 35

36 String String is a class in Java with lots of different methods that allows you to manipulate them An individual String is an object, not a basic data type. A String is a sequence of characters enclosed in double quotes Java provides a String class and we can create String objects Why does String have a capital S while primitive data types have lower case first letters String is the name of a class Strings can be concatenated I am + a man would evaluate as I am a man Strings and values Everything depends on the order The sum of two numbers is + (5*2) prints as The sum of two numbers is 10 Why? You always work from inside the parentheses outwards However ( The sum of two numbers is 5 ) + 2 prints as The sum of two numbers is 52 In Chapter 9 we do a lot more with String objects 36

37 Casting With Strings and Characters A + B = 131 (integer) A + B = AB (String) A + B = AB (String) + A + B = AB (String) A gets cast to String A + B + = 131 (String) = 7 (String) = 34 (String) Key is that without parentheses we are reading left to right 37

38 38

39 Printing and Special Characters The System.out object is a predefined instance of a class called PrintStream, and is included with the basic java.lang and therefore is always available for use. It is called the standard output object, and prints to the terminal We will learn how to print to other File objects later in this term We will be using several basic static methods from this class System.out.println( abc ) // prints the String and a character return System.out.print ( abc ) // prints a String without a character return Escape sequences inside the String can be used to control printing Escape Sequence Character \n newline \t tab \b backspace \f form feed \r return \" " (double quote) \' ' (single quote) \\ \ (back slash) \udddd character from the Unicode character set (DDDD is four hex digits) used when the character isn t available during input 39

40 Printing Example public class PrintAPoem { public static void main (String[] args) { System.out.println ( He wrote his code ); System.out.print( \the indented well\n ); System.out.println( \ttill he was done ); System.out.print( \nthe Author\n ); } } He wrote his code He indented well Till he was done The Author System.out.println(concatenated String) prints and goes to the next line System.out.print(concatenated String) prints and stays on the same line 40

41 Printing Example Concatenation in Print Statements When you write expressions in a System.out.println() statement the expression may or may not be calculated first, depending on if and where you put the parentheses The rules are exactly the same as used when concatenating String(s) Ultimately the println method will output a single String public class PrintingNumbers //Class name { public static void main ( String[] args ) { System.out.println("The sum of is " + (5+6)); System.out.println("The sum of is " + 5+6); System.out.println("The sum of " +5 +" + " +6 + " is " +(5 + 6)); } } 41

42 Formatted Printing with printf (1) For simple formatted outputs, each format parameter aligns to the subsequent variable or constant after the String It is possible to more clearly format your output with the printf method Width, precision, leading blanks, signs, etc. can all be controlled The printf method has a String followed by a number of primitive or object variables to be printed You can also specify formatting a geographic area, but we ll ignore that for now Please use printf as opposed to println and print in this class to the greatest extent possible Nice reference Development/UsingJavasprintfMethod.htm 42

43 Formatted Printing with printf (2) System.out.printf( characters %format1 characters %format2 characters %format3, varorconst1, varorconst2, varorconst3); The first parameter is a String (in double quotes) that lays out the sentence and format for each variable, and includes special control characters There is a one to one mapping of format to variable The variable must match the format type Example System.out.printf( The average of %,d students taking %d exams is %3.2f\n, 1250, 4, ); // prints out as: The average of 1,250 students taking 4 exams is Each format specification begins with % and ends with the format specifier type (see next page) 43

44 Some Key Conversion Character Specifiers For Formatted Output Specifier Name Example %b or %B boolean false or FALSE %c or %C character f or F %d decimal integer 189 %e exponential floating 1.59e+01 %f Floating point number 15.9 %s or %S String if Java Java or JAVA %x or %X Hexadecimal integer 1f2a or 1F2A %% The percent symbol % We will also learn several other important elements Flags for left justified, etc. Width - specifies the field width for outputting the argument and represents the minimum number of characters to be written to the output Precision - used to restrict the output depending on the conversion and specifies the number of digits of precision when outputting floating-point values. 44

45 Important Control Characters Control Character Name \n new line \t tab \\ Prints \ Always placed inside the String 45

46 Controlling Integer Output With printf The %wd means reserve a minimum of w spaces, right justified The in %-wd means left justified The 0 in %0d means left fill with 0 s The + in %+d means add a positive sign for positive numbers A ( encloses a negative number in parentheses A, is used as a group separator (may work differently outside of U.S.) See Printf1.java 46

47 Simple Formatted Output With Decimals For simple formatted outputs, each format parameter aligns to the subsequent variable or constant after the String public class Printf2 { } public static void main(string[] args) { double x = 27.5, y = 33.75; System.out.printf("x = %f y = %f\n", x, y); } Output: x = y =

48 Controlling Formatted Outputs With Decimals Uses the same formatting structures as integers Adds the ability to specify the number of decimal places to the right of the decimal point, as opposed to printing a minimum of a default 6 %w.nf has a minimum width of w and n decimal places %#w.nf the # guarantees a decimal point Variable associated with f must be of type double or float - it won t cast up any type of integer Note: On some machines it may not do a perfect job in rounding as it uses bankers rounding Bankers Rounding is an algorithm for rounding quantities to integers, in which numbers which are equidistant from the two nearest integers are rounded to the nearest even integer. Thus, 0.5 rounds down to 0; 1.5 rounds up to 2. It has been extended to be used at any level of precision would print to two places as 1.68 while would also round to two places as 1.68 See See Printf3.java 48

49 Controlling Other Formatted Outputs (1) Strings with %-ws - will left justify w specifies width s is for a String If s is capitalized then the entire String prints capitalized We will learn how to use String variables later this semester Same rules apply for c (char) and b (boolean) See Printf4.java 49

50 Formatted Printing With printf Putting It All Together (1) See Printf5.java 50

51 51

52 What is a Variable A variable (either primitive or a reference) is a named memory location capable of storing data of a specified type Variables indicate logical, not physical addresses Those are taken care of in the JVM and the OS Variables in Java always have a specific data type Variables must always be declared before they can be used Remember that a data type is a scheme for using bit patterns to represent a value or a reference. Think of a variable as a little box made of one or more bytes that can hold a value using a particular data type. double Cost_of_Home 128,

53 What is a Variable (2) A declaration of a variable is made if a program requires a named variable of a particular type Three things happen The variable is named with an identifier The amount of space required for the variable is defined How the bits in that space are interpreted is defined The value of a variable is always its last declared or assigned value in a program public class Example1_CH3 { public static void main ( String [] args ) { long payamount; //the declaration of the variable payamount = 123; // variable assignment System.out.println("The variable payamount contains: " + payamount); payamount = -8976; // variable reassignment System.out.printf("The variable payamount contains: %d\n,payamount); } } 53

54 Declaring Variables Variables must be declared before they are used Basic syntax: Type name1, name2, name3 ; Example: double dinner_bill, creditbalance, moneyinbank;//three variables of type double Variables can be explicitly initialized when they are declared short rent = 75; double milkprice_half = 1.99; boolean testimony = true; Can t do multiple assignments at once when declaring variables int x=y=z=0; // Incorrect syntax int x,y,z=60; // only z is initialized, but good syntax int x=60, y=60, z=60; //all three are initialized, good syntax Don t try to assign a value that that is illegal short big_number = ; This gives an error why? 54

55 Naming Variables (1) Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', character '_', and character '$'. Just like any other identifier A variable name cannot contain the space character. Do not start with a digit A variable can be any number of characters Java is case sensitive. Upper and lower case count as different characters SUM and Sum are different identifiers A variable name cannot be a reserved word Don t use the same name twice, even as different types it will generate an error during compilation Programmers should follow the good practice of creating meaningful identifier names that self-describe an item's purpose Meaningful names make programs easier to maintain userage, housesquarefeet, and numitemsonshelves Good practice minimizes use of abbreviations in identifiers except for wellknown ones like num in numpassengers Abbreviations make programs harder to read and can also lead to confusion, such as if a chiropractor application involves number of messages and number of massages, and one is abbreviated nummsgs (which is it?) 55

56 Naming Variables (2) There are certain conventions used by java programmers Variables and methods start with a lower case letter with the exception of final variables (slide 59) i.e. var1, interest Multiword variables capitalize the first letter of subsequent words i.e. interestrate, milesperhour Names of classes by convention begin with a capital letter i.e. Calculator, MyProgram 56

57 Assigning Variables Assignment statements look like this: variablename = expression ; //The equal sign = is the assignment operator variablename is the name of a variable that has been declared previously in the program. Remember: An expression is a combination of literals, operators, variable names, and parentheses used to calculate a value must be syntactically correct Assignment is accomplished in two steps: Evaluate the expression Store the value in the variable which appears to the left of the = sign Examples : int total; double price, tax; total = 3 + 5; // total =8 price = 34.56; tax = price*0.05; //tax = While you can t do a multiple assignment in a declaration statement, you can do multiple assignments once the variables have been declared: int x,y,z; //declaration of the variables x=y=z=0; // works as an assignment statement provided the variables have been declared previously these work right to left int x=y=z=3; // This will generate a syntax error because you are first declaring the variables here These two statements also work: int x,y,z; x=y=z=14+5; // First calculate the value of the expression, then do the assignments Only rightmost part in multi-assignment can be an expression, all the rest must be variables 57

58 Assigning Variables (2) Primitive variables must be initialized before they are used They aren t given a default value They are typically initialized by reading in a value You can also explicitly initialize in the code int value; value = value + 10; // this gives an error as value wasn t initialized 58

59 final Variables final variables are really constants They are assigned a value that doesn t change final double PI = ; final int PERFECT = 100; final variables are by convention written with all capitals It is legal to defer initialization of a final variable, provided that it is initialized exactly once before it is used for the first time boolean leapyear =true; final int DAYS_IN_FEBRUARY; if (leapyear) DAYS_IN_FEBRUARY= 29; else DAYS_IN_FEBRUARY= 28; 59

60 An Example of a Simple Program (1) The Fibonacci sequence is 1,1,2,3,5,8,13,21,34,55. The next number is the sum of the previous two numbers. Pseudocode for printing Fibonacci series up to 50 Set the low number =1 Set the high number equal to 1 Print the low Start of Loop check that high is less than 50 Print the high Set the high equal to the low+high Set the low equal to the high -low Repeat loop 60

61 An Example of a Simple Program (2) public class Fibonacci { // Print out the Fibonacci sequence for values < 50 public static void main(string[] args) { int lo = 1; int hi = 1; System.out.printf( %d\n,lo); while (hi < 50) { System.out.println(hi); hi = lo + hi; // new hi lo = hi - lo; /* new lo is (sum - old lo) i.e., the old hi */ } } } Note: also look at Fibonacci2.java 61

62 62

63 Obtaining Input Data Using Scanner Scanner is a class. You must include the following statement to use the class to create a Scanner object: import java.util.scanner; or import java.util.*; You are importing a class with all it s methods that can then be used to create objects Declare a Scanner object variable and create an object: Scanner scannername = new Scanner (System.in); new means you are creating a new object new is a reserved word System.in is a variable that tell the Java program that this input stream is coming from the keyboard You can now access seven types of primitive input: byte, short, int, long, double, float and boolean using predefined methods associated with the Scanner class A Scanner object doesn t read characters We will learn a way around this when we study the String object The scannername is just another variable name It contains an address which refers to the Scanner object you have created 63

64 There are 7 Input Methods Available For Primitive Data Types ScannerName.nextByte() ScannerName.nextShort() ScannerName.nextInt() ScannerName.nextLong() ScannerName.nextDouble() ScannerName.nextFloat() ScannerName.nextBoolean() Note: the type names are capitalized in these methods Note: There is no way to directly input a char with a Scanner object What you are looking at above is the standard way objects access methods: objectname.method(par1, par2, ) - There are no parameters required for the Scanner methods 64

65 Each Scanner Object Is Created From The Scanner Class keyboard Name0f input file (System.in) Constructor used to create object Methods nextbyte() nextshort() nextint() nextlong() nextfloat() nextdouble() nextboolean() next() nextline() hasnext() o

66 An Example Showing Scanner Usage import java.util.scanner; public class ScannerUsage { public static void main(string [] args) { Scanner keyboard = new Scanner(System.in); // Creates a new Scanner called keyboard System.out.println("Enter an integer of type int"); int n1 = keyboard.nextint(); System.out.printf("Enter an integer of type byte\n"); byte b1 = keyboard.nextbyte(); } } float f1; double d1; long l1; short s1; boolean bn1; System.out.println("Enter a floating point of type float"); f1 = keyboard.nextfloat(); System.out.printf("Enter a floating point of type double and Enter an integer of type long\n"); d1 = keyboard.nextdouble(); l1 = keyboard.nextlong(); System.out.printf("Enter an integer of short int and Enter boolean value\n"); s1 = keyboard.nextshort(); bn1 = keyboard.nextboolean(); System.out.println("n1 = " + n1 +"\nb1 = " + b1 + "\nf1 = " + f1 + "\nd1 = " + d1); System.out.printf("l1 = %d\ns1 = %d\nbn1 = %b\n, l1, s1, bn1); 66

67 A Practical Example Using Scanner import java.util.scanner; // Make the Scanner class available. public class Interest2WithScanner { public static void main(string[] args) { Scanner keyboard = new Scanner( System.in ); // Create the Scanner. double principal; // The value of the investment. double rate; // The annual interest rate. double interest; // The interest earned during the year. System.out.printf("Enter the initial investment: "); //always ask for an input with a question principal = keyboard.nextdouble(); System.out.printf("Enter the annual interest rate as a percent"); rate = keyboard.nextdouble(); rate = rate/100; interest = principal * rate; // Compute this year's interest. principal = principal + interest; // Add it to principal. System.out.printf("The value of the investment after one year is $ %.2f\n, principal); } } // end of class Interest2withScanner 67

68 68

69 Casting (1) The value of a smaller numerical type may be assigned to a higher numerical data type automatically Do you know the order? Casting down must be done explicitly Example: int natural, bigger; double odds, othernumber; odds = 20.3; natural = 5; othernumber = (int)(odds)*natural; bigger = (int)othernumber; System.out.printf( %.1f\n,otherNumber); //prints System.out.println(bigger); //prints 100 othernumber = odds*natural; bigger = (int)othernumber; System.out.printf( %.1f\n,otherNumber); //prints System.out.println(bigger); //prints

70 Casting (2) Remember that float is a special case that always requires casting if you are assigning a floating point number to a float variable float x = 15.0; //This creates an error float y = (float)15.0; //This is proper explicit casting float z = 15; //Implicit casting 70

71 Casting (3) Character data may be assigned to any of the types short, int, long, double or float When this happens the ASCII/Unicode value is assigned to the numerical value double x = A ; System.out.printf( %.1f, x); The output is 65.0 Why? However, char chm = A ; System.out.printf( %c, chm); The output is A 71

72 Shortcuts Operator Shortcut For += x+=10 x=x+10 -= x-=10 x=x-10 *= x*=10 x=x*10 /= x/=10 x=x/10 %= x%=10 x=x%10 72

73 Prefix and Postfix for Incrementing and Decrementing (1) There are two mechanisms for adding or subtracting 1 from a variable ++number; //prefix form for adding 1 to number --number; //prefix form for subtracting 1 from number number++; //postfix form for adding 1 to number number--; //postfix form for subtracting 1 from number What s the difference? In assignment statements prefix action takes effect before the assignment In assignment statements postfix action takes effect after the assignment 73

74 Prefix and Postfix for Incrementing and Decrementing (2) Prefix Incrementing Postfix Incrementing int number =5,result; result = 3*(++number); System.out.printf( %d\n, result); 18 System.out.println(number); 6 int number =5,result; result = 3*(number++); System.out.printf( %d\n, result); 15 System.out.println(number); 6 Use postscript incrementing carefully, it can be confusing However, it is very useful when dealing with loops 74

75 Prefix and Postfix for Incrementing and Decrementing (3) Here is what happens in a postfix in prior example result = 3*(number++); a. temp = number; // a hidden temp is created by the compiler b. number = number +1; c. result = 3*temp; What is the value printed in the following example; int number =10; number = number++; System.out.printf( %d\n, number); 75

76 76

77 Exercise 6. Triangle1Stars Write a program that prints the triangle: * ** *** **** ***** ****** Programming Exercise 1 Use this framework: public class Pname //Class name { public static void main ( String[] args ) //main method header } { } Code goes here //Body Compile with javac Pname.java Execute with java Pname once you compile successfully 77

78 Exercise 2. Uptime Programming Exercise 2 The uptime command of the UNIX operating system displays the number of days, hours and minutes since the operating system was started. For example the UNIX command uptime might return the string Up 53 days 12:39. Write a program that converts the 53 days, 12 hours and 39 minutes to the number of seconds that have elapsed since the operating since was last started. 78

79 Programming Exercise 3 CharSum Write a program that that prints out your initials and the prints out the sum of the ASCII values for the following character sets: N T C A F G The output will look as follows: HGR NTC 229 AF 135 G 71 79

80 Area Programming Exercise 4 Write a program that prompts a user for the dimensions (double) of a room in feet (length, width, height) and calculates and prints out the total area of the floor, ceiling and walls. 80

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal

Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand variables Understand how to declare and use variables in Java Programs Learn how to formulate assignment statements

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Variables and Assignments CSC 121 Fall 2015 Howard Rosenthal

Variables and Assignments CSC 121 Fall 2015 Howard Rosenthal Variables and Assignments CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand variables Understand how to declare and use variables in Java Programs Learn how to formulate assignment statements

More information

Variables and Assignments CSC 121 Fall 2014 Howard Rosenthal

Variables and Assignments CSC 121 Fall 2014 Howard Rosenthal Variables and Assignments CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand variables Understand how to declare and use variables in Java Programs Learn Assignment statements for variables Learn

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Overview of Source Code Components Comments Library declaration Classes Functions Variables Comments Can

More information

Chapter 2. Elementary Programming

Chapter 2. Elementary Programming Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

More information

Basics of Java Programming

Basics of Java Programming Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value Lecture Notes 1. Comments a. /* */ b. // 2. Program Structures a. public class ComputeArea { public static void main(string[ ] args) { // input radius // compute area algorithm // output area Actions to

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Chapter 2 Elementary Programming

Chapter 2 Elementary Programming Chapter 2 Elementary Programming Part I 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Primitive Data Types: Intro

Primitive Data Types: Intro Primitive Data Types: Intro Primitive data types represent single values and are built into a language Java primitive numeric data types: 1. Integral types (a) byte (b) int (c) short (d) long 2. Real types

More information

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers and letters. Think of them

More information

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on: Data and Expressions Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration And Use Of Variables Expressions

More information

A variable is a name for a location in memory A variable must be declared

A variable is a name for a location in memory A variable must be declared Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;

More information

JAVA Programming Fundamentals

JAVA Programming Fundamentals Chapter 4 JAVA Programming Fundamentals By: Deepak Bhinde PGT Comp.Sc. JAVA character set Character set is a set of valid characters that a language can recognize. It may be any letter, digit or any symbol

More information

ECE 122 Engineering Problem Solving with Java

ECE 122 Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction Outline Problem: How do I input data and use it in complicated expressions Creating complicated expressions

More information

CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

More information

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2 ELEMENTARY PROGRAMMING Chapter 2 ELEMENTARY PROGRAMMING Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Objectives To write Java programs to perform simple

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

DEPARTMENT OF MATHS, MJ COLLEGE

DEPARTMENT OF MATHS, MJ COLLEGE T. Y. B.Sc. Mathematics MTH- 356 (A) : Programming in C Unit 1 : Basic Concepts Syllabus : Introduction, Character set, C token, Keywords, Constants, Variables, Data types, Symbolic constants, Over flow,

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University April 21, 2015 Chapter 2: Data and Expressions CS 121 1 / 53 Chapter 2 Part 1: Data Types

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

Important Java terminology

Important Java terminology 1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as

More information

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University January 15, 2015 Chapter 2: Data and Expressions CS 121 1 / 1 Chapter 2 Part 1: Data

More information

Chapter 2 Primitive Data Types and Operations. Objectives

Chapter 2 Primitive Data Types and Operations. Objectives Chapter 2 Primitive Data Types and Operations Prerequisites for Part I Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs,

More information

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

More information

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Writing a Simple Java Program Intro to Variables Readings Your textbook is Big Java (3rd Ed). This Week s Reading: Ch 2.1-2.5, Ch

More information

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic BIT 3383 Java Programming Sem 1 Session 2011/12 Chapter 2 JAVA basic Objective: After this lesson, you should be able to: declare, initialize and use variables according to Java programming language guidelines

More information

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will

More information

Section 2: Introduction to Java. Historical note

Section 2: Introduction to Java. Historical note The only way to learn a new programming language is by writing programs in it. - B. Kernighan & D. Ritchie Section 2: Introduction to Java Objectives: Data Types Characters and Strings Operators and Precedence

More information

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach. DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net COURSE ORGANIZATION 2 Course Elements Lectures: 10 lectures Find schedule and class rooms in online

More information

Programming Lecture 3

Programming Lecture 3 Programming Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements

More information

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public

More information

ANSI C Programming Simple Programs

ANSI C Programming Simple Programs ANSI C Programming Simple Programs /* This program computes the distance between two points */ #include #include #include main() { /* Declare and initialize variables */ double

More information

What did we talk about last time? Examples switch statements

What did we talk about last time? Examples switch statements Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ OBJECT-ORIENTED PROGRAMMING IN JAVA 2 Programming

More information

Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

More information

Chapter. Let's explore some other fundamental programming concepts

Chapter. Let's explore some other fundamental programming concepts Data and Expressions 2 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Data and Expressions Let's explore some

More information

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M. Java Language Essentials Java is Case Sensitive All Keywords are lower case White space characters are ignored Spaces, tabs, new lines Java statements must end with a semicolon ; Compound statements use

More information

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

CEN 414 Java Programming

CEN 414 Java Programming CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 02 Variables and Operators Agenda Variables Types Naming Assignment Data Types Type casting Operators

More information

Values and Variables 1 / 30

Values and Variables 1 / 30 Values and Variables 1 / 30 Values 2 / 30 Computing Computing is any purposeful activity that marries the representation of some dynamic domain with the representation of some dynamic machine that provides

More information

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Walter Savitch Frank M. Carrano Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers

More information

Introduction to Java Applications; Input/Output and Operators

Introduction to Java Applications; Input/Output and Operators www.thestudycampus.com Introduction to Java Applications; Input/Output and Operators 2.1 Introduction 2.2 Your First Program in Java: Printing a Line of Text 2.3 Modifying Your First Java Program 2.4 Displaying

More information

An overview of Java, Data types and variables

An overview of Java, Data types and variables An overview of Java, Data types and variables Lecture 2 from (UNIT IV) Prepared by Mrs. K.M. Sanghavi 1 2 Hello World // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld { public

More information

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester

More information

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Lesson 02 Data Types and Statements MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Topics Covered Statements Variables Constants Data Types

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Declaration and Memory

Declaration and Memory Declaration and Memory With the declaration int width; the compiler will set aside a 4-byte (32-bit) block of memory (see right) The compiler has a symbol table, which will have an entry such as Identifier

More information

Elementary Programming

Elementary Programming Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal

More information

DM503 Programming B. Peter Schneider-Kamp.

DM503 Programming B. Peter Schneider-Kamp. DM503 Programming B Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm503/! VARIABLES, EXPRESSIONS & STATEMENTS 2 Values and Types Values = basic data objects 42 23.0 "Hello!" Types

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Java Notes. 10th ICSE. Saravanan Ganesh

Java Notes. 10th ICSE. Saravanan Ganesh Java Notes 10th ICSE Saravanan Ganesh 13 Java Character Set Character set is a set of valid characters that a language can recognise A character represents any letter, digit or any other sign Java uses

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos. Lecture 2: Variables and Operators AITI Nigeria Summer 2012 University of Lagos. Agenda Variables Types Naming Assignment Data Types Type casting Operators Declaring Variables in Java type name; Variables

More information

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Lesson 02 Data Types and Statements MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Topics Covered Statements Variables Data Types Arithmetic

More information

Reserved Words and Identifiers

Reserved Words and Identifiers 1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the

More information

Getting started with Java

Getting started with Java Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

More information

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2 Java Foundations Introduction to Program Design and Data Structures 4th Edition Lewis TEST BANK Full download at : https://testbankreal.com/download/java-foundations-introduction-toprogram-design-and-data-structures-4th-edition-lewis-test-bank/

More information

Work relative to other classes

Work relative to other classes Work relative to other classes 1 Hours/week on projects 2 C BOOTCAMP DAY 1 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Overview C: A language

More information

4 Programming Fundamentals. Introduction to Programming 1 1

4 Programming Fundamentals. Introduction to Programming 1 1 4 Programming Fundamentals Introduction to Programming 1 1 Objectives At the end of the lesson, the student should be able to: Identify the basic parts of a Java program Differentiate among Java literals,

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:

More information

COMP 202 Java in one week

COMP 202 Java in one week CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

More information

The Java Language Rules And Tools 3

The Java Language Rules And Tools 3 The Java Language Rules And Tools 3 Course Map This module presents the language and syntax rules of the Java programming language. You will learn more about the structure of the Java program, how to insert

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All for repetition statement do while repetition statement switch multiple-selection statement break statement continue statement Logical

More information

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M tutor Isam M. Al Jawarneh, PhD student isam.aljawarneh3@unibo.it Mobile Middleware

More information

2.5 Another Application: Adding Integers

2.5 Another Application: Adding Integers 2.5 Another Application: Adding Integers 47 Lines 9 10 represent only one statement. Java allows large statements to be split over many lines. We indent line 10 to indicate that it s a continuation of

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g. 1.3a Expressions Expressions An Expression is a sequence of operands and operators that reduces to a single value. An operator is a syntactical token that requires an action be taken An operand is an object

More information

JAVA Ch. 4. Variables and Constants Lawrenceville Press

JAVA Ch. 4. Variables and Constants Lawrenceville Press JAVA Ch. 4 Variables and Constants Slide 1 Slide 2 Warm up/introduction int A = 13; int B = 23; int C; C = A+B; System.out.print( The answer is +C); Slide 3 Declaring and using variables Slide 4 Declaring

More information