Beruflich Dokumente
Kultur Dokumente
PG-DESD Aug-2013
Session 2:
Learning Objectives
By the end of this session, you must be able to Explain basic programming constructs of Java Explain Classes and Objects in Java Use instance data and methods Use new operator to create instances Explain Constructors - Overloading
Identifiers:
Identifiers are the named words a programmer uses in a program An identifier can be made up of letters, digits, the underscore character (_), and the dollar sign ($) They cannot begin with a digit Java is case sensitive, therefore different identifiers Total and total are
Reserved Words
Often we use special identifiers called reserved words that already have a predefined meaning in the language A reserved word cannot be used in any other way default do double else extends false final finally float for future generic goto if implements import inner instanceof int interface long native new null operator outer package private protected public rest return short static super switch synchronized this throw throws transient true try var void volatile while
abstract boolean break byte byval case cast catch char class const continue
Variables
Programming languages uses variables to store data To allocate memory space for a variable JVM requires:
1) To specify the data type of the variable 2) To associate an identifier with the variable 3) Optionally, the variable may be assigned an initial value
All done as part of variable declaration.
type identifier [=value][, identifier [=value] ]; Examples: int a, b, c; int d = 3, e, f = 5; byte g = 22; double pi = 3.14159; char ch = 'x';
Constants
A constant is an identifier that is similar to a variable except that it holds one value for its entire existence The compiler will issue an error if you try to change a constant In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69;
Example:
int 32-bit integer type long 64-bit integer type float 32-bit floating-point type double 64-bit floating-point type char symbols in a character set (16-bit Unicode) boolean logical values true and false
Data type Bytes Min Value byte short int long float double char boolean 1 2 4 8 4 8 2 -27 -215 -231 -263 0 -
Literal Values 123 1234 12345, 086, 0x675 123456 1.0 123.86 a, \n true, false
General rule: Min value = 2(bits 1) Max value = 2(bits-1) 1 (where 1 byte = 8 bits)
10
Operators - Types
Types of operators
Assignment Operators Arithmetic Operators Unary Operators Equality Operators Relational Operators Conditional Operators instaceof Operator Bitwise Operators Shift Operators
11
Assignment Operator
Operator
=
Description
Assignment
Example
int i = 10; int j = i;
Arithmetic Operators Operator + * Description Addition Subtraction Multiplication Example int i = 8 + 9; byte b = (byte) 5+4; int i = 9 4; int i = 8 * 6;
/
%
Division
Remainder
int i = 10 / 2;
int i = 10 % 3;
12
++ -!
Unary minus
Increment Decrement Logical Not
int i = -1;
int j = i++; int j = i--; boolean j = !true;
== !=
If (i==1) If (i != 4)
13
>
< >= <=
Greater than
Less than Greater than or equal to Less than or equal to
if ( x > 4)
if ( x < 4) if ( x >= 4) if ( x <= 4)
Conditional Operators Operator && || Description Conditional and Conditional or Example If (a == 4 && b == 5) If (a == 4 || b == 5)
14
instanceof
Instance of
Bitwise Operators Operator & | Description Bitwise and Bitwise or Example 001 & 111 = 1 001 | 110 = 111
^
~
Bitwise ex-or
Reverse
Shift Operators
Operator >> Description Right shift Example 4 >> 1 = 0100 >> 1 = 0010 = 2
<<
>>>
Left Shift
Unsigned Right shift
class ArithmeticDemo { public static void main (String[] args){ // result is now 3 int result = 1 + 2; System.out.println(result); // result is now 2 result = result - 1; System.out.println(result);
Arithmetic Example
Logical Example
class BitDemo { public static void main(String[] args) { int bitmask = 0x000F; int val = 0x2222; System.out.println(val & bitmask); } }
Examples
class ConditionalDemo1 { public static void main(String[] args){ int value1 = 1; int value2 = 2; if((value1 == 1) && (value2 == 2)) System.out.println("value1 is 1 AND value2 is 2"); if((value1 == 1) || (value2 == 1)) System.out.println("value1 is 1 OR value2 is 1"); } }
class ConditionalDemo2 { public static void main(String[] args){ int value1 = 1; int value2 = 2; int result; boolean someCondition = true; result = someCondition ? value1 : value2; System.out.println(result); } }
Operator Precedence
Selection Statements
Java selection statements allow us to control the flow of programs execution based upon conditions known only during run-time. Java provides four selection statements:
1) 2) 3) 4)
Syntax
Example
if (<condition-1>) { // logic for true condition-1 goes here } else if (<condition-2>) { // logic for true condition-2 goes here } else { // if no condition is met, control comes here }
int a = 10; if (a < 10 ) { System.out.println(Less than 10); } else if (a > 10) { System.out.pritln(Greater than 10); } else { System.out.println(Equal to 10); } Result: Equal to 10s
22
switch
Example
Syntax
switch (<value>) { case <a>: // stmt-1 break; case <b>: //stmt-2 break; default:
//stmt-3
int a = 10; switch (a) { case 1: System.out.println(1); break; case 10: System.out.println(10); break; default: System.out.println(None); Result: 10
23
class SwitchDemo2 { public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31;break; case 4: case 6: case 9: case 11: numDays = 30; break case 2: if (year % 4 == 0) numDays = 29; else numDays = 28 break; default: System.out.println("Invalid month."); break; } System.out.println("N umber of Days =+ numDays); } }
Iteration Statements
Java iteration statements enable repeated execution of part of a program until a certain termination condition becomes true.
do-while
Syntax Example
int i = 0; do { System.out.println(In do); i++; } while ( i < 10); Result: Prints In do 11 times
while
Syntax Example
for
Syntax Example
for ( initialize; condition; expression) for (int i = 0; i < 10; i++) { { // stmt System.out.println(In for); } } Result: Prints In do 10 times
29
For-each style
class ForDemo2 // for each style { public static void main(String[] args) { int arr[]={10,20,30,40,50}; for(int i: arr) { System.out.println("Count="+i); } } }
Jump Statements
Java jump statements enable transfer of control to other parts of program. Java provides three jump statements: 1) break
2) continue 3) return
In addition, Java supports exception handling that can also alter the control flow of a program.
class BreakDemo { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,2000, 8, 622, 127 }; int searchfor = 12; int i; boolean foundIt = false; for (i = 0; i < arrayOfInts.length; i++) { if (arrayOfInts[i] == searchfor) { foundIt = true; break; } } if (foundIt) { System.out.println("Found " + searchfor + " at index " + i); } else { System.out.println(searchfor + " not in the array"); } } }
class ContinueDemo { public static void main(String[] args) { String searchMe = "peter piper picked a " + "peck of pickled peppers"; int max = searchMe.length(); int numPs = 0; for (int i = 0; i < max; i++) { // interested only in p's if (searchMe.charAt(i) != 'p') continue; // process p's numPs++; } System.out.println("Found " + numPs + " p's in the string."); } }
Coding Guidelines
What is an Object?
Real world entities or things which have: 1) State
What is a Class?
Class is basis for the Java language. Each concept we wish to describe in Java must be included in a class. Class is a group of set of values and set of operations A class is a template for objects A class is a blueprint / prototype that defines the variables and methods common to all objects of a certain kind. Example: your dog is a object of the class Dog. An object holds values for the variables defined in the class. A class defines a new data type, whose values are objects
Class Definition
A class consists of : Name, Several variable declarations (instance variables) Several method declarations These are called members of the class A Class also consists constructors and blocks General form of a class: class classname { type instance-variable-1; type instance-variable-n; type method-name-1(parameter-list) { }
Example Program
Object Destruction
A program accumulates memory through its execution. Two mechanisms to free memory that is no longer needed by the program:
Constructor
A constructor used to initialize the state of an object. It is invoked at the time of object creation It constructs the values (data) for the object Features: 1) It is syntactically similar to a method 2) It has the same name as the name of its class 3) It is written without return type; The default return type is the class
When the class has no constructor, the default constructor automatically supplied the compiler.
Example: Constructor
class Box { double width; double height; double depth; Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } double volume() { return width * height * depth; } }
Default Constructor
Parameterized Constructor
Constructor Overloading
Method Overloading
A class with multiple methods by the same name but different parameters Implements polymorphism in java (static) Three ways: Number of arguments Types of arguments Order and Type of argument
Method Overloading
Method Overloading
Method Overloading
Parameter Passing
Only pass-by value or call by value is available in Java. There is no call by reference. Primitive data types and objects can be passed as values
Parameter Passing
Assignment Lab: Get yourself acquainted with java environment. Build a class Emp, which contains details about the Employee and compile and run its instances.
-Create instances ( minimum 3) - Constructors - Methods - Overloaded methods and constructors - Copy objects one to other
Next.
this facility static member, static method and static block JDK and its Usage Garbage Collection
Class
Class Variables
Methods
Method Variables
private
protected default final abstract strictfp
transient
synchronized native volatile static
63
Modifiers Class
public
Class can be accessed from any other class present in any package
default
Class can be accessed only from within the same package. Classes outside the package in which the class is defined cannot access this class
final
abstract
Class cannot be instantiated, need to sub-classs/extend.
strictfp
Conforms that all methods in the class will conform to IEEE standard rules for floating points
64
public
Attribute can be accessed from any other class present in any package Attribute can be accessed from only within the class Attribute can be accessed from all classes in the same package and subclasses. Attribute can be accessed only from within the same package. This value of the attribute cannot be changed, can assign only 1 value The attribute value cannot be serialized Thread always reconciles its own copy of attribute with master. Only one value of the attribute per class
private
protected default final transient
volatile
static
65
Modifiers Methods
public
Method can be accessed from any other class present in any package
private
Access Levels
Modifier
public protected
Class
Y Y
Package
Y Y
Subclass
Y Y
World
Y N
no modifier
private
Y
Y
Y
N
N
N
N
N
Assignment Lab: Get yourself acquainted with java environment. Build a class Emp, which contains details about the Employee and compile and run its instances.
-Create instances ( minimum 3) - Constructors - Methods - Overloaded methods and constructors - Copy objects one to other
Assignment Reading: Study the book Java FAQ Assignment Tutorial: Compare and contrast C++ and Java
Questions?