Thanks to visit codestin.com
Credit goes to www.slideshare.net

Java Basics-II
Topics to be Covered:
•Scope and life time of variables
•Type Conversion and Type Casting
•Arrays
•Operators
•Expressions
•Control statements
Scope and life time of variables
• A block is begun with an opening curly brace and ended by a
closing curly brace. A block defines a scope. Thus, each time
you start a new block, you are creating a new scope.
• A scope determines what objects are visible to other parts of
your program. It also determines the lifetime of those objects.
• In Java, the two major scopes are those defined by a class and
those defined by a method.
• Variables declared inside a scope are not visible (that is,
accessible) to code that is defined outside that scope. Thus,
when you declare a variable within a scope, you are localizing
that variable and protecting it from unauthorized access
and/or modification.
Scopes can be nested. For example, each time you create a
block of code, you are creating a new, nested scope. When this
occurs, the outer scope encloses the inner scope. This means
that objects declared in the outer scope will be visible to code
within the inner scope. However, the reverse is not true. Objects
declared within the inner scope will not be visible outside it.
Ex. Class Visible
{
int a=10;
viod show()
{
int b=20;
System.out.println(“a and b values
are:”+a+” “+b);
}
System.out.println(“b value
} is:”+b)//error
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
x and y:10 20
•Variables are created when their scope is entered, and destroyed
when their scope is left. This means that a variable will not hold its
value once it has gone out of scope. Therefore, variables declared
within a method will not hold their values between calls to that
method.
•Also, a variable declared within a block will lose its value when the
block is left. Thus, the lifetime of a variable is confined to its scope.
If a variable declaration includes an initializer, then that variable will
be reinitialized each time the block in which it is declared is entered.
// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y); } } }
The output generated by this program is shown here:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
As you can see, y is reinitialized to –1 each time the
inner for loop is entered. Even though it is subsequently
assigned the value 100, this value is lost.
Although blocks can be nested, you cannot declare a
variable to have the same name as one in an outer
scope. For example, the following program is illegal:
// This program will not compile
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}
Type Conversion and Casting
• We can assign a value of one type to a variable of another
type. If the two types are compatible, then Java will perform
the conversion automatically. For example, it is always
possible to assign an int value to a long variable.
• However, not all types are compatible, and thus, not all type
conversions are implicitly allowed. For instance, there is no
automatic conversion defined from double to byte.
• To obtain a conversion between incompatible types. You must
use a cast, which performs an explicit conversion between
incompatible types.
Source Destination Compatibility
int long compatible
double byte incompatible
Java’s Automatic Conversions
When one type of data is assigned to another type of variable, an
automatic type conversion
will take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes
place. For example, the int type is always large enough to hold
all valid byte values, so no explicit cast statement is
required.
For widening conversions, the numeric types, including integer
and floating-point types are compatible with each other.
However, there are no automatic conversions from the numeric
types to char or boolean.
Also, char and boolean are not compatible with each other.
Casting Incompatible Types
For example, what if you want to assign an int value to a byte
variable? This conversion will not be performed automatically,
because a byte is smaller than an int. This kind of conversion is
sometimes called a narrowing conversion, since you are explicitly
making the value narrower so that it will fit into the target type.
To create a conversion between two incompatible types, you must
use a cast. A cast is simply an explicit type conversion.
Syntax: (target-type) value
int a;
byte b;
// ...
b = (byte) a;
A different type of conversion will occur when a floating-point
value is assigned to an integer type: truncation.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
This program generates the following output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
Arrays
• An array is a group of like-typed variables that are referred to by a
common name. Arrays of any type can be created and may have
one or more dimensions. A specific element in an array is
accessed by its index. Arrays offer a convenient means of grouping
related information.
One-Dimensional Arrays
• A one-dimensional array is, essentially, a list of like-typed
variables. To create an array, you first must create an array
variable of the desired type. The general form of a one-
dimensional array declaration is
type var-name[ ];
• For example, the following declares an array named month_days
with the type “array of int”:
int month_days[];
The general form of new as it applies to one-dimensional arrays appears
as follows:
array-var = new type[size];
Ex.
int month_days[];
month_days = new int[12];
or
int month_days[] = new int[12];
// Demonstrate a one-dimensional array.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
// An improved version of the previous program.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays.
Ex. int twoD[][] = new int[4][5];
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
Operators
• Java provides a rich set of to manipulate variables. We can
divide all the Java operators into the following groups:
• Arithmetic Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Misc Operators
Arithmetic operators
Arithmetic operators are used in mathematical expressions in
the same way that they are used in algebra. The following table
lists the arithmetic operators. Assume integer variable A holds
10 and variable B holds 20, then:
Opera
tor
Description Example
+ Addition - Adds values on either side of the
operator
A + B will
give 30
- Subtraction - Subtracts right hand operand from
left hand operand
A - B will
give -10
* Multiplication - Multiplies values on either side of
the operator
A * B will
give 200
/ Division - Divides left hand operand by right hand
operand
B / A will
give 2
% Modulus - Divides left hand operand by right
hand operand and returns remainder
B % A will
give 0
++ Increment - Increases the value of operand by 1 B++ gives
21
-- Decrement - Decreases the value of operand by 1 B-- gives 19
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
}
}
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}

Introduction to Java Basics Programming-II.pptx

  • 1.
  • 2.
    Topics to beCovered: •Scope and life time of variables •Type Conversion and Type Casting •Arrays •Operators •Expressions •Control statements
  • 3.
    Scope and lifetime of variables • A block is begun with an opening curly brace and ended by a closing curly brace. A block defines a scope. Thus, each time you start a new block, you are creating a new scope. • A scope determines what objects are visible to other parts of your program. It also determines the lifetime of those objects. • In Java, the two major scopes are those defined by a class and those defined by a method. • Variables declared inside a scope are not visible (that is, accessible) to code that is defined outside that scope. Thus, when you declare a variable within a scope, you are localizing that variable and protecting it from unauthorized access and/or modification.
  • 4.
    Scopes can benested. For example, each time you create a block of code, you are creating a new, nested scope. When this occurs, the outer scope encloses the inner scope. This means that objects declared in the outer scope will be visible to code within the inner scope. However, the reverse is not true. Objects declared within the inner scope will not be visible outside it. Ex. Class Visible { int a=10; viod show() { int b=20; System.out.println(“a and b values are:”+a+” “+b); } System.out.println(“b value } is:”+b)//error
  • 5.
    // Demonstrate blockscope. class Scope { public static void main(String args[]) { int x; // known to all code within main x = 10; if(x == 10) { // start new scope int y = 20; // known only to this block // x and y both known here. System.out.println("x and y: " + x + " " + y); x = y * 2; } y = 100; // Error! y not known here // x is still known here. System.out.println("x is " + x); } } x and y:10 20
  • 6.
    •Variables are createdwhen their scope is entered, and destroyed when their scope is left. This means that a variable will not hold its value once it has gone out of scope. Therefore, variables declared within a method will not hold their values between calls to that method. •Also, a variable declared within a block will lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope. If a variable declaration includes an initializer, then that variable will be reinitialized each time the block in which it is declared is entered. // Demonstrate lifetime of a variable. class LifeTime { public static void main(String args[]) { int x; for(x = 0; x < 3; x++) { int y = -1; // y is initialized each time block is entered System.out.println("y is: " + y); // this always prints -1 y = 100; System.out.println("y is now: " + y); } } }
  • 7.
    The output generatedby this program is shown here: y is: -1 y is now: 100 y is: -1 y is now: 100 y is: -1 y is now: 100 As you can see, y is reinitialized to –1 each time the inner for loop is entered. Even though it is subsequently assigned the value 100, this value is lost. Although blocks can be nested, you cannot declare a variable to have the same name as one in an outer scope. For example, the following program is illegal:
  • 8.
    // This programwill not compile class ScopeErr { public static void main(String args[]) { int bar = 1; { // creates a new scope int bar = 2; // Compile-time error – bar already defined! } } }
  • 9.
    Type Conversion andCasting • We can assign a value of one type to a variable of another type. If the two types are compatible, then Java will perform the conversion automatically. For example, it is always possible to assign an int value to a long variable. • However, not all types are compatible, and thus, not all type conversions are implicitly allowed. For instance, there is no automatic conversion defined from double to byte. • To obtain a conversion between incompatible types. You must use a cast, which performs an explicit conversion between incompatible types. Source Destination Compatibility int long compatible double byte incompatible
  • 10.
    Java’s Automatic Conversions Whenone type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met: • The two types are compatible. • The destination type is larger than the source type. When these two conditions are met, a widening conversion takes place. For example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is required. For widening conversions, the numeric types, including integer and floating-point types are compatible with each other. However, there are no automatic conversions from the numeric types to char or boolean. Also, char and boolean are not compatible with each other.
  • 11.
    Casting Incompatible Types Forexample, what if you want to assign an int value to a byte variable? This conversion will not be performed automatically, because a byte is smaller than an int. This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the value narrower so that it will fit into the target type. To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. Syntax: (target-type) value int a; byte b; // ... b = (byte) a; A different type of conversion will occur when a floating-point value is assigned to an integer type: truncation.
  • 12.
    class Conversion { publicstatic void main(String args[]) { byte b; int i = 257; double d = 323.142; System.out.println("nConversion of int to byte."); b = (byte) i; System.out.println("i and b " + i + " " + b); System.out.println("nConversion of double to int."); i = (int) d; System.out.println("d and i " + d + " " + i); System.out.println("nConversion of double to byte."); b = (byte) d; System.out.println("d and b " + d + " " + b); } } This program generates the following output: Conversion of int to byte. i and b 257 1 Conversion of double to int. d and i 323.142 323 Conversion of double to byte. d and b 323.142 67
  • 13.
    Arrays • An arrayis a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. Arrays offer a convenient means of grouping related information. One-Dimensional Arrays • A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you first must create an array variable of the desired type. The general form of a one- dimensional array declaration is type var-name[ ]; • For example, the following declares an array named month_days with the type “array of int”: int month_days[];
  • 14.
    The general formof new as it applies to one-dimensional arrays appears as follows: array-var = new type[size]; Ex. int month_days[]; month_days = new int[12]; or int month_days[] = new int[12];
  • 15.
    // Demonstrate aone-dimensional array. class Array { public static void main(String args[]) { int month_days[]; month_days = new int[12]; month_days[0] = 31; month_days[1] = 28; month_days[2] = 31; month_days[3] = 30; month_days[4] = 31; month_days[5] = 30; month_days[6] = 31; month_days[7] = 31; month_days[8] = 30; month_days[9] = 31; month_days[10] = 30; month_days[11] = 31; System.out.println("April has " + month_days[3] + " days."); } }
  • 16.
    // An improvedversion of the previous program. class AutoArray { public static void main(String args[]) { int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; System.out.println("April has " + month_days[3] + " days."); } } Multidimensional Arrays In Java, multidimensional arrays are actually arrays of arrays. Ex. int twoD[][] = new int[4][5];
  • 17.
    class TwoDArray { publicstatic void main(String args[]) { int twoD[][]= new int[4][5]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<5; j++) { twoD[i][j] = k; k++; } for(i=0; i<4; i++) { for(j=0; j<5; j++) System.out.print(twoD[i][j] + " "); System.out.println(); } } } This program generates the following output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
  • 18.
    Operators • Java providesa rich set of to manipulate variables. We can divide all the Java operators into the following groups: • Arithmetic Operators • Relational Operators • Bitwise Operators • Logical Operators • Assignment Operators • Misc Operators Arithmetic operators Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators. Assume integer variable A holds 10 and variable B holds 20, then:
  • 19.
    Opera tor Description Example + Addition- Adds values on either side of the operator A + B will give 30 - Subtraction - Subtracts right hand operand from left hand operand A - B will give -10 * Multiplication - Multiplies values on either side of the operator A * B will give 200 / Division - Divides left hand operand by right hand operand B / A will give 2 % Modulus - Divides left hand operand by right hand operand and returns remainder B % A will give 0 ++ Increment - Increases the value of operand by 1 B++ gives 21 -- Decrement - Decreases the value of operand by 1 B-- gives 19
  • 20.
    class BasicMath { publicstatic void main(String args[]) { // arithmetic using integers System.out.println("Integer Arithmetic"); int a = 1 + 1; int b = a * 3; int c = b / 4; int d = c - a; int e = -d; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); System.out.println("e = " + e); } }
  • 21.
    class IncDec { publicstatic void main(String args[]) { int a = 1; int b = 2; int c; int d; c = ++b; d = a++; c++; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); } }