Java Programming Lab
Session 2
By : Dr. Amar Arora
USAR, GGSIPU-EDC
Java Variables
• Primitive data types - includes byte(1), short(2), int(4), long(8),
float(4), double(8), boolean(1) and char(2)
• Non-primitive data types - such as String, Arrays and Classes
have variable sizes.
Java Variables ( Examples)
int intVal = 10; // Integer (whole number)
float floatVal = 7.997272f; // Floating point number
char charVal = 'A'; // Character
boolean boolVal = true; // Boolean
String stringText = "GGSIPU"; // String
Type Casting
Java supports two types of casting:
● Widening Casting (automatic conversion) - converting a smaller type to
a larger type size
byte -> short -> char -> int -> long -> float -> double
● Narrowing Casting (manual conversion) - converting a larger type to a
smaller size type
double -> float -> long -> int -> char -> short -> byte
Java is strict in Narrowing Casting and don’t allow it automatically under
any case.
Java Conditional Statements
All Conditional tests are done on the basis of boolean [Link] true or false.
class BooleanTest {
public static void main(String[] args) {
if(1)
{
[Link]("Hello, World!");
}
}
}
//Returns an error: incompatible types: int cannot be converted to boolean
Switch Statements
• Switch in Java works similar to C except that switch expression can be of byte,
short, int, long (with its Wrapper type), enums and also String (From JE 7).
• default and break in the same fashion as in C and C++
String levelTest="Pass";
switch(levelTest){
case "Pass":[Link](“Passed”);
break;
case "Fail": [Link](“Failed”);
break;
default: [Link](“Default”); }
Loops
Java supports while, do while, for and for each loops
While, do while and for works as C/C++, but they must have boolean
conditions to verify.
For each is exclusively used for arrays:
String[] names = {"GGSIPU", "USAR", "EDC"};
for (String i : names) {
[Link](i);
}
Programs to execute
3. WAP to make a an object of Class Fibonacci in the another class
DisplaySeries and print the Fibonacci Series till n.
4. WAP to print elements of an array in reverse order by using for,
while and do while loops in separate member functions.