Lab 2
Lab 2
Objective:
● To learn about the primitive data types and variables in Java
● To know about the user input and output
● To learn about the different types of operators (Assignment, Arithmetic,
Relational, Logical Operators etc.)
● To learn to use conditional statements (if-else, switch case)
● To know about Enumerated Data Types
1
Page-1
Variable Narrowing: When a larger primitive type value is assigned in a smaller size primitive
data type, this is called narrowing of the variable. It can cause some data loss due to less number
of bits available to store the data. It requires explicit type-casting to the required data type. In the
given example, float type variable is assigned to int type variable with data loss.
Overflow: Overflow occurs when we assign such a value to a variable which is more than the
maximum permissible value. In the given example, the overflow occurred since byte datatype
value-range lies between -128 to 127 (inclusive) which is much less than int datatype value-range.
// Narrowing/Typecasting
float aFloat2 = 10.5F;
//int aInt2 = aFloat2; //Compile time error
int aInt2 = (int)aFloat2;
System.out.println(aFloat2);
System.out.println(aInt2);
// Overflow
int aInt = 130;
byte aByte = (byte)aInt;
System.out.println(aInt);
System.out.println(aByte);
}
}
Page No: 2
System.out.print("Enter a String: ");
String s = input.next();
input.close();
}
}
Operators:
Java provides a rich set of operators to manipulate variables such as Arithmetic Operators,
Relational Operators, Logical Operators, Ternary Operators. Following code shows how to find min
and max of two number using Ternary Operator.
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}
Page No: 3
3
else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}
else{
System.out.println("Invalid!");
}
}
}
Enumerated Types:
Enumerations represent a group of named constants in Java. Enums are used when we know all
possible values at compile time, such as choices on a menu, command line flags, etc. In Java,
enums are represented using enum data type. Additionally, we can add variables, methods, and
constructors to it. The main objective of enum is to define our own data types, called Enumerated
Data Types.
Page No: 4
Page No: 5