Unit-2
Structuring the Data, Computations and Program
Q1) What are the Elementary Data Types?
A1) Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java language.
Java is a statically-typed programming language. It means, all variables must be declared before its use. That is why we need to declare variable's type and name.
There are 8 types of primitive data types:
Data Type | Default Value | Default size |
Boolean | false | 1 bit |
Char | '\u0000' | 2 bytes |
Byte | 0 | 1 byte |
Short | 0 | 2 bytes |
Int | 0 | 4 bytes |
Long | 0L | 8 bytes |
Float | 0.0f | 4 bytes |
Double | 0.0d | 8 bytes |
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example: Boolean one = false
Byte Data Type
The byte data type is an example of primitive data type. It is an 8-bit signed two's complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Example: byte a = 10, byte b = -20
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller than an integer.
Example: short s = 10000, short r = -5000
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem about memory.
Example: int a = 100000, int b = -200000
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1) (inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a range of values more than those provided by int.
Example: long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is unlimited. It is recommended to use a float (instead of double) if you need to save memory in large arrays of floating-point numbers. The float data type should never be used for precise values, such as currency. Its default value is 0.0F.
Example: float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type is generally used for decimal values just like float. The double data type also should never be used for precise values, such as currency. Its default value is 0.0d.
Example: double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\off' (or 65,535 inclusive). The char data type is used to store characters.
Example: char letter = 'A'
Q2) Explain Character String types
A2) In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example:
is same as:
Java String class provides a lot of methods to perform operations on strings such as compare (), concat (), equals (), split (), length (), replace (), compareTo (), intern (), substring () etc.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in java by using these three classes.
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.
We will discuss immutable string later. Let's first understand what is String in Java and how to create the String object.
What is String in java
Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.
How to create a string object?
There are two ways to create String object:
1) String Literal
Java String literal is created by using double quotes. For Example:
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
In the above example, only one object will be created. Firstly, JVM will not find any string object with the value "Welcome" in string constant pool, that is why it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create a new object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).
2) By new keyword
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).
Java String Example
Q3) What are the Java String class methods?
A3) The java.lang.String class provides many useful methods to perform operations on sequence of char values.
No. | Method | Description |
1 | char charAt(int index) | returns char value for the particular index |
2 | int length() | returns string length |
3 | static String format(String format, Object... args) | returns a formatted string. |
4 | static String format(Locale l, String format, Object... args) | returns formatted string with given locale. |
5 | String substring(int beginIndex) | returns substring for given begin index. |
6 | String substring(int beginIndex, int endIndex) | returns substring for given begin index and end index. |
7 | boolean contains(CharSequence s) | returns true or false after matching the sequence of char value. |
8 | static String join(CharSequence delimiter, CharSequence... elements) | returns a joined string. |
9 | static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) | returns a joined string. |
10 | boolean equals(Object another) | checks the equality of string with the given object. |
11 | boolean isEmpty() | checks if string is empty. |
12 | String concat(String str) | concatenates the specified string. |
13 | String replace(char old, char new) | replaces all occurrences of the specified char value. |
14 | String replace(CharSequence old, CharSequence new) | replaces all occurrences of the specified CharSequence. |
15 | static String equalsIgnoreCase(String another) | compares another string. It doesn't check case. |
16 | String[] split(String regex) | returns a split string matching regex. |
17 | String[] split(String regex, int limit) | returns a split string matching regex and limit. |
18 | String intern() | returns an interned string. |
19 | int indexOf(int ch) | returns the specified char value index. |
20 | int indexOf(int ch, int fromIndex) | returns the specified char value index starting with given index. |
21 | int indexOf(String substring) | returns the specified substring index. |
22 | int indexOf(String substring, int fromIndex) | returns the specified substring index starting with given index. |
23 | String toLowerCase() | returns a string in lowercase. |
24 | String toLowerCase(Locale l) | returns a string in lowercase using specified locale. |
25 | String toUpperCase() | returns a string in uppercase. |
26 | String toUpperCase(Locale l) | returns a string in uppercase using specified locale. |
27 | String trim() | removes beginning and ending spaces of this string. |
28 | static String valueOf(int value) | converts given type into string. It is an overloaded method. |
Q4) Define User Defined Ordinal Types
A4) User-Defined Ordinal Types
An ordinal type is one in which the range of possible values can be easily associated with a set of positive integers. In pascal the builtin ordinal types are integers, char, Boolean. User can define two types of ordinal types: enumeration and subrange.
a) Enumeration types
An enumeration type is one in which the user enumerates all of the possible values, which are symbolic constants. In Ada a typical enumeration type is shown as: type DAYS is (M, T, W, R, F, Sa, S);
b) Subrange types
A subrange type is an ordered contiguous subsequence of an ordinal type. These types were introduced by Pascal. For example: 12 . . . 16 is a subrange of the integer type.
Q5) Explain array in java
A5) Java array is an object which contains elements of a similar data type. Additionally, the elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the size of operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java. Like C/C++, we can also create single dimensional or multidimensional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
Disadvantages
3. Explain Declaration, Instantiation and Initialization of Java Array, For-each Loop for Java Array, Passing Array to a Method in Java, Anonymous Array in Java, Returning Array from the Method
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
Let's see the simple example to print this array.
Output:
33
3
4
5
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop.
The syntax of the for-each loop is given below:
Let us see the example of print the elements of Java array using the for-each loop.
Output:
33
3
4
5
Passing Array to a Method in Java
We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get the minimum number of an array using a method.
Output:
3
Anonymous Array in Java
Java supports the feature of an anonymous array, so you don't need to declare the array while passing an array to the method.
Output:
10
22
44
66
Returning Array from the Method
We can also return an array from the method in Java.
Output:
10
30
50
90
60
Q7) What is the class name of Java array?
A7) In Java, an array is an object. For array object, a proxy class is created whose name can be obtained by getClass().getName() method on the object.
Output:I
Copying a Java Array
We can copy an array to another by the arraycopy() method of System class.
Syntax of arraycopy method
Example of Copying an Array in Java
Output:
caffein
Cloning an Array in Java
Since, Java array implements the Cloneable interface, we can create the clone of the Java array. If we create the clone of a single-dimensional array, it creates the deep copy of the Java array. It means, it will copy the actual value. But, if we create the clone of a multidimensional array, it creates the shallow copy of the Java array which means it copies the references.
Output:
Printing original array:
33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
false
Q8) Write a programAddition of 2 Matrices in Java
A8) Let's see a simple example that adds two matrices.
Output:
2 6 8
6 8 10
Q9) Explain Associative Arrays
A9) Associative arrays are used to represent collections of data elements that can be retrieved by specifying a name called a key. D associative array keys are formed by a list of scalar expression values called a tuple. You can think of the array tuple itself as an imaginary parameter list to a function that is called to retrieve the corresponding array value when you reference the array. Each D associative array has a fixed key signature consisting of a fixed number of tuple elements where each element has a given, fixed type. You can define different key signatures for each array in your D program.
Associative arrays differ from normal, fixed-size arrays in that they have no predefined limit on the number of elements, the elements can be indexed by any tuple as opposed to just using integers as keys, and the elements are not stored in reallocated consecutive storage locations. Associative arrays are useful in situations where you would use a hash table or other simple dictionary data structure in a C, C++, or JavaTM language program. Associative arrays give you the ability to create a dynamic history of events and state captured in your D program that you can use to create more complex control flows.
To define an associative array, you write an assignment expression of the form:
name[key] =expression;
where name is any valid D identifier and key is a comma-separated list of one or more expressions. For example, the following statement defines an associative array a with key signature [ int, string] and stores the integer value 456 in a location named by the tuple [ 123, "hello”]:
a [123, "hello"] = 456;
The type of each object contained in the array is also fixed for all elements in a given array. Because a was first assigned using the integer 456, every subsequent value stored in the array will also be of type int. You can use any of the assignment operators defined in Chapter 2 to modify associative array elements, subject to the operand rules defined for each operator. The D compiler will produce an appropriate error message if you attempt an incompatible assignment. You can use any type with an associative array key or value that you can use with a scalar variable. You cannot nest an associative array within another associative array as a key or value.
You can reference an associative array using any tuple that is compatible with the array key signature. The rules for tuple compatibility are similar to those for function calls and variable assignments: the tuple must be of the same length and each type in the list of actual parameters must be compatible with the corresponding type in the formal key signature. For example, if an associative array x is defined as follows:
x[123ull] = 0;
then the key signature is of type unsigned long long and the values are of type int. This array can also be referenced using the expression x['a'] because the tuple consisting of the character constant 'a' of type int and length one is compatible with the key signature unsigned long long according to the arithmetic conversion rules described in Type Conversions.
If you need to explicitly declare a D associative array before using it, you can create a declaration of the array name and key signature outside of the probe clauses in your program source code:
int x[unsigned long long, char];
BEGIN
{
x[123ull, 'a'] = 456;
}
Once an associative array is defined, references to any tuple of a compatible key signature are permitted, even if the tuple in question has not been previously assigned. Accessing an unassigned associative array element is defined to return a zero-filled object. A consequence of this definition is that underlying storage is not allocated for an associative array element until a non-zero value is assigned to that element. Conversely, assigning an associative array element to zero causes DTrace to deallocate the underlying storage. This behaviour is important because the dynamic variable space out of which associative array elements are allocated is finite; if it is exhausted when an allocation is attempted, the allocation will fail and an error message will be generated indicating a dynamic variable drop. Always assign zero to associative array elements that are no longer in use.
Q10) Explain Expression and Assignment Statements: Arithmetic expression
A10) Java Variables are used to store data. Variables have type, name, and value. Variable names begin with a character, such as x, D, Y, z. Other examples are xy1, abc2, Count, N, sum, Sum, product etc. These are all variable names.
Different variable types are int, char, double. A variable type tells you what kind of data can be stored in that variable.
The syntax of assignment statements is easy. Assignment statements look like this:
variableName = expression;
For example:
int x; // This means variable x can store numbers such as 2, 10, -5.
char y; // This means variable y can store single characters 'a', 'A'.
double z; // This means variable z can store real numbers such as
10.45, 3.13411.
The above are declarations for variables x, y and z.
Important points:
1. Note that a variable has to be declared before being used.
2. The values assigned to a variable correspond to its type. Statements below represent assignment of values to a variable.
x = 100; // x is an integer variable.
y = 'A'; // y is a character variable.
abc = 10.45; // abc is of type double (real numbers).
3. Both variable declaration and assignment of values can be done in same statement. For example,
int x;
x = 100; is same as int x = 100;
4. A variable is declared only once.
int x; // Declaration for x.
x = 100; // Initialization.
x = x + 12; // Using x in an assignment statement.
Often in a program you want to give a variable, a constant value. This can be done:
class ConstDemo
{
public static void main (String [] arg)
{
final double PI = 3.14;
final double CONSTANT2 = 100;
. . . . . .
}
}
The reserved word final tells the compiler that the value will not change. The names of constants follow the same rules as the names for variables. (Programmers sometimes use all capital letters for constants; but that is a matter of personal style, not part of the language.)
2. Arithmetic Expressions
--------------------------
An assignment statement or expression changes the value that is held in a variable. Here is a program that uses an assignment statement:
class example
{
public static void main (String [] args)
{
long x; //a declaration without an initial value
x = 123; //an assignment statement
System.out.println("The variable x contains: " + x );
}
}
Java Arithmetic expressions use arithmetic operators such as +, -, /, *, and %. The % operator is the remainder or modulo operator. Arithmetic expressions are used to assign arithmetic values to variables. An expression is a combination of literals, operators, variables, and parentheses used to calculate a value.
The following code describes the use of different arithmetic expressions.
int x, y, z; // Three integer variables declared at the same time.
x = 10;
y = 12;
z = y / x; // z is assigned the value of y divided by x.
// Here z will have value 1.
z = x + y; // z is assigned the value of x+y // Here z will have value 22.
z = y % x // z is assigned the value of remainder when y // is divided by x. Here z will have value 2.
Java Boolean expressions are expressions which are either true or false. The different Boolean operators are < (less than), > (greater than),
== (equal to), >= (greater or equal to), <= (less or equal), != (not equal to).
Example:
int x = 10;
int y = 4;
int z = 5;
(x < 10) // This expression checks if x is less than 10.
(y > 1) // This expression checks if y is greater than 1.
((x - y) == (z + 1)); // This expression checks
// if (x - y) equals (z + 1).
A Boolean expression can also be a combination of other Boolean expressions. Two or more Boolean expressions can be connected using &&
(logical AND) and || (logical OR) operators.
The && operator represents logical AND. The expression is true only if both Boolean expressions are true. The || operator represents logical
OR. This expression would be true if any one of the associated expressions is true.
Example:
int x = 10; int y = 4; int z = 5;
(x <= 10) && (y > 1) // This expression checks if x is less
// than 10 AND y is greater than 1.
// This expression is TRUE.
(x*y == 41) || (z == 5) // This expression checks if x*y is equal
// to 40 OR if z is equal to 5.
// This expression is FALSE