0% found this document useful (0 votes)
7 views27 pages

Lecture-06 Java

The document covers type conversion and arrays in Java, detailing automatic conversions, casting incompatible types, and the behavior of arrays including their declaration, initialization, and multidimensional arrays. It also introduces the String class and ArrayList, explaining their functionalities and methods. Key examples illustrate how to manipulate data types and collections in Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views27 pages

Lecture-06 Java

The document covers type conversion and arrays in Java, detailing automatic conversions, casting incompatible types, and the behavior of arrays including their declaration, initialization, and multidimensional arrays. It also introduces the String class and ArrayList, explaining their functionalities and methods. Key examples illustrate how to manipulate data types and collections in Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lecture-6

Type Conversion and Arrays

Professor Dr. Dipankar Das


Department of ICE, RU
• 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 size than the source type.
– For example, we can assign int to long (widening
conversions)
– Applicable for integer and floating-point types
– However, the numeric types are not compatible with
char or boolean.
– Also, char and boolean are not compatible with each
other.
• Casting Incompatible Types
– Assign an int value to a byte variable? This conversion will not be performed
automatically
• 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.
/ /
• It has this general form:
(target-type) value
• Here, target-type specifies the desired type to convert the specified value to.
• For example,
– int a;
– byte b;
– // ...
– b = (byte) a;
• If the integer’s value is larger than the range of a byte, it will be reduced
modulo. In the case of Byte, it will be mod 128.
• Conversion a floating-point value to integer
value through truncation.
Truncation = / /

• When a floating-point value is assigned to an


integer type, the fractional component is lost.
• For example, if the value 1.23 is assigned to an
integer, the resulting value will simply be 1.
• If the size of the whole number component is
too large to fit into the target integer type, then
that value will be reduced modulo the target
type’s range.
• Type conversions may occur: in expressions. To see why,
consider the following:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
• The intermediate term a * b easily exceeds the range of either
of its byte operands. / /

• To handle this kind of problem, Java automatically promotes


each byte or short operand to int when evaluating an
expression.
• This means that the sub-expression a * b is performed using
integers—not bytes.
• Thus, 2000, the result of the intermediate expression, 50 * 40,
is legal even though a and b are both specified as type byte.
• As useful as the automatic promotions are, they
can cause confusing compile-time errors.
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
• Can be corrected as:
byte b = 50;
b = (byte)(b * 2);
• All byte and short values are promoted to int
• If one operand is a long, the whole expression
is promoted to long.
• If one operand is a float, the entire expression
is promoted to float.
• If any of the operands is double, the result is
double.
• 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.
• A one-dimensional array is, essentially, a list of like-
typed variables
• The general form of a one dimensional array declaration
is
type var-name[ ];
– type declares the base type of the array.
• The base type determines the data type of each element
that comprises the array.
• For example:
int month_days[];
– the value of month_days is set to null, which represents an
array with no value.
– We must allocate memory using new
• Example:
month_days = new int[12];
• After this statement executes, month_days will refer to an
array of 12 integers and all elements in the array will be
initialized to zero.
• Obtaining an array is a two-step process.
– First, we must declare a variable of the desired array type.
– Second, we must allocate the memory that will hold the array,
using new, and assign it to the array variable.
• In Java all arrays are dynamically allocated.
• Once we have allocated an array, we can access a specific
element in the array by specifying its index within square
brackets.
• All array indexes start at zero. For example:
month_days[0] = 31;
month_days[1] = 28;
• Arrays can be initialized when they are declared.
• An array initializer is a list of comma-separated
expressions surrounded by curly braces.
• The array will automatically be created large enough to
hold the number of elements specify in the array
initializer. array- initializer , array
initializer- (elements)

• There is no need to use new.


// 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 };
[Link]("April has " + month_days[3] + " days.");
}
}
• In Java, multidimensional arrays are actually arrays of
arrays.
• For example, the following declares a 2D array variable:
int twoD[][] = new int[4][5];
• This allocates a 4 by 5 array and assigns it to 2D array.
• Conceptually, this array will look like:
// Demonstrate a two-dimensional array.
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++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
}
Since // Manually allocate differing size second dimensions.
multidimensi class TwoDAgain {
onal arrays public static void main(String args[]) {
int twoD[][] = new int[4][];
are actually
twoD[0] = new int[1];
arrays of twoD[1] = new int[2];
arrays, the twoD[2] = new int[3];
length twoD[3] = new int[4];
of each array int i, j, k = 0;
is under your for(i=0; i<4; i++)
control for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
}
// Initialize a two-dimensional array.
class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
[Link](m[i][j] + " ");
[Link]();
}
}
}
• A second form to declare an array:
type[ ] var-name;
• Here, the square brackets follow the type specifier,
and not the name of the array variable.
• For example, the following two declarations are
equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
• The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
• A second form to declare an array:
type[ ] var-name;
• Here, the square brackets follow the type specifier,
and not the name of the array variable.
• For example, the following two declarations are
equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
• The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
• Java’s String is not a simple type. Nor is it simply an array of characters
(as are strings in C/C++). String is a class defined in [Link]
• String defines an object, and a full description of it requires an
understanding of several object-related features.
• The String type is used to declare string variables. You can also declare
arrays of strings.
• A quoted string constant can be assigned to a String variable.
• An object of type String can be assigned to another object of type
String.
• You can use an object of type String as an argument to println( ).
• For example:
String str = "this is a test";
[Link](str);
• String objects have many special features and attributes that make
them quite powerful and easy to use.
• String class has several constructor and methods
• Some methods are:
Method Description
charAt(int index) Returns the char value at the specified index.
compareTo(String anotherString) Compares two strings lexicographically.
concat(String str) Concatenates the specified string to the end of this
string.
substring(int beginIndex, Returns a new string that is a substring of this string.
int endIndex)

toUpperCase() Converts all of the characters in this String to upper case


using the rules of the default locale.
toCharArray() Converts this string to a new character array.
trim() Removes leading and trailing whitespaces
Original: ‘ Hell
Length: 13
public class StringExample { Character at 1:
public static void main(String[] args) {
Uppercase: HE
String greeting = " Hello World ";
Lowercase: he
[Link]("Original: '" + greeting + "'"); Trimmed: 'Hell
[Link]("Length: " + [Link]()); Substring (1-5)
[Link]("Character at 1: " + [Link](1)); Contains 'Worl
[Link]("Uppercase: " + [Link]());
Replace 'l' with
[Link]("Lowercase: " + [Link]());
[Link]("Trimmed: '" + [Link]() + "'");
[Link]("Substring (1-5): " + [Link](1, 5));
[Link]("Contains 'World'? " + [Link]("World"));
[Link]("Replace 'l' with 'x': " + [Link]('l', 'x'));
}
}
• In Java, ArrayList is a class in the [Link]
package that implements the List interface and
provides dynamic array-like functionality.
• It allows you to store and manipulate a
collection of elements.
• Unlike arrays, ArrayList can dynamically grow
and shrink in size as elements are added or
removed.
• Import the package: First, we need to import the
ArrayList class from the [Link] package.
import [Link];
• Creation of an ArrayList:
– We can create an ArrayList object using the ArrayList class
constructor.
– We can also specify the type of elements or object the list
will hold within angle brackets (<>).
ArrayList<Object/Elements>.
ArrayList<String> arrayList = new ArrayList<String>();
// Creates an ArrayList of Strings objects
ArrayList<Integer> integerList = new ArrayList<Integer>();
// Creates an ArrayList of Integers
• Add elements: We can add elements to the
ArrayList using the add() method.
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
• Access elements: We can access elements by
their index using the get() method.
String fruit = [Link](0);
// Retrieves the element at index 0
• Iterate over the ArrayList: We can use loops like for-each
loop or traditional for loop to iterate over the elements
of the ArrayList.
• For-Each:
for (String item : arrayList) {
[Link](item);
}
• Traditional for loop:
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i));
}
• ArrayList provides many other useful methods for
manipulating the list, such as set(), clear(), contains(),
indexOf(), isEmpty(), addAll(), removeAll(), etc.
import [Link]; // Removing an element
[Link]("Mango");
public class ArrayListExample { [Link]("After removing Mango: " +
fruits);
public static void main(String[] args) {
// Creating an ArrayList of Strings // Checking size
ArrayList<String> fruits = new ArrayList<>(); [Link]("Size of list: " + [Link]());

// Adding elements // Looping through elements


[Link]("Apple"); [Link]("Looping through ArrayList:");
[Link]("Banana");
for (String fruit : fruits) {
[Link](fruit);
[Link]("Mango");
}
Fruits List:} [Apple, Banana, Mango]
// Printing the ArrayList First Fruit:
} Apple
[Link]("Fruits List: " + fruits); After updating second fruit: [Apple, Orange, Mango]
After removing Mango: [Apple, Orange]
// Accessing elements
Size of list: 2
[Link]("First Fruit: " + [Link](0));
Looping through ArrayList:
// Changing an element
Apple
[Link](1, "Orange"); Orange
[Link]("After updating second fruit: " + fruits);
• What will be the output?
class Main {
public static void main(String[] args) {
int x;
float y=12345.12f;
x = (int)y;
[Link]("Type Conversion: "+x);
}
}
• Control Statements

You might also like