CHAPTER 3,4 & 5. Contents:

Size: px
Start display at page:

Download "CHAPTER 3,4 & 5. Contents:"

Transcription

1 CHAPTER 3,4 & 5 Contents: *Understanding a Simple java program *Basic Program elements Character set, comments, java tokens, main method, data types. *Variable/identifiers and rules for identifier *Constants/literals, and types of Literals. *Escape sequences. *Operators and operands. *Types of operators in java. * Precedence of Java Operators. *Introduction to Control structures *Conditional structures: if,if else, if else if else and switch. *Repetitive control structures: while,do while and for.

2 My First java Program //This program prints Welcome to Java! public class Hello { public static void main(string[] args) { System.out.println("Welcome to Java!"); Comments Comments are important because they make the programmer feel convenient to understand the logic of the program. Although these comments are ignored(not read) by the Java compiler, they are included in the program for the convenience of the user to understand it. To provide the additional information about the code, use comments. These comments give the overview of the code in the form of the information which is not available in the code itself. There are two types of comments used in Java. They are: 1. // text To add a comment to the program, we can use two slashes characters i.e. //. The line starting from slashes to the end is considered as a comment. We can write only a single line comment use these slashes. For example: // This comment extends to the end of the line. // This type of comment is called a "slash-slash" comment 2. /* text */ To add a comment of more than one line, we can precede our comment using /*. The precise way to use this is to start with delimiter /* and end with delimiter */. Everything in between these two delimiters is discarded by the Java compiler. For example:

3 /* This comment, a "slash-star" comment, includes multiple lines. It begins with the slash-star sequence (with no space between the '/' and '*' characters) and extends to the star-slash sequence. */ Declaring classes and methods If you're declaring a class or a method, you have to tell Java the name that you want to associate with the class or method, and how accessible it is to be from elsewhere in your application. Our class is declared in this example as public class Hello which means: It's available to any other class (public) It's a class (class) It's called Hello (Hello)Java Programming for the Web Hello Java World Our method is declared as public static void main(string[] args) which means: It's available to run from any other class (public) It's not dependent on any particular object (static) It doesn't pass anything back to the code that calls it (void) It's called main (main) It takes one parameter, an array of Strings that it will know as "args" Reading Input from the Console(keyboard) 1. Create a Scanner object Scanner input = new Scanner(System.in); 2. Use the methods nextdatatype() example: nextbyte() for byte, nextshort() for short, nextint() for int, nextlong() for long, nextfloat() for float, nextdouble() for double. For example:- System.out.print("Enter a double value: "); Scanner input = new Scanner(System.in); double d = input.nextdouble(); //This program prints Welcome to Java!

4 public class Hello { public static void main(string[] args) { System.out.println("Welcome to Java!"); BLOCKS: A pair of braces in a program forms a block that groups components of a program. public class Test { public static void main(string[] args) { System.out.println("Welcome to Java!"); Method block Class block The main method: The main method provides the control of program flow ( main function has the actual logic or actual calculation of the program.it is the main body of program which controls the actual work of program). The Java interpreter starts executes the program by invoking(calling/reading) the main method. The main method looks like this: public static void main(string[] args) { // Statements; The Java Character Set

5 lower-case <= a b c d e f g h i j k l m n o p q r s t u v w x y z upper-case <= A B C D E F G H I J K L M N O P Q R S T U V W X Y Z alphabetic <= lower-case upper-case numeric <= alphanumeric <= alphabetic numeric special <=! % ^ & * ( ) - + = { ~ [ ] \ ; ' : " < >?,. / ` _ graphic <= alphanumeric special Java tokens The Smallest individual units in a program are called tokens. Java language includes five types of tokens 1) Reserved words 2) Identifiers 3) Literals 4) Operators 5) Separators 1)Reserved words: Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. For example, when the compiler sees the word class, it understands that the word after class is the name for the class. Keywords are identifiers that Java reserves for its own use. These identifiers have built-in meanings that cannot change. Thus, programmers cannot use these identifiers for anything other than their built-in meanings. Technically, Java classifies identifiers and keywords as separate categories of tokens. abstract continue goto package switch assert default if private this boolean do implements protected throw break double import public throws

6 byte else instanceof return transient case extends int short try catch final interface static void char finally long strictfp volatile class float native super while const for new synchronized Notice that all Java keywords contain only lower-case letters and are at least 2 characters long; therefore, if we choose identifiers that are very short (one character) or that have at least one upper-case letter in them, we will never have to worry about them clashing with (accidentally being mistaken for) a keyword In our example, words like "public" and "class", "static" and "void" are understood by the Java Virtual Machine. Words like "main" and "println" are not understood by the JVM, but are nevertheless unchangeable as they are part of the standard classes and methods provided. On the other hand, the words "Hello" and "args" are our choice, and we can change them if we wish. You must not use words that the JVM itself understands (they are "reserved words") for things you name yourself. You should also avoid using words that relate to standard classes and methods for things you name. 2)Java Identifiers - symbolic names: Identifiers are used to name classes, variables, and methods. Identifier Rules:

7 An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. An identifier cannot be a reserved word. (for example:if, else, while, for, etc are reserved words, and cannot be used as identifiers). An identifier cannot be true, false, or null. An identifier can be of any length In java, variable names are case-sensitive. MyVariable is not the same as myvariable. There is no limit to the length of a Java variable name. A variable name can be of any length. The following are legal variable names: MyVariable myvariable MYVARIABLE x i _myvariable $myvariable _9pins andros ανδρος OReilly This_is_an_insanely_long_variable_name_that_jus t_keeps_going_and_going_and_going_and_well_you_ get_the_idea_the_line_breaks_arent_really_part_ of_the_variable_name_its_just_that_this_variabl e_name_is_so_ridiculously_long_that_it_won't_fi t_on_the_page_i_cant_imagine_why_you_would_need _such_a_long_variable_name_but_if_you_do_you_ca n_have_it The following are not legal variable names: My Variable // Contains a space 9pins // Begins with a digit

8 a+c // The plus sign is not an alphanumeric character testing1-2-3 // The hyphen is not an alphanumeric character O'Reilly // Apostrophe is not an alphanumeric character OReilly_&_Associates // ampersand is not an alphanumeric character Java Data Types For all data, assign a name (identifier) and a data type. Data type tells compiler: How much memory to allocate, format in which to store data, and types of operations you will perform on data? Java is a "strongly typed" language, which means that all identifiers must be declared before they can be used. Jave supports the following primitive data types: byte, short, int, long, float, double, char, boolean. Type Size in Bytes Minimum Value Maximum Value byte short 2-32,768 32,767 int 4-2, 147, 483, 648 2, 147, 483, 647 long 8-9,223,372,036,854,775,808 9,223,372,036,854,775,807 float 4 1.4E E38 double 8 4.9E E308 char 2 character encoded as 0 character encoded as FFFF boolean 2 values true and false Java Data Types

9 For all data, assign a name (identifier) and a data type. Data type tells compiler: How much memory to allocate, format in which to store data, and types of operations you will perform on data? The type of value that a variable will hold is called a data type. As you ay imagine, different variables can be meant to hold different types of values Java is a "strongly typed" language, which means that all identifiers must be declared before they can be used. There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a key word. Let us now look into detail about the eight primitive data types. 1)byte: Byte data type is a 8-bit signed two s complement integer. Minimum value is -128 (-2^7) Maximum value is 127 (inclusive)(2^7-1) Default value is 0 Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int. Example : byte a = 100, byte b = -50

10 2)short: Short data type is a 16-bit signed two's complement integer. Minimum value is -32,768 (-2^15) Maximum value is 32,767(inclusive) (2^15-1) Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int Default value is 0. Example : short s= 10000, short r = )int: Int data type is a 32-bit signed two's complement integer. Minimum value is - 2,147,483,648.(-2^31) Maximum value is 2,147,483,647(inclusive).(2^31-1) Int is generally used as the default data type for integral values unless there is a concern about memory. The default value is 0. Example : int a = , int b = )long: Long data type is a 64-bit signed two's complement integer. Minimum value is -9,223,372,036,854,775,808.(- 2^63) Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63-1) This type is used when a wider range than int is needed. Default value is 0L. Example : int a = L, int b = L 5)float:

11 Float data type is a single-precision 32-bit IEEE 754 floating point. Float is mainly used to save memory in large arrays of floating point numbers. Default value is 0.0f. Float data type is never used for precise values such as currency. Example : float f1 = 234.5f 6)double: double data type is a double-precision 64-bit IEEE 754 floating point. This data type is generally used as the default data type for decimal values. generally the default choice. Double data type should never be used for precise values such as currency. Default value is 0.0d. Example : double d1 = )boolean: boolean data type represents one bit of information. There are only two possible values : true and false. This data type is used for simple flags that track true/false conditions. Default value is false. Example : boolean one = true 8)char: char data type is a single 16-bit Unicode character. Minimum value is '\u0000' (or 0). Maximum value is '\uffff' (or 65,535 inclusive). Char data type is used to store any character. Example. char lettera ='A'

12 ESCAPE SEQUENCE: Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences. An escape sequence is regarded as a single character and is therefore valid as a character constant. Java language supports few special escape sequences. They are: Notation Character represented \n Newline (0x0a) \r Carriage return (0x0d) \f Formfeed (0x0c) \b Backspace (0x08) \s Space (0x20) \t tab \" Double quote \' Single quote \\ backslash What are variables? A variable is a container that holds values that are used in a Java program. To be able to use a variable it needs to be declared. Declaring variables is normally the first thing that happens in any program. Example: a is variable. a can contain any number as its value.(eg: a=2) Variables are used for calculation and storing the result. Lets consider a variable called square. Now square=a*a; the result of a*a is put in another variable called square.

13 Naming variables Rules that must be followed when naming variables or errors will be generated and your program will not work: No spaces in variable names No special symbols in variable names such Variable names can only contain letters, numbers, and the underscore ( _ ) symbol Variable names can not start with numbers, only letters or the underscore ( _ ) symbol (but variable names can contain numbers) Recommended practices (make working with variables easier and help clear up ambiguity in code): Make sure that the variable name describes what it stores - For example, if you have a variable which stores a value specifying the amount of chairs in a room, name it "numchairs". Make sure the variable name is of appropriate length - Should be long enough to be descriptive, but not too long. Also keep in mind: Distinguish between uppercase and lowercase - Java is a case sensitive language which means that the variables varone, VarOne, and VARONE are three separate variables! When referring to existing variables, be careful about spelling - If you try to reference an existing variable and make a spelling mistake, an error will be generated.

14 Printing variables Variables are printed by including the variable name in a System.out.print() or System.out.println() method. When printing the value of a variable, the variable name should NOT be included in double quotes. You can also print variables together with regular text. To do this, use the + symbol to join the text and variable values. class PrintText{ public static void main(string[] args){ //declare some variables byte abyte = -10; int anumber = 10; char achar = 'b'; boolean isboolean = true; //print variables alone System.out.println(aByte); System.out.println(aNumber); //print variables with text System.out.println("aChar = " + achar); System.out.println("Is the isboolean variable a boolean variable? " + isboolean); Output: achar = b Is the isboolean variable a boolean variable? true 3)Declaring Constant (literals): In java constant value cannot change during program execution. Syntax: datatype constantidentifier = Value; Note: assigning a value when the constant is declared is optional. But a value must be assigned before the constant is used. Use all capital letters for constants and separate words with an underscore: Example: double TAX_RATE =.05; Declare constants at the top of the program so their values can easily be seen. Declare as a constant any data that should not change during program execution. Examples: int numplayers = 10; // numplayers holds 10 numplayers = 8; // numplayers now holds 8

15 int legalage = 18; int voterage = legalage; The next statement is illegal int height = weight * 2; // weight is not defined int weight = 20; and generates the following compiler error: illegal forward reference. Java Literals: A literal is a source code representation of a fixed value. They are represented directly in the code without any computation. Literals can be assigned to any primitive type variable. For example: byte a = 68; char a = 'A' byte, int, long, and short can be expressed in decimal(base 10),hexadecimal(base 16) or octal(base 8) number systems as well. Prefix 0 is used to indicates octal and prefix 0x indicates hexadecimal when using these number systems for literals. For example: int decimal = 100; int octal = 0144; int hexa = 0x64; String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are:

16 "Hello World" "two\nlines" "\"This is in quotes\"" By literal we mean any number, text, or other information that represents a value. This means what you type is what you get. We will use literals in addition to variables in Java statement. While writing a source code as a character sequence, we can specify any value as a literal such as an integer. This character sequence will specify the syntax based on the value's type. This will give a literal as a result. For instance int month = 10; In the above statement the literal is an integer value i.e 10. The literal is 10 because it directly represents the integer value. Integer Literals An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int. It is recommended that you use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1. Values of the integral types byte, short, int, and long can be created from int literals. Values of type long that exceed the range of int can be created fromlong literals. Integer literals can be expressed these number systems: Decimal: Base 10, whose digits consists of the numbers 0 through 9; this is the number system you use every day Hexadecimal: Base 16, whose digits consist of the numbers 0 through 9 and the letters A through F Binary: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in Java SE 7 and later)

17 For general-purpose programming, the decimal system is likely to be the only number system you'll ever use. However, if you need to use another number system, the following example shows the correct syntax. The prefix 0x indicates hexadecimal and 0b indicates binary: int decval = 26; // The number 26, in decimal int hexval = 0x1a; // The number 26, in hexadecimal(0x represents hexadecimal number) int binval = 0b11010; // The number 26, in binary(0b represents binary number) Floating-Point Literals A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d. The floating point types (float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted). double d1 = 123.4; double d2 = 1.234e2; // same value as d1, but in scientific notation float f1 = 123.4f; String Literals The string of characters is represented as String literals in Java. We represent string literals as String mystring = "How are you?"; The above example shows how to represent a string. It consists of a series of characters inside double quotation marks. Strings can include the character escape codes as well, as shown here: String example = "Your Name, \"Sumit\""; System.out.println("Thankingyou,\nRichards\n");

18 Boolean Literals The values true and false are also treated as literals in Java programming. When we assign a value to a boolean variable, we can only use these two values.(2 values:true or false) Unlike C++, we can't presume that the value of 1 is equivalent to true and 0 is equivalent to false in Java. We have to use the values true and false to represent a Boolean value. Example: boolean chosen = true; Remember that the literal true is not represented by the quotation marks around it. The Java compiler will take it as a string of characters, if its in quotation marks. Example of literals: Integer literals: 33, 0, -9 Floating-point literals:.3,0.3, 3.14 Character literals: '(','R', 'r', '{' Boolean literals:(predefined values) true, false String literals: "language" "0.2", "r", "" 4)Java Operators: Understanding operators and operands: As we have seen, a mathematics expression can be made up of only one element, for example, a number, as in: 3 ( 3 can be considered to be an expression) Usually, though, expressions are made up of numbers,characters and operators. Let's consider this one: The above expression evaluates to five.( means the result is 5) The above expression has three elements in it:

19 The number 3 The addition operator '+' The number 2 Well, we have already dealt with the idea that 2 and 3 are numbers representing values in an expression. Here, let's talk about the '+'.< Officially, the '+' in the above expression is called an operator. It is the addition operator. Operators do not exist alone in expressions. That is, for example, the addition operator needs some values to add. It needs some values to operate upon. In this expression: The addition operator works with, or operates upon, the values represented by the numbers 3 and 2. The numbers 3 and 2 are said to be the operands for the '+', that is, the 3 and the 2 are operands for the addition operator. Operators in Java 1)Simple Assignment Operator Assignment operator is the most common operator almost used with all programming languages. It is represented by "=" symbol in Java which is used to assign a value to a variable lying to the left side of the assignment operator. But, If the value already exists in that variable then it will be overwritten by the assignment operator (=). This operator can also be used to assign the references to the objects. Syntax of using the assignment operator is: <variable> = <expression>; For example:

20 int counter = 1; String name = "Nisha" In all cases a value of right side is being assigned to its type of variable lying to the left side. You can also assign a value to the more than one variable simultaneously. For example, see these expressions shown as: x = y = z = 2; x =(y + z); Where the assignment operator is evaluated from right to left. In the first expression, value 2 is assigned to the variables "z", then "z" to "y", then "y" to "x" together. While in second expression, the evaluated value of the addition operation is assigned to the variable "x" initially then the value of variable "x" is returned. Apart from "=" operator, different kind of assignment operators available in Java that are know as compound assignment operators and can be used with all arithmetic operators. Syntax of using the compound assignment operator is: operand operation= operand In this type of expression, firstly an arithmetic operation is performed then the evaluated value is assigned to a left most variable. For example an expression as x += y; is equivalent to the expression as x = x + y; which adds the value of operands "x" and "y" then stores back to the variable "x". In this case, both variables must be of the same type. The table shows all compound assignment operators which you can use to make your code more readable and efficient. Operator Example Equivalent Expression += x += y; x = (x + y); -= x -= y; x = (x - y);

21 *= x *= y; x = (x * y); /= x /= y; x = (x / y); %= x %= y; x = (x % y); class CompAssignDemo { public static void main(string[] args) { int x=5; int y=10; x += y; System.out.println("The addition is:"+ x); x -= y; System.out.println("The subtraction is:"+ x); x *= y; System.out.println("The multiplication is:"+ x); x /= y; System.out.println("The division is"+ x); x %= y; System.out.println("The remainder is:"+x); Output of the Program: C:\nisha>javac CompAssignDemo.java C:\nisha>java CompAssignDemo The addition is: 15 The subtraction is: 5 The multiplication is: 50

22 The division is 5 The remainder is: 5 2)Arithmetic Operators Arithmetic Operators are used to perform some mathematical operations like addition, subtraction, multiplication, division, and modulo (or remainder). These are generally performed on an expression or operands. The symbols of arithmetic operators are given in a table: Name of the Symbol Operator Additive + Operator Subtraction - Operator Multiplication * Operator Division / Operator Remainder % Operator Example n = n + 1; n = n - 1; n = n * 1; n = n / 1; n = n % 1; The "+" operator can also be used to concatenate (to join) the two strings together. For example: String str1 = "Concatenation of the first"; String str2 = "and second String"; String result = str1 + str2; The variable "result" now contains a string "Concatenation of the first and second String". Lets have one more example implementing all arithmetic operators: class ArithmeticDemo{ public static void main(string[] args) { int x = 4;

23 int y = 6; int z = 10; int rs = 0; rs = x + y; System.out.println("The addition of (x+y):"+ rs); rs = y - x; System.out.println("The subtraction of (y-x):"+ rs); rs = x * y; System.out.println("The multiplication of (x*y):"+ rs); rs = y / x; System.out.println("The division of (y/x):"+ rs); rs = z % y; System.out.println("The remainder of (z%x):"+ rs); rs = x + (y * (z/x)); System.out.println("The result is now :"+ rs); Output of the Program: C:\nisha>javac ArithmeticDemo.java C:\nisha>java ArithmeticDemo The addition of (x + y): 10 The subtraction of (y - x): 2 The multiplication of (x * y): 24 The division of (y / x): 1 The remainder of (z % x): 4 The result is now : 16 3)The Unary Operators

24 The unary operators require only one operand(variable); they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean. + Unary plus operator; indicates positive value (numbers are positive without this, however) - Unary minus operator; negates an expression ++ Increment operator; increments a value by 1 -- Decrement operator; decrements a value by 1! Logical complement operator; inverts the value of a boolean The following program, UnaryDemo, tests the unary operators: class UnaryDemo { public static void main(string[] args){ int result = +1; // result is now 1 System.out.println(result); result--; // result is now 0 System.out.println(result); result++; // result is now 1 System.out.println(result); result = -result; // result is now -1 System.out.println(result); boolean success = false; System.out.println(success); // false System.out.println(!success); // true 4)Increment and Decrement Operators ++ and -- are Java's increment and decrement operators. The increment operator, ++, increases its operand by one. The decrement operator, --, decreases its operand by one. For example, this statement: x = x + 1; can be rewritten like this by use of the increment operator:

25 x++; This statement: x = x - 1; is equivalent to x--; The increment and decrement operators are unique in that they can appear both Initial Value of x Expression Final Value of Final Value of x y 5 y = x y = ++x y = x y = --x 4 4 in postfix form and prefix form. In the postfix form they follow the operand, for example, i++. In the prefix form, they precede the operand, for example, --i. The difference between these two forms appears when the increment and/or decrement operators are part of a larger expression. In the prefix form, the operand is incremented or decremented before the value is used in the expression. In postfix form, the value is used in the expression, and then the operand is modified. Examples of Pre-and Post- Increment and Decrement Operations For example: x = 42; y = ++x; y is set to 43, because the increment occurs before x is assigned to y. Thus, the line

26 y = ++x; is the equivalent of these two statements: x = x + 1; y = x; However, when written like this, x = 42; y = x++; the value of x is obtained before the increment operator is executed, so the value of y is 42. In both cases x is set to 43. The line is the equivalent of these two statements: y = x; x = x + 1; The following program demonstrates the increment operator. public class Main { public static void main(string args[]) { int a = 1; int b = 2; int c = ++b; int d = a++; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); The output of this program follows: a = 2 b = 3

27 c = 3 d = 1 5)Equality and Relational Operators Whenever we need to compare the results of two expressions or operands in a program then the equality and relational operators are used to know whether an operand is equal, not equal, greater than, less than to another operand. There are different types of equality and relational operators mentioned in a table given below: Name of the Symbol Operator Example Operation = = Equal to a = = b a is equal to b!= Not equal to a! = b a is not equal to b > Greater than a > b a is greater than b < Less than a < b a is less than b >= <= Greater than or equal to Less than or equal to a > = b a > = b a is greater thanor equal to b a is less than or equal to b The Equality operator "= =" differs from an assignment operator "=" i.e. the equality operator is used to determine whether one operand is equal to another operand or not while the assignment operator is used to assign a value to a variable. All these operators are often used in the control structures such as if, do, while with the conditional operators to make decisional expressions. Lets have an example implementing these operators: class EquityOperator {

28 public static void main(string[] args){ int x = 5; int y = 10; if(x == y) System.out.println("value of x is equal to the value of y" ); if(x!= y) System.out.println("value of x is not equal to the value of y"); if(x > y) System.out.println("value of x is greater then the value of y"); if(x < y) System.out.println("value of x is less then the value of y"); if(x >= y) System.out.println("value of x is greater then or equal to the value of y"); if(x <= y) System.out.println("value of x is less then or equal to the value of y"); Output of the Program: C:\nisha>javac EquityOperator.java C:\nisha>java EquityOperator value of x is not equal to the value of y value of x is less then the value of y value of x is less then or equal to the value of y 6)The Logical Operators: The following table lists the logical operators: Assume boolean variables A holds true and variable B holds false then: Operator Description Example

29 && Called Logical AND operator. If both the operands are non zero then then condition becomes true. (A && B) is false. Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. (A B) is true.!(a && B) is true. The following simple example program demonstrates the logical operators class Test { public static void main(string args[]) { int a = true; int b = false; System.out.println("a && b = " + (a&&b) ); System.out.println("a b = " + (a b) ); System.out.println("!(a && b) = " +!(a && b) ); This would produce following result: a && b = false a b = true!(a && b) = true Truth Table for Operator && p1 p2 p1 && p2 false false false false true false Example (assume age = 24, gender = 'F') (age > 18) && (gender == 'F') is true, because (age > 18) and (gender == 'F') are both true.

30 Truth Table for Operator p1 p2 p1 p2 false false false false true true true false true true true true Truth Table for Operator! p!p Example (assume age = 24, gender = 'F') (age > 34) (gender == 'F') is true, because (gender == 'F') is true. (age > 34) (gender == 'M') is false, because (age > 34) and (gender == 'M') are both false. Example true false false 6)Conditional Operator (? : ): true!(1 > 2) is true, because (1 > 2) is false.!(1 > 0) is false, because (1 > 0) is true. Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as : variable x = (expression)? value if true : value if false Following is the example: public class Test { public static void main(string args[]){ int a, b;

31 a = 10; b = (a == 1)? 20: 30; System.out.println( "Value of b is : " + b ); b = (a == 10)? 20: 30; System.out.println( "Value of b is : " + b ); This would produce following result: Value of b is : 30 Value of b is : 20 Precedence of Java Operators: Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator: For example x = * 2; Here x is assigned 13, not 20 because operator * has higher precedenace than + so it first get multiplied with 3*2 and then adds into 7. Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedenace operators will be evaluated first. Postfix Category () []. (dot operator) Operator Unary ! ~ Multiplicative * / % Additive + - Shift >> >>> << Relational > >= < <=

32 Equality ==!= Bitwise AND Bitwise XOR & ^ Bitwise OR Logical AND && Logical OR Conditional?: Assignment = += -= *= /= %= >>= <<= &= ^= = Comma, Precedence Rules Evaluate all sub expressions in parentheses Evaluate nested parentheses from the inside out In the absence of parentheses or within parentheses Evaluate *, /, or % before + or Evaluate sequences of *, /, and % operators from left to right Evaluate sequences of + and operators from left to right Precedence Examples Example % 8 / 5 is the same as 6 + ((37 % 8) / 5) = 6 + ( 5 / 5) = 7 Example % (8 / 5) = % 1 = = 6 Glance at java operators Arithmetic operators: Operator Operator + addition - subtraction

33 * multiplication / division % modulus(remainder after division) Equality operators o Used to determine if values of two expressions are equal or not equal o Result is true or false == Type is Binary, meaning is equal to!= Type is Binary, meaning is not equal to o Example (age == 39) means is age equal to 39, returns true or false (age!= 39) means is age not equal to 39, returns true or false o Only use equality on primitive types, and not objects, o results may be different Don t confuse (equality operator) == with (assignment operator) =, they are different Relational Operators o o o o < binary is less than > binary is greater than <= binary is less than or equal to >= binary is greater than or equal to Logical Operators o! unary NOT o && Binary AND o Binary OR Separator: Separator is one of the category of token (also known as a punctuator). A symbol that is used to separate one group of code from another is called a Seperator.There are exactly nine, single character separators in Java, shown in the following simple EBNF rule. separator <= ;,. ( ) { [ ] Following are the some characters which are generally used as the separators in Java.

34 Separator Name Use. Period It is used to separate the package name from sub-package name & class name. It is also used to separate variable or method from its object or instance., Comma It is also used to separate the consecutive variables of same type while declaration. ; Semicolon It is used to terminate the statement in Java. () Parenthesis This holds the list of parameters in method definition. Also used in control statements & type casting. { Braces This is used to define the block/scope of code, class, methods. [] Brackets It is used in array declaration. Separators in Java Whitspaces: A space tab,or newline is called a Whitespace in java. CONTROL STRUCTURES IN JAVA: Control structures are used to control the flow of program.they define what mechanism the program is using to solve a given problem. Control structure can be categorized into two types: 1)looping control structure/iteration control structure (eg: for,while,do while) 2) conditional or branching control structure. (eg: if,if else, if else ladder and switch) In a looping control structure, series of statements are repeated. In a conditional or branching control structure, a portion of the program is executed once depending on what conditions occur in the code.(either true or false)

35 1)CONDITIONAL STATEMENTS: if statement: The if statement is the simple form of control flow statement. It directs the program to execute a certain section of code if and only if the test evaluates to true. That is the if statement in Java is a test of any boolean expression. Syntax: if (Expression) { statement (s) else { statement (s) Example: public class MainClass { public static void main(string[] args) { int a = 3; if (a > 3) a++; else a = 3; Example: class IfElseexamp { public static void main(string[] args) {

36 int testscore = 66; char grade; if (testscore >= 90) { grade = 'A'; else if (testscore >= 80) { grade = 'B'; else if (testscore >= 70) { grade = 'C'; else if (testscore >= 60) { grade = 'D'; else { grade = 'F'; System.out.println("Grade = " + grade); The output will be D

37 The Switch Statement: The Switch Statement is an alternative to a series of else if is the switch statement. Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types. The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. The switch statement evaluates its expression and executes the appropriate case. Switch Statement Syntax: switch (expression) { case value_1 : statement (s); break; case value_2 : statement (s); break;... case value_n : statement (s); break; default: statement (s); Example: class Switchexamp {

38 public static void main(string[] args) { int month = 5; switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September");

39 break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Wrong Input"); break; The output will be : May 2)Iteration Statements While Statement The while statement is a looping construct control statement that executes a block of code while a condition is true. You can either have a single statement or a block of code within the while loop. The loop will never be executed if the testing expression evaluates to false. The loop condition must be a boolean expression. The syntax of the while loop is

40 while (<loop condition>) <statements> Below is an example that demonstrates the looping construct namely while loop used to print numbers from 1 to 10. public class WhileLoopDemo { public static void main(string[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); while (count <= 10) { System.out.println(count++); Output Printing Numbers from 1 to Do-while Loop Statement The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead of at the beginning. This ensures that the loop will be executed at least once. A do-while loop begins with the keyword do, followed by the statements that make up the body of the loop. Finally, the keyword while and the test expression completes the do-while loop. When the loop condition becomes false, the loop is terminated andexecution continues with the statement immediately following the loop. You can either have a single statement or a block of code within the do-while loop.

41 The syntax of the do-while loop is do <loop body> while (<loop condition>); Below is an example that demonstrates the looping construct namely do-while loop used to print numbers from 1 to 10. public class DoWhileLoopDemo { public static void main(string[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); do { System.out.println(count++); while (count <= 10); Output Printing Numbers from 1 to Example: public class Test { public static void main(string args[]){ int x= 10; do{ System.out.print("value of x : " + x ); x++; System.out.print("\n");

42 while( x < 20 ); This would produce following result: value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 Program: FIBONACCI SERIES Below is an example that creates A Fibonacci sequence controlled by a do-while loop public class Fibonacci { public static void main(string args[]) { System.out.println("Printing Limited set of Fibonacci Sequence"); double fib1 = 0; double fib2 = 1; double temp = 0; System.out.println(fib1); System.out.println(fib2); do { temp = fib1 + fib2; System.out.println(temp); fib1 = fib2; //Replace 2nd with first number fib2 = temp; //Replace temp number with 2nd number while (fib2 < 5000); Output

43 Printing Limited set of Fibonacci Sequence For Loops The for loop is a looping construct which can execute a set of instructions a specified number of times. It s a counter controlled loop. The syntax of the loop is as follows: for (<initialization>; <loop condition>; <increment expression>) <loop body> The first part of a for statement is a starting initialization, which executes once before the loop begins. The <initialization> section can also be a comma-separated list of expression statements. The second part of a for statement is a test expression. As long as the expression is true, the loop will continue. If this expression is evaluated as false the first time, the loop will never be executed.

44 The third part of the for statement is the body of the loop. These are the instructions that are repeated each time the program executes the loop. The final part of the for statement is an increment expression that automatically executes after each repetition of the loop body. Typically, this statement changes the value of the counter, which is then tested to see if the loop should continue. Below is an example that demonstrates the for loop used to print numbers from 1 to 10. public class ForLoopDemo { public static void main(string[] args) { System.out.println("Printing Numbers from 1 to 10"); for (int count = 1; count <= 10; count++) { System.out.println(count); Output Printing Numbers from 1 to Simple For loop Example 1. /* 2. Simple For loop Example 3. This Java Example shows how to use for loop to iterate in Java program. 4. */ public class SimpleForLoopExample {

45 7. 8. public static void main(string[] args) { /* Syntax of for loop is 11. * 12. * for(<initialization> ; <condition> ; <expression> ) 13. * <loop body> 14. * 15. * where initialization usually declares a loop variable, condition is a 16. * boolean expression such that if the condition is true, loop body will be 17. * executed and after each iteration of loop body, expression is executed which 18. * usually increase or decrease loop variable. 19. * 20. * Initialization is executed only once. 21. */ for(int index = 0; index < 5 ; index++) 24. System.out.println("Index is : " + index); /* 27. * Loop body may contains more than one statement. In that case they should 28. * be in the block. 29. */ for(int index=0; index < 5 ; index++) 32. { 33. System.out.println("Index is : " + index); 34. index++; /* 38. * Please note that in above loop, index is a local variable whose scope 39. * is limited to the loop. It can not be referenced from outside the loop. 40. */ /* 45. Output would be 46. Index is : 0

46 47. Index is : Index is : Index is : Index is : Index is : Index is : Index is : */ Java Pyramid EXAMPLE USING for loop 1. /* 2. Java Pyramid 1 Example 3. This Java Pyramid example shows how to generate pyramid or triangle like 4. given below using for loop * 7. ** 8. *** 9. **** 10. ***** 11. */ public class JavaPyramid1 { public static void main(string[] args) { for(int i=1; i<= 5 ;i++){ for(int j=0; j < i; j++){ 20. System.out.print("*"); //generate a new line 24. System.out.println(""); /* 30. Output of the above program would be 31. * 32. ** 33. ***

47 34. **** 35. ***** 36. */ Java Pyramid 2 Example 1. /* 2. Java Pyramid 2 Example 3. This Java Pyramid example shows how to generate pyramid or triangle like 4. given below using for loop ***** 7. **** 8. *** 9. ** 10. * 11. */ public class JavaPyramid2 { public static void main(string[] args) { for(int i=5; i>0 ;i--){ for(int j=0; j < i; j++){ 20. System.out.print("*"); //generate a new line 24. System.out.println(""); /* Output of the example would be 32. ***** 33. **** 34. *** 35. ** 36. * */

48 Java Pyramid 3 Example 1. /* 2. Java Pyramid 3 Example 3. This Java Pyramid example shows how to generate pyramid or triangle like 4. given below using for loop * 7. ** 8. *** 9. **** 10. ***** 11. ***** 12. **** 13. *** 14. ** 15. * 16. */ 17. public class JavaPyramid3 { public static void main(string[] args) { for(int i=1; i<= 5 ;i++){ for(int j=0; j < i; j++){ 24. System.out.print("*"); //generate a new line 28. System.out.println(""); //create second half of pyramid 32. for(int i=5; i>0 ;i--){ for(int j=0; j < i; j++){ 35. System.out.print("*"); //generate a new line 39. System.out.println("");

49 45. /* Output of the example would be 48. * 49. ** 50. *** 51. **** 52. ***** 53. ***** 54. **** 55. *** 56. ** 57. * */ Java Pyramid 4 Example 1. /* 2. Java Pyramid 4 Example 3. This Java Pyramid example shows how to generate pyramid or triangle like 4. given below using for loop */ 13. public class JavaPyramid4 { public static void main(string[] args) { for(int i=1; i<= 5 ;i++){ for(int j=0; j < i; j++){ 20. System.out.print(j+1); System.out.println("");

50 29. /* Output of the example would be */ List Even Numbers Java Example 1. /* 2. List Even Numbers Java Example 3. This List Even Numbers Java Example shows how to find and list even 4. numbers between 1 and any given number. 5. */ public class ListEvenNumbers { public static void main(string[] args) { //define limit 12. int limit = 50; System.out.println("Printing Even numbers between 1 and " + limit); for(int i=1; i <= limit; i++){ // if the number is divisible by 2 then it is even 19. if( i % 2 == 0){ 20. System.out.print(i + " "); /* 27. Output of List Even Numbers Java Example would be 28. Printing Even numbers between 1 and */

51

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

Java Basic Datatypees

Java Basic Datatypees Basic Datatypees Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory. Based on the data type of a variable,

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

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

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

JAVA OPERATORS GENERAL

JAVA OPERATORS GENERAL JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

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

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

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

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Basic Operators Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

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

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

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

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 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

A variable is a name that represents a value. For

A variable is a name that represents a value. For DECLARE A VARIABLE A variable is a name that represents a value. For example, you could have the variable myage represent the value 29. Variables can be used to perform many types of calculations. Before

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

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

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

1. Introduction to Java for JAS

1. Introduction to Java for JAS Introduction to Java and Agent-Based Economic Platforms (CF-904) 1. Introduction to Java for JAS Mr. Simone Giansante Email: sgians@essex.ac.uk Web: http://privatewww.essex.ac.uk/~sgians/ Office: 3A.531

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

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

Language Fundamentals Summary

Language Fundamentals Summary Language Fundamentals Summary Claudia Niederée, Joachim W. Schmidt, Michael Skusa Software Systems Institute Object-oriented Analysis and Design 1999/2000 c.niederee@tu-harburg.de http://www.sts.tu-harburg.de

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

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

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

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

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

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

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

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

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

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

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9 Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits

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

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

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

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

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

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

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

Learning the Java Language. 2.1 Object-Oriented Programming

Learning the Java Language. 2.1 Object-Oriented Programming Learning the Java Language 2.1 Object-Oriented Programming What is an Object? Real world is composed by different kind of objects: buildings, men, women, dogs, cars, etc. Each object has its own states

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 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

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

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

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

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

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

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Op. Use Description + x + y adds x and y x y

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

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

The Arithmetic Operators

The Arithmetic Operators The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Examples: Op. Use Description + x + y adds x

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that

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

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

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

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

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

Tony Valderrama, SIPB IAP 2009

Tony Valderrama, SIPB IAP 2009 Wake up and smell the coffee! Software Java Development Kit (JDK) - http://java.sun.com/javase/downloads/index.jsp Eclipse Platform - http://www.eclipse.org/ Reference The Java Tutorial - http://java.sun.com/docs/books/tutorial/index.html

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

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

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

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

Preview from Notesale.co.uk Page 9 of 108

Preview from Notesale.co.uk Page 9 of 108 The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names. abstract assert boolean break byte case catch char class

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

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

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

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Java Syntax Program Structure Variables and basic data types. Industry standard naming conventions. Java syntax and coding conventions If Then Else Case statements Looping (for,

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

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

CHAPTER 2 Java Fundamentals

CHAPTER 2 Java Fundamentals CHAPTER 2 Java Fundamentals Copyright 2016 Pearson Education, Inc., Hoboken NJ Chapter Topics Chapter 2 discusses the following main topics: The Parts of a Java Program The print and println Methods, and

More information

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Tools : The Java Compiler. The Java Interpreter. The Java Debugger Tools : The Java Compiler javac [ options ] filename.java... -depend: Causes recompilation of class files on which the source files given as command line arguments recursively depend. -O: Optimizes code,

More information

Chapter 2 Primitive Data Types and Operations

Chapter 2 Primitive Data Types and Operations Chapter 2 Primitive Data Types and Operations 2.1 Introduction You will be introduced to Java primitive data types and related subjects, such as variables constants, data types, operators, and expressions.

More information

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>= Operators in java Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc. There are many types of operators in java which are given below: Unary Operator, Arithmetic

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

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

Java Programming. Atul Prakash

Java Programming. Atul Prakash Java Programming Atul Prakash Java Language Fundamentals The language syntax is similar to C/ C++ If you know C/C++, you will have no trouble understanding Java s syntax If you don't, it will be easier

More information

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA. DECLARATIONS Character Set, Keywords, Identifiers, Constants, Variables Character Set C uses the uppercase letters A to Z. C uses the lowercase letters a to z. C uses digits 0 to 9. C uses certain Special

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

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1 topics: introduction to java, part 1 cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 cis20.1-fall2007-sklar-leci.2 1 Java. Java is an object-oriented language: it is

More information

The MaSH Programming Language At the Statements Level

The MaSH Programming Language At the Statements Level The MaSH Programming Language At the Statements Level Andrew Rock School of Information and Communication Technology Griffith University Nathan, Queensland, 4111, Australia a.rock@griffith.edu.au June

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

COMP Primitive and Class Types. Yi Hong May 14, 2015

COMP Primitive and Class Types. Yi Hong May 14, 2015 COMP 110-001 Primitive and Class Types Yi Hong May 14, 2015 Review What are the two major parts of an object? What is the relationship between class and object? Design a simple class for Student How to

More information

Control Flow Statements

Control Flow Statements Control Flow Statements The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution

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

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

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

AP Computer Science A

AP Computer Science A AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive

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

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language Chapter 1 Getting Started Introduction To Java Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language The syntax of expressions

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Chapter 2 Working with Data Types and Operators

Chapter 2 Working with Data Types and Operators JavaScript, Fourth Edition 2-1 Chapter 2 Working with Data Types and Operators At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics

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

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( ) Sir Muhammad Naveed Arslan Ahmed Shaad (1163135 ) Muhammad Bilal ( 1163122 ) www.techo786.wordpress.com CHAPTER: 2 NOTES:- VARIABLES AND OPERATORS The given Questions can also be attempted as Long Questions.

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

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