Upload
garapati-avinash
View
44
Download
0
Embed Size (px)
Citation preview
BITS PilaniPilani Campus
Object-Oriented Programming (BITS C342)
Lecture -3 [Variables, Operators, Expressions, Statements and Blocks]
BITS Pilani, Pilani Campus
Today’s Agenda
Language Basics Variables
Primitive Data Types Arrays
Operators Assignment, Arithmetic, and Unary Operators Equality, Relational, and Conditional Operators Bitwise and Bit Shift Operators
Expressions, Statements, and Blocks Control Flow Statements
if – then and if – then – else switch while and do – while for and branching statements
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Variables in Java
• We know that object stores its variables in its fields (statevariables)
• What are the rules and conventions for naming a field?• Besides int, what other data types are there?• Do fields have to be initialized when they are declared?• Are fields assigned a default value it they are not initialized?
In the Java programming language, the terms "field" and "variable" are both used; this is acommon source of confusion among new developers, since both often seem to refer tothe same thing.
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Variables in Java
• The Java programming language defines the following kinds of variables
Instance Variables (Non-Static Fields) - objects store their individual statesin "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are uniqueto each instance of a class. the currentSpeed of one bicycle is independent fromthe currentSpeed of another.
Class Variables (Static Fields) - A class variable is any field declared with thestatic modifier; this tells the compiler that there is exactly one copy of thisvariable in existence, regardless of how many times the class has beeninstantiated. A field defining the number of gears for a particular kind of bicyclecould be marked as static since conceptually the same number of gears willapply to all instances. The code static int numGears = 6; would create such astatic field. Additionally, the keyword final could be added to indicate that thenumber of gears will never change.
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Variables in Java
Local Variables - a method will often store its temporary state in localvariables. There is no special keyword designating a variable as local;that determination comes entirely from the location in which thevariable is declared — which is between the opening and closing bracesof a method. As such, local variables are only visible to the methods inwhich they are declared; they are not accessible from the rest of theclass.
Parameters - parameters are always classified as "variables" not"fields".
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Naming
• Variable names are case-sensitive. A variable's name can be any legalidentifier — an unlimited-length sequence of Unicode letters and digits (a-z,A-Z, 0-9). Always begin your variable names with a letter. Subsequentcharacters may be letters, digits, dollar signs, or underscore characters.
• Spell one word in all lowercase letters. Example: radius, area, weight etc
• For more than one word, capitalize the first letter of each subsequent word. Example: gearRatio, numberOfGears, monthlySalary etc
• Capitalize every letter and separate subsequent words with the underscorecharacter for variables that are made to store constant value, such thatthose with modifiers static, final, and static final both. Example: static final NUM_GEARS = 6;
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Primitive Data Types
• Java programming language is strongly typed• Supports eight primitive data types
byte – 8 bit signed two’s complement integer Range -128 to 127
short - 16 bit signed two’s complement integer Range -32768 to +32767
int - 32 bit signed two’s complement integer Range -2,147,483,648 to 2,147,483,647
long – 64 bit signed two’s complement integer Range -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float - single-precision 32-bit IEEE 754 floating point Range is beyond the scope of discussion
double - double-precision 64-bit IEEE 754 floating point Range is beyond the scope of discussion
boolean – represent one bit of information boolean data type can have one of the two values true or false
Char - single 16-bit Unicode character Range ‘\u000’ (or 0) to ‘\uffff’ (or 65535)
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Primitive Data Types (Contd.)
• Java programming language provides special support forcharacter strings via the java.lang.String class.
• Enclosing your character string within double quotes willautomatically create a new String object;
• for example, String s = “this is a string”;
• String objects are immutable, which means that oncecreated, their values cannot be changed.
• The String class is not technically a primitive data type,but considering the special support given to it by thelanguage, you'll probably tend to think of it as such.
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Default values
• It's not always necessary to assign a value when a field is declared. Fields that aredeclared but not initialized will be set to a reasonable default by the compiler.Generally speaking, this default will be zero or null, depending on the data type.Relying on such default values, however, is generally considered bad programmingstyle.
• Data Type Default Value (for fields)
byte - 0
short - 0
int - 0
long - 0L
float - 0.0f
double - 0.0d
char - '\u0000'
String (or any object) - null
Boolean - false
The compiler never assigns a default value to anuninitialized local variable. If you cannot initializeyour local variable where it is declared, make sureto assign it a value before you attempt to use it.Accessing an uninitialized local variable will result ina compile-time error
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Arrays
• An array is a container object that holds a fixednumber of values of a single type. The length of anarray is established when the array is created. Aftercreation, its length is fixed
• Each item in an array is called an element, and eachelement is accessed by its numerical index
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Declaring a Variable to Refer to an Array
int[] anArray; // declares an array of integers
byte[] anArrayOfBytes; // declares an array of byte
short[] anArrayOfShorts; // declares an array of short
long[] anArrayOfLongs; // declares an array of long
float[] anArrayOfFloats; // declares an array of float
double[] anArrayOfDoubles; // declares an array of double
boolean[] anArrayOfBooleans; // declares an array of boolean
char[] anArrayOfChars; // declares an array of characters
String[] anArrayOfStrings; // declares an array of Strings
float anArrayOfFloats[]; // this form is discouraged
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Creating, Initializing, and Accessing an Array
• Create an arrayanArray = new int[5]; // create an array of integers
If this statement were missing, the compiler would print an error like the following, and compilation would fail
ArrayDemo.java:4: Variable anArray may not have been initialized
• Initializing an arrayanArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
• Another way of initializing the arrayint[] anArray = {100, 200, 300, 400, 500};
• Accessing an arraySystem.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declares an array of integers
anArray = new int[5]; // allocates memory for 10 integers
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
anArray[3] = 400;
anArray[4] = 500;
System.out.println("Element at index 0: " + anArray[0]); System.out.println("Element at index 1: " + anArray[1]); System.out.println("Element at index 2: " + anArray[2]); System.out.println("Element at index 3: " + anArray[3]); System.out.println("Element at index 4: " + anArray[4]); System.out.println("Element at index 5: " + anArray[5]);
}
}
OUTPUT
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Length of array, copying array
• The size of the array can be determined by its built-in length property
// print the array's size to standard output
System.out.println(anArray.length);
• The System class has an arraycopy method that you can use to efficiently copy data fromone array into anotherpublic static void arraycopy(Object src, int srcPos, Object dest,int destPos, int length)
class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n','a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.araycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Multidimensional Arrays
• In the Java programming language, a multidimensional array is simply an array whose components are themselves arrays
• This is unlike arrays in C. A consequence of this is that the rows are allowed to vary in length
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}};
//Mr. Smith
System.out.println(names[0][0] + names[1][0]);
//Ms. Jones
System.out.println(names[0][2] + names[1][1]);
}
}
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Questions
• The term "instance variable" is another name for non-static field
• The term "class variable" is another name for static field
• A local variable stores temporary state; it is declared inside a method
• A variable declared within the opening and closing parenthesis of a method is called a parameter
• Character strings are represented by the class java.lang.String
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Operators
• Assignment, Arithmetic, and Unary Operators
• Equality, Relational, and Conditional Operators
• Bitwise and Bit Shift Operators
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Operator Precedence
Operators Precedence
postfix expr++ expr–
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Operators with higher precedence are evaluated beforeoperators with relatively lower precedence. Operators on thesame line have equal precedence. When operators of equalprecedence appear in the same expression, a rule must governwhich is evaluated first. All binary operators except for theassignment operators are evaluated from left to right;assignment operators are evaluated right to left.
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Questions
• Consider the following code snippet. int i = 10;
int n = i++%5;
What are the values of i and n after the code is executed? • Answer: i is 11, and n is 0
What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))? • Answer: i is 11, and n is 1
• To invert the value of a boolean, which operator would you use? Answer: The logical complement operator "!"
• Which operator is used to compare two values, = or == ? Answer: The == operator is used for comparison, and = is used for
assignment• Explain the following code sample:
result = someCondition ? value1 : value2
Answer: This code should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Control Flow Statements
• The if-then and if-then-else Statements
• The switch Statement
• The while and do-while Statements
• The for Statement
• Branching Statements
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
THANK YOU
BITS C342, Object Oriented Programming