CHAPTER 3,4 & 5. Contents:

Similar documents
Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Java Basic Datatypees

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

JAVA OPERATORS GENERAL

Full file at

Chapter 3: Operators, Expressions and Type Conversion

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

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

3. Java - Language Constructs I

Program Fundamentals

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

Chapter 2 Elementary Programming

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

A variable is a name that represents a value. For

4 Programming Fundamentals. Introduction to Programming 1 1

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

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

1. Introduction to Java for JAS

Operators. Java operators are classified into three categories:

Basics of Java Programming

Language Fundamentals Summary

CSC 1214: Object-Oriented Programming

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

Chapter 2. Elementary Programming

CMPT 125: Lecture 3 Data and Expressions

Programming with Java

Lecture Set 2: Starting Java

The C++ Language. Arizona State University 1

Lecture Set 2: Starting Java

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

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

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

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

Introduction to Java & Fundamental Data Types

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

JAVA Programming Fundamentals

Important Java terminology

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

Programming Lecture 3

Learning the Java Language. 2.1 Object-Oriented Programming

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

Chapter 2 ELEMENTARY PROGRAMMING

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

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

UNIT- 3 Introduction to C++

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

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

Chapter 2: Basic Elements of C++

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

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

Visual C# Instructor s Manual Table of Contents

The Arithmetic Operators

Chapter 2: Using Data

Accelerating Information Technology Innovation

BASIC ELEMENTS OF A COMPUTER PROGRAM

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

Operators and Expressions

Chapter 2 Primitive Data Types and Operations. Objectives

Tony Valderrama, SIPB IAP 2009

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

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

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

A Java program contains at least one class definition.

Elementary Programming

Preview from Notesale.co.uk Page 9 of 108

Java Notes. 10th ICSE. Saravanan Ganesh

DEPARTMENT OF MATHS, MJ COLLEGE

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

Object-Oriented Programming

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

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

CHAPTER 2 Java Fundamentals

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

Chapter 2 Primitive Data Types and Operations

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

Fundamental of Programming (C)

Chapter 2: Data and Expressions

Java Programming. Atul Prakash

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

Getting started with Java

1 Lexical Considerations

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

The MaSH Programming Language At the Statements Level

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

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

Control Flow Statements

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

2 rd class Department of Programming. OOP with Java Programming

Chapter 2: Data and Expressions

AP Computer Science A

COMP 202 Java in one week

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

Lexical Considerations

Chapter 2 Working with Data Types and Operators

Objectives. In this chapter, you will:

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

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

Chapter. Let's explore some other fundamental programming concepts

Transcription:

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.

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:

/* 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!

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

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 <= 0 1 2 3 4 5 6 7 8 9 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

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:

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

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 1-128 127 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-45 3.4028235E38 double 8 4.9E-324 1.7976931348623157E308 char 2 character encoded as 0 character encoded as FFFF boolean 2 values true and false 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? 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

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. 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: 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) \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 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 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) 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); 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 10 numplayers = 8; // numplayers now holds 8

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:

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

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

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

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;

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

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:

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++ 5 6 5 y = ++x 6 6 5 y = x-- 5 4 5 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

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

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 {

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

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

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;

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 = 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. Postfix Category () []. (dot operator) 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 Evaluate sequences of + and operators from left to right Precedence Examples Example 1 6 + 37 % 8 / 5 is the same as 6 + ((37 % 8) / 5) = 6 + ( 5 / 5) = 7 Example 2 6 + 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 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.

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)

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

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

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 {

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

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

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 10 1 2 3 4 5 6 7 8 9 10 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 10 1 2 3 4 5 6 7 8 9 10 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 : 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

Printing Limited set of Fibonacci Sequence 0.0 1.0 1.0 2.0 3.0 5.0 8.0 13.0 21.0 34.0 55.0 89.0 144.0 233.0 377.0 610.0 987.0 1597.0 2584.0 4181.0 6765.0 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.

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 10 1 2 3 4 5 6 7 8 9 10 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. */ 5. 6. public class SimpleForLoopExample {

7. 8. public static void main(string[] args) { 9. 10. /* 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. */ 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. { 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 scope 39. * is limited to the loop. It can not be referenced from outside the loop. 40. */ 41. 42. 43. 44. /* 45. Output would be 46. Index is : 0

47. Index is : 1 48. Index is : 2 49. Index is : 3 50. Index is : 4 51. Index is : 0 52. Index is : 2 53. Index is : 4 54. */ 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. 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++){ 18. 19. for(int j=0; j < i; j++){ 20. System.out.print("*"); 21. 22. 23. //generate a new line 24. System.out.println(""); 25. 26. 27. 28. 29. /* 30. Output of the above program would be 31. * 32. ** 33. ***

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. 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 line 24. System.out.println(""); 25. 26. 27. 28. 29. /* 30. 31. Output of the example would be 32. ***** 33. **** 34. *** 35. ** 36. * 37. 38. */

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. 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 28. System.out.println(""); 29. 30. 31. //create second half of pyramid 32. 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 line 39. System.out.println(""); 40. 41. 42. 43. 44.

45. /* 46. 47. Output of the example would be 48. * 49. ** 50. *** 51. **** 52. ***** 53. ***** 54. **** 55. *** 56. ** 57. * 58. 59. */ 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. 5. 6. 1 7. 12 8. 123 9. 1234 10. 12345 11. 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 be 32. 1 33. 12 34. 123 35. 1234 36. 12345 37. 38. */ 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. */ 6. 7. public class ListEvenNumbers { 8. 9. public static void main(string[] args) { 10. 11. //define limit 12. int limit = 50; 13. 14. System.out.println("Printing Even numbers between 1 and " + limit); 15. 16. for(int i=1; i <= limit; i++){ 17. 18. // if the number is divisible by 2 then it is even 19. if( i % 2 == 0){ 20. System.out.print(i + " "); 21. 22. 23. 24. 25. 26. /* 27. Output of List Even Numbers Java Example would be 28. Printing Even numbers between 1 and 50 29. 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. */