Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a...

63
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

Transcript of Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a...

Page 1: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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.

Page 2: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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:

Page 3: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

/* 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 methodsIf you're declaring a class or a method, you have to tell Java the name that you wantto associate with the class or method, and how accessible it is to be from elsewhere inyour application.Our class is declared in this example aspublic class Hellowhich 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 aspublic 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();

Page 4: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

//This program prints Welcome to Java! 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.

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

Page 5: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

The Java Character Set

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|zupper-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|Zalphabetic <= lower-case | upper-casenumeric     <= 0|1|2|3|4|5|6|7|8|9alphanumeric <= alphabetic | numericspecial       <= !|%|^|&|*|(|)|-|+|=|{|}|||~|[|]|\|;|'|:|"|<|>|?|,|.|/|#|@|`|_graphic     <= alphanumeric | special

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

Page 6: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

break double import public throws

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 understoodby the Java Virtual Machine. Words like "main" and "println" are not understood bythe JVM, but are nevertheless unchangeable as they are part of the standard classesand methods provided.On the other hand, the words "Hello" and "args" are our choice, and we can changethem 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 wordsthat relate to standard classes and methods for things you name.

Page 7: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

2)Java Identifiers - symbolic names:Identifiers are used to name classes, variables, and methods.  Identifier Rules:

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, ornull.

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_variable_name_is_so_ridiculously_long_that_it_won't_fit_on_the_page_I_cant_imagine_why_you_would_need_such_a_long_variable_name_but_if_you_do_you_can_have_it

The following are not legal variable names:

Page 8: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

My Variable // Contains a space 9pins // Begins with a digit 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 TypesFor 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 Valuebyte             1                                       -128                                                    127short            2                                    -32,768                                              32,767int                4                      -2, 147, 483, 648                                 2, 147, 483, 647long              8      -9,223,372,036,854,775,808                9,223,372,036,854,775,807float              4                                   1.4E-45                                   3.4028235E38double          8                                 4.9E-324                  1.7976931348623157E308char             2              character  encoded as 0              character encoded as FFFF boolean     2 values true and false

Java Data Types

Page 9: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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

Page 10: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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

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

3)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 = 100000, int b = -200000

4)long:

Long data type is a 64-bit signed two's complement integer.

Page 11: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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 = 100000L, int b = -200000L

5)float:

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

7)boolean:

Page 12: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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'

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)

Page 13: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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

Naming variablesRules 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 as !@#

%^&* 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)

Page 14: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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.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);

Page 15: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

System.out.println("Is the isBoolean variable a boolean variable? " + isBoolean); } }Output:-10 10 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 10numPlayers = 8; // numPlayers now holds 8

int legalAge = 18;int voterAge = legalAge;

The next statement is illegalint height = weight * 2; // weight is not definedint 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.

Page 16: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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:

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

Page 17: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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)

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.

Page 18: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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 LiteralsThe string of characters is represented as String literals in Java. We represent string literals asString 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");

Boolean LiteralsThe 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:

Page 19: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

'(' ,'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:

3 + 2

The above expression evaluates to five.( means the result is 5)

The above expression has three elements in it:

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:

3 + 2

Page 20: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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:

 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.

Page 21: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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); *=  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);

Page 22: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

    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 CompAssignDemoThe addition is: 15The subtraction is: 5The multiplication is: 50The division is 5The 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:

SymbolName of the Operator Example

 + Additive Operator   n =  n + 1;

 - Subtraction Operator  n =  n - 1;

 * Multiplication  n =  n * 1;

Page 23: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

Operator 

 / Division Operator  n = n / 1;

 % Remainder Operator  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;  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);

Page 24: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

  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 ArithmeticDemoThe addition of (x + y): 10The subtraction of (y - x): 2The multiplication of (x * y): 24The division of (y / x): 1The remainder of (z % x): 4The result is now : 16

3)The Unary Operators

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 {

Page 25: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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:

x++;

This statement:

x = x - 1;

is equivalent to

x--;

The increment and decrement operators are unique in that they can appear both 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.

Page 26: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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

Initial Value of x Expression Final Value of y

Final Value of x

5 y = x++ 5 65 y = ++x 6 65 y = x-- 5 45 y = --x 4 4

For example:

x = 42; y = ++x;

y is set to 43, because the increment occurs before x is assigned to y. Thus, the line

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:

Page 27: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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 = 2b = 3c = 3d = 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:

SymbolName of the Operator ExampleOperation

Page 28: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

 = = 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  a > = b

 a is greater thanor equal to b

 <=   Less than or equal to a > = 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 {

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");

Page 29: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

 }}

 

Output of the Program: 

C:\nisha>javac EquityOperator.java C:\nisha>java EquityOperatorvalue of x is not equal to the value of yvalue of x is less then the value of yvalue 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

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

(A || B) is 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.

Page 30: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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 = falsea || b = true!(a && b) = true

Truth Table for Operator &&

Truth Table for Operator ||

Page 31: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

Truth Table for Operator !

6)Conditional Operator ( ? : ):

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; 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 : 30Value 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

Page 32: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

multiplication operator has higher precedence than the addition operator:

For example x = 7 + 3 * 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.

Category  Operator Postfix  () [] . (dot operator)Unary  ++ - - ! ~Multiplicative   * / % Additive   + - Shift   >> >>> <<  Relational   > >= < <=  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

Page 33: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

• Evaluate sequences of + and – operators from left to rightPrecedence Examples

• Example 16 + 37 % 8 / 5 is the same as6 + ((37 % 8) / 5) = 6 + ( 5 / 5) = 7 • Example 26 + 37 % (8 / 5) =6 + 37 % 1 =6 + 0 = 6

Glance at java operators

Arithmetic operators:

Operator Operator+ addition- subtraction* multiplication/ division

% modulus(remainder after division)

 Equality operatorso  Used to determine if values of two expressions are equal

or not equalo 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 falseo Only use equality on primitive types, and not objects,

results may be differento  Don’t confuse (equality operator) == with (assignment

operator) =, they are different Relational Operators

Page 34: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

o  < binary “is less than”o  > binary “is greater than”o <= binary “is less than or equal to”o  >= binary “is greater than or equal to” 

  Logical Operators

o  ! unary NOTo  && Binary ANDo || 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.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.

Page 35: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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)

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 {

Page 36: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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

 

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

Page 37: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

        } else {

            grade = 'F';

        }

        System.out.println("Grade = " + grade);

    }

}

 

 

The output will be

D

 

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

Page 38: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

     break;  .  .  .case value_n :     statement (s);     break;default:     statement (s);}

 

Example:

class Switchexamp {

    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;

Page 39: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

            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");

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;

        }

    }

}

Page 40: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

 

The output will be     :

May

2)Iteration StatementsWhile 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

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 10123456

Page 41: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

78910

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.

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 1012

Page 42: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

345678910

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"); }while( x < 20 ); }}

This would produce following result:

value of x : 10value of x : 11value of x : 12value of x : 13value of x : 14value of x : 15value of x : 16value of x : 17value of x : 18value of x : 19

Program: FIBONACCI SERIES

Below is an example that creates A Fibonacci sequence controlled by a do-while loop

public class Fibonacci {

Page 43: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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 numberfib2 = temp; //Replace temp number with 2nd number

} while (fib2 < 5000);}

}

Output

Printing Limited set of Fibonacci Sequence

0.01.01.02.03.05.08.013.021.034.055.089.0144.0233.0377.0610.0987.01597.02584.04181.06765.0

For Loops

Page 44: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

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.

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 101234

Page 45: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

5678910

Simple For loop Example

1. /*2.   Simple For loop Example3.   This Java Example shows how to use for loop to

iterate in Java program.4. */5.  6. public class SimpleForLoopExample {7.  8. public static void main(String[] args) {9.  10. /* Syntax of for loop is11.   * 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 be17.   * executed and after each iteration of loop

body, expression is executed which18.   * usually increase or decrease loop variable.19.   * 20.   * Initialization is executed only once.21.   */22.  23. for(int index = 0; index < 5 ; index++)24. System.out.println("Index is : " + index);25.  26. /*27.   * Loop body may contains more than one

statement. In that case they should 28.   * be in the block.29.   */30.  31. for(int index=0; index < 5 ; index++)32. {

Page 46: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

33. System.out.println("Index is : " + index);34. index++;35. }36.  37. /*38.   * Please note that in above loop, index is a

local variable whose scope39.   * is limited to the loop. It can not be

referenced from outside the loop.40.   */41. }42. }43.  44. /*45. Output would be46. Index is : 047. Index is : 148. Index is : 249. Index is : 350. Index is : 451. Index is : 052. Index is : 253. Index is : 454. */

Java Pyramid EXAMPLE USING for loop

1. /*2. Java Pyramid 1 Example3. This Java Pyramid example shows how to generate

pyramid or triangle like4. given below using for loop.5.  6. *7. **8. ***9. ****10. *****11. */12.  13. public class JavaPyramid1 {14.  15. public static void main(String[] args) {16.  17. for(int i=1; i<= 5 ;i++){

Page 47: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

18.  19. for(int j=0; j < i; j++){20. System.out.print("*");21. }22.  23. //generate a new line24. System.out.println("");25. }26. }27. }28.  29. /*30. Output of the above program would be31. *32. **33. ***34. ****35. *****36. */

Java Pyramid 2 Example

1. /*2. Java Pyramid 2 Example3. This Java Pyramid example shows how to generate

pyramid or triangle like4. given below using for loop.5.  6. *****7. ****8. ***9. **10. *11. */12.  13. public class JavaPyramid2 {14.  15. public static void main(String[] args) {16.  17. for(int i=5; i>0 ;i--){18.  19. for(int j=0; j < i; j++){20. System.out.print("*");21. }22.  23. //generate a new line24. System.out.println("");

Page 48: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

25. }26. }27. }28.  29. /*30.  31. Output of the example would be32. *****33. ****34. ***35. **36. *37.  38. */

Java Pyramid 3 Example

1. /*2. Java Pyramid 3 Example3. This Java Pyramid example shows how to generate

pyramid or triangle like4. given below using for loop.5.  6. *7. **8. ***9. ****10. *****11. *****12. ****13. ***14. **15. *16. */17. public class JavaPyramid3 {18.  19. public static void main(String[] args) {20.  21. for(int i=1; i<= 5 ;i++){22.  23. for(int j=0; j < i; j++){24. System.out.print("*");25. }26.  27. //generate a new line

Page 49: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

28. System.out.println("");29. }30.  31. //create second half of pyramid32. for(int i=5; i>0 ;i--){33.  34. for(int j=0; j < i; j++){35. System.out.print("*");36. }37.  38. //generate a new line39. System.out.println("");40. }41.  42. }43. }44.  45. /*46.  47. Output of the example would be48. *49. **50. ***51. ****52. *****53. *****54. ****55. ***56. **57. *58.  59. */

Java Pyramid 4 Example

1. /*2. Java Pyramid 4 Example3. This Java Pyramid example shows how to generate

pyramid or triangle like4. given below using for loop.5.  6. 17. 128. 1239. 123410. 1234511.  

Page 50: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

12. */13. public class JavaPyramid4 {14.  15. public static void main(String[] args) {16.  17. for(int i=1; i<= 5 ;i++){18.  19. for(int j=0; j < i; j++){20. System.out.print(j+1);21. }22.  23. System.out.println("");24. }25.  26. }27. }28.  29. /*30.  31. Output of the example would be32. 133. 1234. 12335. 123436. 1234537.  38. */

List Even Numbers Java Example

1. /*2. List Even Numbers Java Example3. This List Even Numbers Java Example shows how to find

and list even4. numbers between 1 and any given number.5. */6.  7. public class ListEvenNumbers {8.  9. public static void main(String[] args) {10.  11. //define limit12. int limit = 50;13.  14. System.out.println("Printing Even

numbers between 1 and " + limit);15.  

Page 51: Declaring classes and methods - جامعة نزوى€¦  · Web viewContents: *Understanding a Simple java program *Basic Program elements ( Character set, comments, java tokens,

16. for(int i=1; i <= limit; i++){17.  18. // if the number is divisible by 2

then it is even19. if( i % 2 == 0){20. System.out.print(i + " ");21. }22. }23. }24. }25.  26. /*27. Output of List Even Numbers Java Example would be28. Printing Even numbers between 1 and 5029. 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38

40 42 44 46 48 50 30. */