Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

Introduction to JAVA

Data-types and Control Constructs

Achintya Singhal
Primitive DATA Types
• The primitive types byte, short, int and long defined in the
Java language allow for the representation of discrete
integer values of widths 8, 16, 32, and 64 bits,
respectively.
• The primitive types float and double allow for the
representation of single and double precision floating-
point real values with representational widths of 32 and
64 bits, respectively.
• The primitive types char and boolean allow for 16-bit
multi-byte characters and false/true boolean values,
respectively.
Operators
• Arithmetic Operators
• The arithmetic operators in Java include the common
addition “+”, subtraction “-”, multiplication “*” and
division “/” operations.
– These operators apply to numeric operands, and return the type
of operands. When operands are mixed, the widest is used to
prevent unexpected truncation
• The “%” operator returns the remainder of integer
division.
• When used as a unary operator, “-” negates the numeric
operand.
Operators
• Logical Operators
• The logical operators in Java include the
standard and “&&”, or “||” and not “!”. Each
operator returns a boolean result
Operators
• Relational Operators
• The equality “==” and inequality “!=”
operators in Java operate on all values and
objects to return a boolean result.
• < less than
• > greater than
• <= less than or equal
• >= greater than or equal
Operators
• Bitwise Operators
• The following bitwise operators in Java operate on
corresponding bits of byte, short, int and long values.
• & bitwise “and”
• ^ bitwise exclusive “or”
• | bitwise inclusive “or”
• ~ bitwise one’s complement
• >> << right and left bitwise shift
• >>> right bitwise unsigned shift
Operators
• Assignment
• Having seen the basic means of providing new
values to variables, assignment “=” is more
correctly viewed as an operator rather than a
statement. In addition to assigning the right-side
value to the left-side variable, it also returns the
value assigned.
• a = b = 2;
• x op= f; is same as x = x op f;
Operators
Auto increment & Auto decrement (Prefix and Postfix)
int f, g; int f, g;
f = 6; f = 6;
g = f++; g = ++f;
// g has 6 // g has 7
// f has 7 // f has 7

int f, g; int f, g;
f = 6; f = 6;
g = f--; g = --f;
// g has 6 // g has 5
// f has 5 // f has 5

There is a subtle difference between x[i++] += 4 and x[i++] = x[i++] + 4, in that i++ is
evaluated once in the former but twice in the latter.
Operators
• Conditional Expression
– The conditional expression operator ? : returns one
of two values depending on the boolean condition.
For example, the expression A?B:C returns the value
of B if A is true, else the value of C is returned.
• Typecast
– The typecast operator (type)E for a numeric type
(such as int, float, or double), converts the value to
the specified type.
Operator Precedence
Operator Precedence
• Precedence allows the expression “a>>b+c” to be
unambiguously interpreted as “a>>(b+c)”, and not “(a>>b)
+c”. Similarly, “!m&&n” is interpreted as “(!m)&&n” and
not “!(m&&n)”.
• Associativity rules come into effect when equal precedence
levels do not help in resolving evaluation order. Due to
associativity rules (which is left-to-right for “/” and “*”, that
is, evaluating the left operator and then right), “a/b*c” is
interpreted as “(a/b)*c” and not “a/(b*c)”.
• Similarly, due to right-to-left associativity, “~y++” is
interpreted as “~(y++)” instead of “(~y)++”.
Object Instantiation
• A class construct provides a description for
objects of that class, and serves as a template
for objects to be created. However, no
instances of the class is crested, except by
calling the object allocator function new(). The
expression new Counter() returns a newly
created instance of the Counter class. However,
in order that this new object may be referred
to, it is assigned to an appropriate variable.
Representational Independence
• While accessing object attributes directly is permissible, it is
not ideal because it couples implementation code to the
current object representation.
• A common object-oriented programming practice is
information hiding—to make object representations
inaccessible to clients so that modifications in object
representations do not propagate excessively.
• Limiting access to object representations in Java is mainly
achieved by the two main constraint specifiers i.e. private and
public. The former limits access of the following entity to
within the class construct, while the latter makes it accessible
to any client code.
Overloading

• Attribute names of a class may be the same as those in


another class since they are accessed independently. An
attribute x in a class does not necessarily have any semantic
bearing with another as they have different scopes.
• Within a Java class construct, methods may share the same
name as long as they may be distinguished either by:
– the number of parameters, or
– different parameter types.
• This criterion requires a message with associated parameters
to be uniquely matched with the intended method definition.
Blocks
• A block, indicated by { }, may occur at any location
where a statement is valid. It is considered the
sequential construct as the group of statements it
surrounds is treated as a single statement or
processing unit.
• Thus, while the various control-flow constructs
merely show a single statement as the constituent
body, a block may be used where such constructs
should contain more than one statement.
Local Declarations
• In treating a statement sequence as a single statement, a block may also be thought of as a
sub-machine which fulfils a specific task. As such, the scope of local variable declarations is
the rest of the block in which the declaration occurs. This allows declarations and
associated references to be localized, thereby aiding maintainability.
– while (k > 1) {
– f = f*k;
– if (k % 2 == 0) {
– double d = 4.5;
– ....
– even++;
– } else {
– long d = 23546;
– ...
– sumOfOdd = sumOfOdd + k;
–}
– k--;
–}
Control-flow Statements
• The statements are commonly grouped under:
– Conditional statements
• Conditional statements allow for conditions to be
attached to a statement as to whether it will be
executed.
– Iterative statements
Conditional Statements
• if statement
– the statement S is executed only if the boolean condition E
evaluates to true
if (E)
S;
• if-else statement
– If the boolean condition E evaluates to is true and S is executed,
then R would not. If S is not executed, then R would be
if (E)
S;
else
R;
Conditional Statements
• switch statement :allows for multi-way selection
• switch (E) {
• c1: S1;
• break;
• c2: S2;
• break;
• c3: S3;
• c4: S4;
• break;
• default: Sd;
• }
Iterative Statements
• while-statement: a pre-test loop
– repeatedly execute till the boolean condition E is true. The loop terminates
when E is false, after which execution proceeds to the next statement
• while (E)
• S;
• do-while statement: a post-test loop
– R is first executed and subsequently while the boolean expression F
evaluates to true, R is executed again. Again, the loop terminates when F
evaluates to false. Thus, this control flow construct will execute R at least
once.
• do {
• R;
• } while (F);
Iterative Statements
• for-statement: a counter-controlled loop
– for (f = 1; k > 1; k--)
– f = f*k;
– Generic Form
• for (Q; R; S)
• T;
– where Q, T, and S are the initializer, conditional and re-
initializer expressions
Break & Continue
• The break-statement : allows for a quick exit
from the iteration. Its more generic function is
to transfer control out of the innermost switch,
while, do or for-statement.
• The continue-statement: transfers control to
the beginning of the innermost iterative loop so
as to re-evaluate the boolean condition for the
next iteration. Unlike, the break-statement,
control-flow does not exit from the loop.
Arrays
• Just as objects are created dynamically (run-time during
program execution), arrays in Java are similarly created. The size
of an array need not be specified or computed during
compilation.
• An array is thus declared using the subscript operator, but
without indication of the upper bound:
• Counter gates[];
• An array is created via the new operator, but with the array size
within square brackets:
• gates = new Counter[8];
• The array size associated with gates is 8, but this does not imply
eight Counter objects.
Arrays contd...
• it is important to understand a Counter array as
being similar with multiple variables, that is, it is
an object that does not further contain Counter
objects but merely references eight potential
Counter objects. Thus, individual array elements
must be created explicitly:
• Counter gates[];
• gates = new Counter[8];
• for (int i=0; i<8; i++);
• gates[i] = new Counter();
Result Returned by Method
• A method in a class definition has the following general form, with the
return-statement returning control-flow back to the message sender:
• T foo(gT g, hT h ...)
• {
• // local definitions
• // statements
• return v;
• }
• The value returned v, must be of the type T as indicated in the method
signature.
• If the sender does not require any results, the keyword void should be used
as the return type. In this case, the returning expression v would be omitted
in the return statement.
• The return-statement need not be the last statement, but multiple return
statements might be used
Assignment
• Define a Square class with the length of its side as an instance
variable. Include an appropriate constructor method and
methods to enlarge an instance as well as compute its area.
• Using the Square class, create ten randomly sized squares and
find the sum of their areas. (The method Math.random() returns
a random number between 0.0 and 1.0 each time it is invoked.)
• Add the functionality for a Square object to draw itself via ASCII
characters. For example, a Square of length 4 can be drawn as:
****
* *
* *
****

You might also like