16

Java Fundamentals and Control Loops

LEARNING OBJECTIVES

At the end of this chapter, you should be able to

  • Write Java programs with good grasp and understanding of fundamentals.

  • Understand data types and their usage.

  • Use compound statements and increment and decrement operators.

  • Understand operators and their precedence and association rules.

  • Use relational and equality operators.

  • Understand and use control loops.

16.1 Introduction

In this chapter, we introduce you to Java programming fundamentals like the data types permitted by Java language, together with various operators like logical operators, arithmetic operators, etc. In Chapter 15, you have of course used some of these features, but in this chapter we will provide you with underlying syntax, grammar and theory of the Java language. We have shown working of various types of operators such as binary operators and unary operators and bit-wise operators with sample programs. The precedence and association of operators are presented.

There are basically two types of statements, viz., sequential and control statements. Control statements alter the sequence of execution of statements. Repetitive execution of a block of statements is controlled by counter controlled types of statements executed by commands like for, while, do-while and switch statements.

16.2 Constants/Literal Constants

They do not change their value during running of the program. Note that constants are also called literal constants and are presented in Figure 16.1.

 

Java literal constants

 

Figure 16.1 Java literal constants

16.2.1 Integer Constants

They can be subdivided into

  1. Decimal integer constants: 0 10 −745 999

    Example: int myAge=56; // 56 is in decimal

  2. Octal integer constants: Only digits between 0 and 7 are allowed. All octal numbers must start with 0 digit to identify as octal number.

    Allowed octal constants: 0777, 001, 0116, 07565L (octal long)

    Illegal octal constants are: 089 − 8 is illegal, 777 − does not start with 0

    : -0675.76 − . is illegal

    Example: int myAgeOctal=070; // 70 is octal equivalent of 56

  3. Hexadecimal constants: A hexadecimal number must start with 0x or 0X followed by digits 0 to 9 or alphabets a to f, both uppercase or lowercase allowed.

    Allowed hexadecimal constants are: 0xffff, 0xa11f, 0x65000UL

    Illegal hexadecimal constants are: 0x14.55, illegal character “.”

    Example: int myAgeHexa=0x38; // 38 is Hexa equivalent of 56

16.2.2 Floating Point Constants/Real Constants

They are base – 10 number that can be represented either in exponent form or decimal point representation.

Valid floating point constants are: 0.01, 789.89765, 5E-5, 1.768E+9

Invalid floating point declarations are:

6 invalid . must contain exponent or float point.

5E+12.5 Invalid as exponent cannot be float.

6,789.00 Invalid character “,”

Example: float area = 567.89; // float value

double area2 = 567.89; //double value

double area3 = 5.6789e2 ; // scientific notation

16.2.3 Character Constants

Character constants can be declared based on the character set followed in a computer. ANSI have standardized these values as shown below.

 

image

 

In addition, Java allows Unicode characters like ISO Latin for example: u0042,u0043 etc. for Latin character set a, b, etc. A character constant contains a single character enclosed within a pair of single quote marks. Examples of character constants are: ‘5’ ‘X’ ‘;’ ‘ ‘

Note that the character constant ‘5’ is not the same as the number 5. The last constant is a blank space. Character constants have integer values known as ASCII values. Special characters that cannot be printed normally, double quote (“), apostrophe (‘), question mark (?) and backslash () can be represented by using escape sequences. An escape sequence always starts with followed by special character stated above.

16.2.4 String Constants

String constants can contain any number of characters in sequence but enclosed in double quotation marks.

  “new delhi” , “14 Nov 1954” , an empty string is “”.

Please note that NULL character indicates NULL character and is used by Java language to indicate the end of a string.

16.2.5 Backlash Character Strings

A few of the backlash character constants that are supported by Java and extensively used in output programming are shown in Table 16.1.

 

Table 16.1 Precedence and association rules for the operators

Special Character Escape Sequence
Bell a
Back space 
Horizontal tab
Vertical tab v
Form feed f
New line
Carriage return
Double Quote
Apostrophe/Single quote
Backslash \
Null
Octal number On
Hexadecimal number cHn

16.2.6 Boolean Literals

Boolean data type represents either true or false. For example: boolean flag = true; boolean ready = false. Note that we cannot use 1 or 0 to represent true or false as done in C++. Further, observe that true and false are NOT enclosed in quotes.

16.2.7 Symbolic Constants

Many a times, we need to use symbolic constants such as PI, to represent 3.141519 that remains constant through out the program. A symbolic name substitutes a sequence of characters or a numerical value that follows it. Symbolic names are written in capital letters as a convention. We use declaration final and its syntax and examples are shown below:

final data_type symbolic_name = value ;
final double PI = 3.14159; final int MAX = 50;

16.3 Variables and Assignment of Values to Variables

A variable can consist of alphabets and digits. Either upper- or lowercase or mixtures of both cases are allowed. A variable cannot start with a digit. It can start with an _. The allowable characters in Java language are alphabets A to Z, a to z, numbers 0 to 9. Examples of valid variables are:

int x;    char a,b,c;    byte b;    double pi;

Once variables are declared, they need to be assigned values prior to using them. This can be achieved by

  • Assigning values to variables. We can assign the values at the time of declaration of variables or just before they are used. Examples are:
    int count = 100;
    byte m = n= k= 75;
    double x=3.14159;
    int x , y=10; // initializes y to 10
  • Read statement: We can obtain the values interactively from the user from key board using readLine() command. In the example that follows, we show how to take input from keyboard in detail in Chapter 17.

16.4 Data Types

Data types define the range of permitted values and operations that can be performed on the data type. Data types, also called intrinsic data types or primitive data types, supported by Java language is given in Figure 16.2. The ranges allowed for a 32-bit IBM PC and memory requirements are highlighted in Table 16.2.

 

Data types in Java

 

Figure 16.2 Data types in Java

 

Table 16.2 Integer data types and their permissible ranges

 

image

 

Data types can also be distinguished as

  • Intrinsic or basic data types like int, char, float, double, etc. Intrinsic or basic data types are those that do not contain any other data types.
  • Derived data types classes, arrays, interfaces, etc.

16.4.1 Integer Data Types

Java supports four integer data types. The permissible ranges are defined in Table 16.2. Note that it is better to use integer data types as per requirement of storage space rather than routinely declaring the data type as int. Since int takes 4 bytes, it takes longer processing time than byte which is only 1 byte. Also note that Java does not support unsigned data types. All data types are signed, i.e. positive or negative. Long integer constant can be specified by appending the letter l s at the end . For example, 789654234L or 7896s

16.4.2 Floating Point Data Types

Float data types are used to represent fractional part of data such as 2.434. There are two types of floating point numbers viz., single precision and double precision. Float data types and their ranges are presented in Table 16.3. By default Java treats float data type with double precision numbers and to get float, we must either type cast or attach ‘f’ or ‘F’ to denote single precision. For example, 1.4397f or 1.4397e4F. Double precision numbers are used when we need higher precision. In Java all mathematical calculations are carried out in double precision only.

 

Table 16.3 Floating point data types and their permissible ranges

Floating point data types and their permissible ranges

16.4.3 Character Type

Java supports char data type and it takes 2 bytes but it can store only single characters. Two bytes are allocated because Java has to cater for larger number of characters in Unicode.

16.4.4 Boolean Data Type

Boolean data type uses only a single bit of storage. It is used to demote true or false condition. The true and false cannot be put in single or double quotes and neither can they be used as identifiers.

 

Example 16.1: FindMaxDemo.java To Find Program to Find Max of Three Numbers

//FindMaxDemo.java
1. package com.oops.chap16;
2. import java.io.*;
3. class FindMax{
4. public int Max3Numbers(int a ,int b, int c){
5. int max=a;
6. if ( max<b) max = b;
7. else if ( max<c) max=c;
8. return max;}
9. }//end of Findmax
10. public class FindMaxDemo{
11. public static void main(String[] args) {
12. // create an object of FindMax
13. FindMax obj=new FindMax();
14. int num1=0;int num2=0;int num3=0;int max=0;
15. try{
16. BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
17. System.out.println(“Enter value for number num1:”);
18. num1 = Integer.parseInt(input.readLine());
19. System.out.println(“Enter value for number num1:”);
20. num2 = Integer.parseInt(input.readLine());
21. System.out.println(“Enter value for number num1:”);
22. num3 = Integer.parseInt(input.readLine());
23. }catch(Exception e){}
24. //get data for 3 numbers. Call GetNumbers() ofFindmax
25. max=obj.Max3Numbers(num1,num2,num3);
26. System.out.println(“Maximum of three numbers:” + num1+” : “+num2 +” : “+ num3 + “ = “+max);
27. }
28. }// end of class FindMaxDemo
Output: Enter value for number num1: 45
Enter value for number num1: 67
Enter value for number num1: 12
Maximum of three numbers:45 : 67 : 12 = 67
Line No. 3: is package statement: package com.oops.chap16 our class files are stored here.
Line No. 2: imports package java.io.* which is required to handle input and output methods.
Line No. 3: declares a class FindMax. This will be class that will perform our core function of finding out maximum of three numbers.
Line Nos. 4–8: defines a method called Max3Numbers that receive three integers num1, num2, num3 and finds maximum and returns max number at line no 8.
Line No. 10: is our main class, hence it is declared along with public static void main(String[] args) { statement at Line No 11.
Line No. 13: defines an object of class FindMax FindMax obj=new FindMax();
Line No. 14: defines three variables num1, num2, num3 and max and initializes with 0;
Line Nos. 15 & 23: are part of try and catch block, which is used to catch any IO-related errors or exceptions. Note that at line no 15 we have included try block because at line no 16, we are reading BufferedReader input from keyboard.
Line No. 16: BufferedReader input = new BufferedReader (new InputStreamReader(System.in)); It shows that System.in is keyboard , standard input device. This has been attached to InputStreamReader and read into system by BufferedReader object.
Line No. 18: num1 = Integer.parseInt(input.readLine()); This is how we will read data from keyboard.

You will see more about input statements and classes in succeeding chapters. For now, get used to our modus operandi of solving problems with objects.

16.5 Scope and Life Time of Variables

The class variables and instance variables, i.e. objects of a class, are declared inside a class. Class declaration is enclosed in a set of brace brackets { }. Variables belong to all the instances of the class, the instances are particular to the object being created. We define two characteristics for variables viz. scope and life.

Java is a block-oriented language. Block can be defined as a set of statements enclosed in a pair of controlling brace brackets. Scope is defined as availability across methods function and program segments. Life is defined as life of controlling brace brackets. It also means life of variables extends up to controlling block of statement. Hence these variables are also called local variables, i.e. local to block.

The scope of the variable is local. This means that a variable declared in a function is accessible only within the function. Further, the life of variables declared within the function is the life of the function itself, i.e. within the brace brackets of the function. Hence these variables are called local variables.

 

Example 16.2: SwapDemo.java A Java Program to Demonstrate Static Variable Usage

//SwapDemo.java to demonstrate local variables
1. package com.oops.chap16;
2. class Swap{
3. public void SwapVars(int x , int y){
4. int temp;
5. temp=x;x=y;y=temp;
6. System.out.print(“X&Y vars inside Swap Method after swapping”);
7. System.out.println(“ X = “ +x + “ Y = “ + y);}
8. }
9. class SwapDemo {
10. public static void main(String[] args) {
11. int x=10; int y=100;
12. System.out.print(“X&Y variables before calling Swap Method”);
13. System.out.println(“ X = “ +x + “ Y = “ + y);
14. //create an object
15. Swap obj=new Swap();
16. obj.SwapVars(x, y);
17. System.out.print(“X&Y variables after return from Swap Method”);
18. System.out.println(“ X = “ +x + “ Y = “ + y);
19. }
20. }// end of SwapDemo
Output: X&Y variables before calling Swap Method X = 10 Y = 100
X&Y variables inside Swap Method after swapping X = 100 Y = 10
X&Y variables after return from Swap Method X = 10 Y = 100
Line No. 9: declares a class SwapDemo. In line No 11, we have declared two variables x and y to hold values 10 and 100, respectively.
Line No. 15: an object is created for class Swap.
Line No. 16: calls a method SwapVars( x, y) a method belonging to Swap class. Variables x and y are passed by call by value method. In this method, x and y are copied to stack area belonging to SwapVars() stack area.
Line Nos. 3 to 9: define a method SwapVars(int x, int y)
Line No. 4: declares a local variable called temp. Even x and y which are copied by calling method main() into SwapVars() area are local variables.
Line No. 5: swaps the values of variable x and y using a third variable temp;
Line Nos. 6 & 7: display changed variable x and y as 100 and 10 inside SwapVars() method as expected.
Line Nos. 16 & 18: in main() method displays x and y after return from SwapVars() method and the result is that variables have not been swapped, with x and y showing originally assigned values 10 and 100. So what has gone wrong? Nothing. This is what call by value and local variables are expected to do. The change made in SwapVars() method on local variable, in this case temp x and y, are not reflected to calling method main(). Why? Because they belong to different areas of the stack.

Swapping variables without using a third variable: In the method SwapVars() of Example 16.2, we have used a third variable called temp to swap the variable. Can we achieve the same result without using the third variable? Refer to the code segment shown below:

1. public void SwapVars(int x , int y){ // suppose x=10 & y=100
2. x=x+y; // x now becomes 110
3. y=x-y; // y now becomes 110-100 =10
4. x=x-y; // y now becomes 110-10 = 100
5. System.out.print(“X&Y vars inside Swap Method after swapping”);
6. System.out.println(“ X = “ +x + “ Y = “ + y);}
7. }

This code is more efficient as we have not used a third variable.

16.6 Arithmetic Operators

The basic (also known as intrinsic) operators are

 + addition - subtraction * multiplication
 / division % modulus (remainder after division)

These operators are called binary operators because they operate on two operands. For example, a + b involves a binary operator + and two operands a and b. In Java, division implies integer division. For example, 5/4 would result 1. The % operator also called modulus operator would give remainder as result. For example, 20%4 would result in 0 and 21%4 would result in 5.

16.7 Type Conversion and Type Casting

16.7.1 Type Conversion

If the variables involved in an operation are of different types, then Java carries out type conversion automatically before the operation. If the operation is between a float and double, the float will be converted to double and the result will result in double. We can say either widening or narrowing takes place in type conversion. The process of conversion to a larger data type from a smaller data type is called widening and conversion from larger to smaller data type is called narrowing. Note that narrowing will cause truncation of data. If an expression holds byte, short or int, then the result is widened to int. Similarly for floating point, Java automatically converts to double and finally the result is shown as per the largest data type in the expression or as desired by the user through type casting, which is explained in the next section.

16.7.2 Type Cast

Suppose that we want to declare the result in particular data type, we can type cast as shown below. Casting is often used when a method returns a different data type.

The syntax is as follows:

 type var1 = ( type casted) var2;
 int a , b; float x;
 x=(float)a/b; // a/b is integer division and the result is converted to float.

 

Example 16.3: QuadraticDemo.java To Find the Toots of Quadratic Equation

//QuadraticDemo.java

1. package com.oops.chap16;
2. import java.io.*;
3. class Quadratic{
4. public void FindRoots(int a ,int b, int c){
5. int d;
6. float root1,root2;
7. System.out.println(“The Equation is “);
8. System.out.println( a + “X^2” + “+” + b+ “*”+ “X”+”+”+c);
9. d = ((b*b)-(4*a*c));
10. if (d<0)
11. { System.out.println( “No real solution since d<0”);
12. System.out.println( “roots are imaginary
”);
13. double sqrd= (double)Math.sqrt(-d/(2*a));
14. double real = (double)(-b)/(double)(2*a);
15. System.out.println( “root1 : “+ real + “+ i “+ (float)(sqrd));
16. System.out.println( “root1 : “+ real + “- i “+ (float)(sqrd));
17. }
18. if(d==0)
19. { System.out.println( “roots are real
”);
20. System.out.println( “root1&2 are equal “+ (float)-b/(2*a));
21. }
22. else
23. if ( d>0)
24. { double sqrd = Math.sqrt(d);
25. System.out.println( “root1 : “+ (float)(-b + sqrd)/(2*a));
26. System.out.println( “root2 : “+ (float)(-b - sqrd)/(2*a));
27. }
28. }//end of FindRoots
29. }//end of Quadratic
30. public class QuadraticDemo{
31. public static void main(String[] args) {
32. // create an object of Quadratic
33. Quadratic obj=new Quadratic();
34. int num1=0 ;int num2=0; int num3=0;
35. try{
36. BufferedReader input = newBufferedReader (new InputStreamReader (System.in));
37. System.out.println(“Enter Non-zero Integer value for number num1:”);
38. num1 = Integer.parseInt(input.readLine());
39. System.out.println(“Enter Non-Zero Integer value for numbernum1:”);
40. num2 = Integer.parseInt(input.readLine());
41. System.out.println(“Enter Non-Zero Integer value for number num1:”);
42. num3 = Integer.parseInt(input.readLine());
43. }catch(Exception e){}
44. // Call FindRoots of Quadratic
45. obj.FindRoots(num1,num2,num3);
46. System.out.println(“End of Programme …”);
47. }
48. }// end of class QuadratciDemo
Output: Enter Non-Zero Integer value for number num1:3
Enter Non-Zero Integer value for numbernum1:2
Enter Non-Zero Integer value for number num1:-5
The Equation is :3X^2+2X+-5
root1 : 1.0
root2 : -1.6666666
End of Programme …
Enter Non-Zero Integer value for number num1:2
Enter Non-Zero Integer value for numbernum1:3
Enter Non-Zero Integer value for number num1:4
The Equation is 2X^2+3X+4
No real solution since d<0
roots are imaginary
root1 : -0.75+ i 2.236068
root1 : -0.75- i 2.236068
End of Programme …
Line No. 3: declares a class Quadratic, which in turn defines a public method called FindRoots that receives three integer arguments a,b,c.
Line No. 9: calculates the value of d given by b*2 – 4 * a * c;
Line Nos. 10–16: deal for d <0 in which case the roots are imaginary and takes the form -b/2a + i (d/2a). We had resorted to type casting to float or double as a,b,c are integers. The type casting is shown in line No 9: double real = (double)(-b)/(double)(2*a);
Line Nos. 18–21: deal with a case for d = 0 and roots are equal: (float)-b/(2*a))
Line Nos. 22–27: deal with a case for d > 0 and roots are given by: root1 :+ (float)(-b + sqrd)/(2*a))and root2 :(float)(-b - sqrd)/(2*a));
Line No. 30: declares main public class QuadraticDemo and at Line No 33 creates an object for class quadratic.
Line Nos. 37 to 43: obtain values for three coefficients num1, num2, num3 form keyboard. Notice that we have used try and catch blocks for detecting any errors while reading input from keyboard using System.in and BufferedReeader object.

16.8 Unary Operators

In unary operators, operator precedes a single operand. Unary operators are: unary minus (- ), Increment and decrement operators : ++ , -- . . Examples are : - 4.0 , -5*(A+B)

      ++ i , i++ , --i , i−

Minus operator is both a unary and a binary operator. Unary minus, for example -5.0 operates on variable on its right, while the binary operator has variables on both sides of operator and it is an arithmetic operator.

16.8.1 Increment and Decrement Operators

If they precede the operand, the variable is incremented at first and then the operation is performed. If they follow the operand, then the operation is performed first and then the variable is incremented.

 

Example 16.4: IncrDecr.java To Demonstrate Pre- and Post-increment Operators

//16.4 IncrDecr.java to demonstrate pre & Post Increment operators
package com.oops.chap16;
public class IncrDecr {
  public static void main(String[] args) {
  int count = 1;
  System.out.println(“Count = “ + count); // out put will be 1
  /* count will be incremented by one and then operation of
  print is performed . Output will be 2*/
  System.out.println(“Count Pre Incr = “ + (++count));
  /* Now , if you use count will be printed first. Output is 2.
  Then count will be incremented by 1 to 3.*/
  System.out.println(“Count Post Incr; but increment will be after statement = “ + (count++));
  System.out.println(“Count Post Incr after executing post incr = “ + (count));
 }
 }
Output: Count = 1
Count Pre Incr = 2
Count Post Incr; but increment will be after statement = 2
Count Post Incr after executing post incr = 3

16.8.2 Assignment Operator

The assignment operator is =. This is also called equality operator. For example, int x= 45; creates a variable of data type int and assigns a value 45 to it.

There is a compound assignment operator wherein two operators are combined into one statement. For example, x+=10; means x=x+10.

16.8.3 Chained Assignment

The assignment operator together with compound assignment operators can be used in chained assignment statement. For example: int x = y = z = 0; this statement is equivalent to statement x= ( y = ( z = 0)).

Note that assignment always takes place from right to left. The first assignment is z = 0; its reference is passed to y, so that y is also equated to 0, and then lastly x = 0.

16.8.4 Relational Operators

The relational operators are : > >= < and <=.

These four relational operators have the same precedence. However, they have lower priority than arithmetic operators. The two more operators, known as equality operators = = and ! =, have priority just below relational operators.

16.9 Logical Operators

These are && and || and NOT operators (!). Evaluation of expressions connected by logical operators are done from left to right and evaluation stops when either truth or falsehood is established. In the statement shown below:

                    if ( (iflag==0) && ( youflag= 0) )

first iflag == 0 is evaluated, if it is true, then only the second expression (youflag= 0) is evaluated. In other words, evaluation stops as soon as truth or falsehood is established.

We will show the use of logical operators with an example. If attendance is > 75 and sessionals > =50, then set eligible to true, else set it to false. Depending on the eligibility issue, admit card for end term examinations.

 

Example 16.5: LogicalOpDemo.java To Show the Usage of Logical Operators Not

//LogicalDemo.java
1. package com.oops.chap16;
2. import java.io.*;
3. class Logical{
4. public boolean Eligibility(int marks, int att){
5. boolean yesno=true;
6. if ( (marks>50)&& (att>=75) ) yesno=true;
7. else yesno=false;
8. return yesno;
9. }//end of FindReverse
10. }//end of Reverse class
11. public class LogicalDemo{
12. public static void main(String[] args) {
13. //create an object of Logical
14. Logical obj=new Logical();
15. int marks=0;int attendance=0;String name=””;boolean yesno;
16. try{
17. BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
18. System.out.println(“Enter Name of Student”);
19. name=input.readLine();
20. System.out.println(“Enter marks “);
21. marks = Integer.parseInt(input.readLine());
22. System.out.println(“Enter Attendance “);
23. attendance = Integer.parseInt(input.readLine());
24. }catch(Exception e){}
25. //Call Eligibility() of class Logical
26. yesno=obj.Eligibility(marks,attendance);
27. System.out.println(“Name :” + name );
28. System.out.println(“Marks : Attendance : “ + marks + “ : “+ attendance);
29. System.out.println(“eligibility:” + yesno );
30. if( yesno==true)
31. System.out.println(“ Collect Admit Card”);
32. else System.out.println(“Sorry. falling short of academic or Attendance Standard”);
33. }
34. }// end of class LogicalDemo
Output:
Enter Name of Student Suresh Enter marks 65 Enter Attendance 66
Name: Suresh Marks : Attendance : 65 : 66 eligibility:false
Sorry. falling short of academic or Attendance Standard
2 run: Enter Name of Student Gautam Enter marks 98 Enter Attendance89
Name: Gautam Marks : Attendance : 98 : 89eligibility:true
Collect Admit Card
Line No. 6: If(( marks>=50) && (att >=75)) is a statement that contains logical and &&. First the left-hand side (LHS) of &&, i.e. expression (marks>=50), is evaluated. Only if it is true, the right-hand side (RHS) of && expression (att >=75) is evaluated. Only if both are true, only yesno is set to true. Else it is set to false.

Observe that && is utilizing the system very efficiently since it evaluates the RHS if and only if the LHS is true.

16.10 Bit-wise Operators

There are seven bit-wise operators available in Java language. They are:

& Bit-wise AND. Used for masking operation. For example, if you want to mask the first four bits of a number ‘n’, then we will mask n with a number whose last four bits are 1s, i.e. 0001111. In Octal representation, it is 016. (Remember that an octal number starts with 0 and a hexa number starts with 0x.)

          n = 1 0 0 1 0 1 0 1 = 149(decimal)
          & 0 0 0 0 1 1 1 1 = 016(octal)
      result n = 0 0 0 0 0 1 1 1

Note that the last four bits are 0101 and are unaffected, i.e. they are just reproduced in the result, whereas the left four bits are all 0s, i.e. they are masked.

| Bit-wise OR. This operator is used when you want to set a bit. For example, if we want to set 0th and 2nd bit to 1 for n = 144, then we will use | operator with n, as shown below:

          n = 1 0 0 1 0 0 0 0 = 144(decimal)
          | = 0 0 0 0 0 1 0 1 = 005(octal)
   result n = 1 0 0 1 0 1 0 1 = 149(decimal)

^ Bit-wise Exclusive OR. Exclusive OR, also known as odd function, produces output 1 when both bits are not the same (odd) and produces a 0 when both bits are the same.

          n = 1 0 0 1 0 1 0 1 = 149(decimal)
          ^ = 0 0 0 0 0 1 0 1 = 005(octal)
   result n = 1 0 0 1 0 0 0 0 = 149(decimal)

<< Left Shift. Shifting left by one position, bits of a binary number is equal to multiplying the number with 2.

          n = 1 0 0 1 0 0 0 0 = 144(decimal)
       n<<1 1 0 0 1 0 0 0 0 0 = 288(decimal)
    n<<2 1 0 0 1 0 0 0 0 0 0 = 576

>> Right Shift. Shifting right by one position, bits of a binary number is equal to division of the given number with 2.

          n = 1 0 0 1 0 0 0 0 = 144(decimal)
          n>> 0 1 0 0 1 0 0 0 = 72(decimal)
      n>>2 0 0 1 0 0 1 0 0 = 36(decimal)

>>> Bit-wise zero Fill Shift Operator. This operator shifts right by specified positions but fill the shifted slots with zeros. For example, ( n>>>3) would result in

          n = 1 0 0 1 0 1 0 1 = 149(decimal)
          n>>>3 n = 0 0 0 1 0 0 1 0 = 18(decimal)

~ Tilde operator. one's complement Operator. This is a unary operator used to find one's complement of a given number.

          n = 1 0 0 1 0 1 0 1 = 149(decimal)
          ~n = 0 1 1 0 1 0 1 0 = bit-wise complement

 

Example 16.6: Bit-wise.java To Find Whether a Given Number is Prime or Not

//BitWise.java to show the concepts of bit wise operators of java;
package com.oops.chap16;
import java.io.*;
public class BitWise {
public static void main(String[] args) {
int n = 149;
int res;
res = n & 0016;
System.out.println(“The resultant of Bit wise AND operator is :”+ res);
res = n | 0016;
System.out.println(“The resultant of Bit wise OR operator is :”+res);
System.out.println(“The resultant of Logical OR operator is :” + res);
res = n ^ 0016;
System.out.println(“The resultant of Exclusive operator is :” + res);
res = n <<2;
System.out.println(“The resultant of shift left ( by 2 bits) operator is :” + res);
res = n >>2;
System.out.println(“The resultant of shift right ( by 2 bits) operator is :” + res);
res = n >>>3;
System.out.println(“The resultant of shift right>>> ( by 3bits) operator is :” + res);
res = ~n;
System.out.println(“The resultant of NOT operator is :” + res);
}
}
OUTPUT :
The resultant of Bit wise AND operator is :5
The resultant of Bit wise OR operator is :159
The resultant of Logical OR operator is :159
The resultant of Exclusive operator is :154
The resultant of shift left ( by 2 bits) operator is :596
The resultant of shift right ( by 2 bits) operator is :37
The resultant of shift right>>> ( by 3bits) operator is :18
The resultant of NOT operator is :-150

16.11 Other Operators

16.11.1 Question Mark (?) Operator Conditional Expressions

Suppose you want to allot 10 additional bonus marks to students who put in 100 percent attendance, and all others additional 2 marks. This would result in statements like

   If ( attendance > 100)
marks += 10;//this is a compound statement. It means Marks=Marks +10
else
   marks +=2;

Java language gives you the facility of conditional operator, using which the above 4 lines can be coded as a single line

    marks = (attendance > 100) ? marks + 10 : marks + 2;

The syntax is : z = exp1 ? expr 2 : exp3. Exp1 is evaluated first. If it is true z is equated to the result of exp2 . else z is equated to exp3.

 

Example 16.7: Ternary.java To Find Out Maximum of Two Numbers and Three Numbers

1. package com.oops.chap16;
2. public class Ternary {
3.   public static void main(String[] args) {
4.   byte a=56, b=101, c=45, max;
5.   // find the maximum of a & b
6.   max=(a>b)?a:b;
7.   System.out.println(“maximum of a & b =” + max);
8.   max=( ( a>( max=(b>c)?b:c))?a :max );
9.   System.out.println(“maximum of a & b & c =” + max);
10.  }
11. }
maximum of a & b =101
maximum of a & b & c =101

16.11.2 Member Operator or Dot Operator

It is used to denote a package or a member method or a class. For example, we have shown package as: package com.oops.chap16. We have further used member methods as: obj. FindPrime() etc.

16.11.3 Instanceof Operator

We can use instanceof operator to test if the object belongs to a particular class or not. For example, boolean yesno; yesno = std instanceof Student checks if the object std is an instance of class Student and returns true.

16.11.4 New Operator

It is used to allocate resources when we create objects for classes. New operator allocates resources in heap memory at run-time dynamically. For example:

    Student std = new Student (“Ramesh” , 50595,); will allocate resource to object std on heap memory.

    int[] myArray = new int[]{10,13,18,20}; will create an array called myArray of data type integer on heap memory and initialize the array with values of 10,13,18,20

16.11.5 Operator Precedence and Associativity

Like in mathematics, in Java too the use of parentheses overrides the basic precedence of arithmetic operators. There are two priorities associated with arithmetic operators: Higher Priority : * / and % Lower Priority : + - . Therefore, when an expression does not contain any parentheses, Java runs two passes. In the first pass, the higher priorities are considered and in the second pass, the lower priorities are considered.

 

Example 16.8: Evaluate the Expression : a+b/3*c/2-4 for a=2, b=3, and c=4

The given expression is : a + b / 3 * c / 2 – 4 = 2 + 3/3 * 4 / 2 – 4

First pass: High Priority from left to right Step 1: 2 + 1 * 4/2 -4 ( 3/3 is evaluated)

Step 2: 2 + 4 /2 – 4) (1*4 is evaluated) Step3 : 2+ 2 – 4 ( 4/2 is evaluated)

Second pass low priority from left to right: 2 +2 –4 ( 2+2)

4 – 4 =0 (4 – 4 is evaluated last)

 

Example 16.9: Evaluate the Expression : a+b/(3*c)/(8-4) a for a=2, b=24, c=1

The given expression is : :a + b / (3 * c) / ( 8 – 4 ) . The expressions is parentheses are highest priority . Hence : 2 + 24 / ( 3) / ( 4) Brackets are evaluated first

2 + 8/4 left to right : 2 + 2 = 4

The association refers to the execution of operators by the compiler. It can be from right to left or from left to right. The precedence and association of operators are summarized in Table 16.4. The operators at the top have priority more than those that appear later in the table, i.e. operator priority is highest at the top of the table and lowest at the bottom of the table. Operators on the same line have the same priority.

 

Table 16.4 Precedence and association rules for the operators

Operator Association Priority
Dot operator . Method call ( ) Array ref [ ] Left to right 1
Logical negation (!) , Tilde( ~), Increment ( ++ ) , Decrement (--) + Unary minus ( -) , (type) casting Right to left 2
* / % Left to right 3
+ - Left to right 4
<< >> >>> Left to right 5
< <= > >= instanceof Left to right 6
= = != Left to right 7

& bit wise &

^ bit wise XOR

| bit wise or

&& logical and

|| logical or

Left to right 8

Left to right 9

Left to right 10

Left to right 11

Left to right 12

?: conditional operator

= Assignment operator

Right to left 13

Right to left 14

= += -= *= /= %= ^= != <<= >>= Right to left
, Left to right
  • * / and % have all the same priority
  • Unary operators like + , - , and * have more priorities than binary operators

16.12 Conditional and Branching Statements

Normally the instructions are executed sequentially. But logic demands that the next instruction to be executed need not necessarily be the next in line, but can be branched to any other statement as per logic of the algorithms. These are called branching statements. The branching can either be conditional or unconditional.

Java is a block-oriented language. The program consists of statements. Statements are logically grouped into blocks. Blocks are enclosed in brace brackets. {and} are used to denote start and end of the block in Java. All variables declared inside the controlling braces are called local to the block. It means the value the variable holds is available only inside the block. Statements inside the block are also called compound statements. Note that there will be no semicolon after closing brace brackets. For example, in function definition we have enclosed all the statements in brace brackets.

16.12.1 If and If–Else Statements

Refer to Figures 16.3 and 16.4. Control flow and syntax are shown for if statements and also for if-else statements. Else statement is optional. But if used, it will be associated with the nearest if statement. In the example shown, else is attached to the innermost if.

 

Control flow in If statement

 

Figure 16.3 Control flow in If statement

 

Control flow in If-else statement

 

Figure 16.4 Control flow in If-else statement

 

if ( totalMarks > 60)
if ( total Marks > 70) System.out.println (“passed with distinction”);
else System.out.println (“passed with First class”);

Use of brace brackets dictate the association rule for else statement. Else in the following code is linked up with the immediate if statement above it

if ( totalMarks > 60)
 { if ( total Marks > 70)
 { System.out.println (“passed with distinction”);}
  else // associated with inner if
 { cout<<“passed with first class”<<endl;}
}
 else // associated with outer if
 { …else block………}

 

Example 16.10: IfLoop.java To Test the if Control Loop

//IfLoop.java to test the if loop

1. package com.oops.chap16;
2. public class IfLoop {
3. public static void main(String[] args) {
4. //Declare two arrays to hole marks and attendance of 5 students
5. int[] idNo = new int[]{ 50595, 50596,50597,50598,50599};
6. float[] marks = new float[]{96.0F,65.8F,71.0F,46.0F,33.0F};
7. float[] att = new float[]{78.0F,66.0F,71.0F,75.0F,45.0F};
8. boolean [] yesno = new boolean[5];
9. for ( int i=0; i<5;i++)yesno[i]=false; //initial value for yesno
10. // To be eligible attendance >=60.0 and marks>=50.0
11. for (int i=0; i<5;i++)
12. if ((marks[i]>=50.0)&& (att[i]>=60.0)) yesno[i]=true;
13. System.out.println(“List of eligible candidates”);
14. for (int i=0; i<5; i++)
15. if( yesno[i]== true)
16. System.out.println(“ IdNo : “ + idNo[i] + “ marks :” + marks[i] +” attendance “ + att[i]);
17. }
18. }//end of IfLoop class

Output: List of eligible candidates
IdNo : 50595 marks :96.0 attendance 78.0
IdNo : 50596 marks :65.8 attendance 66.0
IdNo : 50597 marks :71.0 attendance 71.0
Line Nos. 5 to 7: declares three arrays namely idNo[], marks[] and att[] to denote and initializes the values to the array. When the array is large , we can also use for loop to enter the values as we have done at line No 9 for initializing the array yesno[5].
Line No. 12: checks if marks[i] >=50.0 and att[i]>=60.0 by using a logical and && operator and sets corresponding yesno[i] to rue.
Line No. 16: ouputs the list of eligible students if is true.

16.12.2 Nested If Statements

Nested if means if statement within an if statement. The problem in Example 16.8 uses nested if statements to implement simple calculator

 

Example 16.11: CalcIf.java To Simulate Simple Calculator With +,-,*,/ Operators Using Nested Ifs

1. package com.oops.chap16;
2. import java.io.*;
3. public class CalcIf {
4. public static void main(String[] args) throws IOException{
5. float a, b, result=0.0F;
6. int choice;
7. BufferedReader input = new BufferedReader (new InputStream Reader(System.in));
8. System.out.println(“Enter number 1”);
9. a = Float.parseFloat(input.readLine());
10. System.out.println(“Enter number 2”);
11. b = Float.parseFloat(input.readLine());
12. System.out.println(“Enter choice 1 Addition 2: Subtraction 3: Multiplication 4 : Division”);
13. choice=Integer.parseInt(input.readLine());
14. if( choice == 1) result = a+b;
15. else
16. if( choice == 2) result = a-b;
17. else
18. if( choice == 3) result = a*b;
19. else
20. if (choice == 4) result = a/b;
21. else
22. System.out.println(“Wrong Operatot”);
23. System.out.println(“The result : “ +result );
24. }
25. }//end of CalcIf class
Output: Enter number 1 100
Enter number 2 20
Enter choice 1 Addition 2: Subtraction 3: Multiplication 4 : Division 4
The result : 5.0

16.12.3 If–Else–If Ladder

Line Nos. 14 to 21 depict the if–else–if ladder. It is called ladder because it looks like a ladder. Observe the indentation. Its deep indent and costs in terms of space. Hence the if–else–if ladder can be replaced by the if–else–if, as shown below:

if( choice == 1) result = a+b;
else if( choice == 2) result = a-b;
else if( choice == 3) result = a*b;
else if (choice == 4) result = a/b;
else System.out.println(“Wrong Operatot”);
System.out.println(“The result : “ +result );

16.12.4 Switch and Case Statements

The switch statement is similar to the if–else–if ladder we have used in the previous section. The syntax is switch (var) { case value1 : statements1 : break;

case value2 : statements2 : break;
default : statements3; // this statement is optional
}

Note that var has to be integer and value has to be an integer constant. Observe also that case label ends with : To demonstrate the concepts involved we show next Example 16.9.

 

Example 16.12: SwitchCalc.java To Simulate Simple Calculator with +,-,*,/ Operators Using Switch Statement Nested Ifs

package com.oops.chap16;
import java.io.*;
public class SwitchCalc {
public static void main(String[] args) throws IOException {
float a, b, result=0.0F;
int choice;
BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
System.out.println(“Enter number 1”);
a = Float.parseFloat(input.readLine());
System.out.println(“Enter number 2”);
b = Float.parseFloat(input.readLine());
System.out.println(“Enter choice 1 Addition 2: Subtraction 3: Multiplication 4 : Division”);
choice=Integer.parseInt(input.readLine());
switch(choice)
{
case 1: result = a+b;break;
case 2: result = a-b;break;
case 3: result = a*b;break;
case 4: result = a/b;break;
default: System.out.println(“Wrong Operatot”);
}//end of switch
System.out.println(“The result : “ +result );
}
}//end of SwitchCalc class
Output: Enter number 1 100
Enter number 2 200
Enter choice 1 Addition 2: Subtraction 3: Multiplication 4 : Division 4
The result : 0.5

16.13 Control Loops

There will be several occasions when a programmer has to execute a set of instructions repeatedly till a condition is met. In these situations we need control loops. There are several conditions likely while framing these control loops like:

  • Programmer is aware of the initial conditions, loop termination conditions and step increments for testing the conditions. We use for loop for this purpose.
  • When the programmer is not aware if the control loop executes, then he has to check the condition first and then enter control loop. We use while statement for this case.
  • When the programmer wants the control loop to be executed at least once and then check for the condition, we use do while loop.

16.13.1 While Loop

While loop is written by a programmer if he is not sure if the while block will be executed. A condition is checked first. If it is true, the while block is executed. The syntax of while statement is

While (expression) //body of while contains a single line no brace brackets required

 Statement;
 While(expression)
 { statement1;
   statement2;
 }
 while(true) // expression is always true
 { block of statements;
 } // the loop is called forever while loop

Let us do an interesting problem to show the use of control loops. We have a number denoted by 989989. We need sum of digits, i.e. 9+8+9+9+8+9 = 52 and no. of digits =6. The method and program are shown below:

 Step1 Rem = n% 10 :// rem =9
 Step 2 N=n/10 :// n=989989/10 = 98998 ( integer division )
 We will repeat Step 1 & 2 while n>0

 

Example 16.13: Sumdigits.java To Find Program to Find the Sum of Digits in a Number

1. package com.oops.chap16;
2. public class SumDigits {
3. public static void main(String[] args) {
4. int num = 989989,rem,sum=0, count =0,temp;
5. temp=num; // store it in temp
6. while ( num>0)
7. {rem=num%10; // finds remainder
8. num=num/10;
9. count++;//increments counter
10. sum+=rem; //adds remainder to sum

 

Control flow for while and for loops

 

Figure 16.5 Control flow for while and for loops

 

11. }//end of while
12. System.out.println(“Given Number” + temp);
13. System.out.println(“No of digits=” + count);
14. System.out.println(“Sum of digits=” +sum);
15. }
16. }//end of class
Output:Given Number989989
No of digits=6
Sum of digits=52
Line No. 6: shows while loop. The condition n>0 is checked first. Only if it is true , the loop is entered.
Line No. 7: is modulus operator that gives remainder.
Line No. 8: is an integer division. This means that it ignores the remainder

16.13.2 Do-while Loop

The syntax is

 Do
 {
  block of statements
  } while (expression);

Do while loop is most appropriate when we want the control loop to be executed at least once. The block is executed first and the condition is checked. If true, the loop is executed till the condition becomes true. We will use do-while loop when we know that the loop needs to be executed at least once, whereas while loop is used when we are not aware if the loop needs to be executed or not. Control flow is shown in Figure 7.6.

 

Example 16.14: SumDigitsDoWhile.java a Program to find sum of digits and also no of digits using do while

1. package com.oops.chap16;
2. public class SumDigitsDoWhile {
3. public static void main(String[] args) {
4. int num = 989989,rem,sum=0, count =0,temp;
5. temp=num; // store it in temp
6. do
7. {rem=num%10; // finds remainder
8. num=num/10;
9. count++;//increments counter
10. sum+=rem; //adds remainder to sum
11. }while( num>0);
12. System.out.println(“Given Number” + temp);
13. System.out.println(“No of digits=” + count);
14. System.out.println(“Sum of digits=” +sum);
15. }
16. }//end of class
Output: Given Number989989 No of digits=6 Sum of digits=52

16.13.3 For Loop

For loop, as control loop is used, when we know the exact number of times the loop needs to be executed. The syntax of for loop is

for ( exp1 ; exp2 ; exp3)
{ block of statements }
where exp1 is initialization block
   exp2 is condition test block
   exp3 is alter initial value assigned to exp1

Forever or infinite for loop is shown below. Observe that forever for loop has no initial and final conditions. Note that infinite for loops are run forever. We have to forcibly stop the program by <cntrl – break>

for ( ; ; )
{statement;}

for loops can be nested. That means we can write for loop with in a for loop. In nested for loop, the inner loop is executed for each value of outer loop. For example, the inner loop is executed for i = 0 and the value of j is varied from 0 final condition. The outer loop is executed for values of i varying from 0 to n − 1.

 

Control flow for Do-while loop

 

Figure 16.6 Control flow for Do-while loop

 

The syntax is

for ( int i=0;i<n;i++)
{for (int j=0;j<n;j++)
    {statement}
}

 

Example 16.15: Fibonaacifor.java //Program to Find Sum of n Numbers and Their Average Using For Loop

package com.oops.chap16;
public class Fibonaaci{
public static void main(String[] args) {
int [] FibArray = new int [20];
int numOfTerms = 20; //number of terms in the series
FibArray[0]=0; FibArray[1]=1; // first two number of the series
for (int i =2 ; i< numOfTerms; i++)
{ FibArray[i]=FibArray[i-1]+FibArray[i-2];}
System.out.println(“ The fibonaacii series for 20 terms …”);
for (int i =0; i< numOfTerms; i++){
System.out.print(FibArray[i] + “ “);}
}
}//end of class
Output: The fibonaacii series for 20 terms …
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

16.14 Break

Break statement is used to exit from the switch control or control loop. We can use break statement to exit from for, while and do while, and switch control statements. You have already seen use of break statement in Switch statement. When used within a nested block, a break statement can be used to go to the end of the block in which the break is used. There is another use in break statement. For example: break label2; takes you to the end of the block labeled as label2.

 

Example 16.16: BreakUses.java: A Program that Demonstrates Break Statement

1. package com.oops.chap16;
2. import java.io.*;
3. public class BreakUses {
4. public static void main(String[] args) throws IOException {
5. int count=0; int sum=0,num;
6. // write a forever for loop for demonstration of
7. // break for going out of control loop
8. BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
9. for(;;){
10. if ( count ==5)
11. { System.out.println(“upper limit of 5 reached”);
12. break;}
13. else{
14. System.out.println(“enter value of “+(count+1)+ “number”);
15. num = Integer.parseInt(input.readLine());
16. sum+=num; count++;}
17. }// end of for
18. // Second use of break with label
19. label1:{System.out.println(“Entered label1 “);
20. label2:{System.out.println(“Entered label2 “);
21. label3:{System.out.println(“Entered label3 “);
22. System.out.println(“Inside a label3 Using break label2 Statement”);
23. break label2;
24. }//end of label3
25. }//end of label2
26. System.out.println(“reached end of label2 “);
27. }//end of label1*/
28. } //end of main()
29. }//end of class
Output: enter value of 01number10
enter value of 11number20
enter value of 21number30
enter value of 31number40
enter value of 41number50
upper limit of 5 reached
Entered label1
Entered label2
Entered label3
Inside a label3 Using break label2 Statement
reached end of label2
Line No. 9: uses for evr for loop. It can be only stopped by Line No 10 which tests for count == 5
Line No. 11: shows break statement. If count == 5 is true, break statement breaks the for loop. If count is not 5 it enters else loop.
Line Nos. 19 to 27: show the use of break label; statement. Each label represents a block of statement. Line No 23 break label2; takes the control to end of label2.

16.15 Continue Statement

Continue is used when we want to stop further processing of loop statements and start at the beginning of the control loop. In the example shown below, we would like to add 10 points to all odd numbers between 0 and 10 and skip adding to even numbers.

 

Example 16.17: Continue.java : A Program that Demonstrates Continue Statement

1. package com.oops.chap16;
2. import java.io.*;
3. public class Continue {
4. public static void main(String[] args){
5. int count=0;
6. for(count = 0;count<=10;count++){
7. if ( count%2==0){System.out.println(“The number “+count+ “ is even “);
8. continue;} //control goes to begining of for loop
9. System.out.println(“The number “+count+ “ is odd”);
10. }//end of for
11. }// end of main
12. }//end of class
Output:
The number 0 is even The number 1 is odd The number 2 is even
The number 3 is odd The number 4 is even The number 5 is odd
The number 6 is even The number 7 is odd The number 8 is even
The number 9 is odd The number 10 is even
Line No. 7: checks if (count%2 ==0) i.e. if count is even.
Line No. 8: continue statement ensures that if the number is even the control goes to the beginning of the loop and does not enter the balance code at line no 9.

16.16 Summary

  1. Java supports integral, character and Boolean constants. Literal constants are those that do not change their value during the running of the program.
  2. Integral constants are Integer constants, Octal constants and Hexa constants.
  3. Floating point or real constants are expressed in decimal or exponent form.
  4. Character constants are character and String constants.
  5. Boolean literals are expressed as true or false.
  6. Constants declared as final cannot change their value during running of the program.
  7. Integer data types are byte (1 byte), short (2 bytes), int (4 bytes), long (8 bytes).
  8. Float data types are float (4 bytes) and double (8 bytes).
  9. The scope of the variable is local. This means that a variable declared in a function is accessible only within the function.
  10. The basic (also known as intrinsic) operators are + addition − subtraction * multiplication / division % modulus (remainder after division).
  11. Type Conversion: If the variables involved in an operation are of different types, then Java carries out type conversion automatically before the operation. The process of conversion to a larger data type from a smaller data type is called widening and conversion from larger to smaller data type is called narrowing.
  12. Type Cast: Suppose we want to declare the result in a particular data type, we can type cast the variable : (data type) variable.
  13. Unary Operators: In unary operators, the operator precedes a single operand. The minus operator is both a unary and a binary operator.
  14. ++ , -- operators are called increment and decrement operators.
  15. Assignment Operator operator is =. This is also called equality operator.
  16. The relational operators are : > >= < and <=. Two more operators, known as equality operators = = and ! =, have priority just below relational operators.
  17. Logical Operators: These are && and || and NOT operator (!). Evaluation of expressions connected by logical operators are done from left to right and evaluation stops when either truth or falsehood is established.
  18. Bit-wise operators available in Java language are Seven. They are & Bit wise AND, | Bitwise OR, ^ Bit wise Exclusive OR, << Left Shift, >> Right Shift, >>> Bitwise zero Fill Shift Operator, ~ Tilde operator . one's complement Operator.
  19. instanceof operator to test if the object belongs to a particular class or not.
  20. new operator It is used to allocate resources when we create objects for classes.
  21. Syntax of if statement: if (expression) statement.
  22. There will be several occasions when a programmer has to execute a set of instructions repeatedly till a condition is met. In these situations, we need control loops. The switch statement is similar to if-else-if ladder.
  23. The syntax of while loop is : While(expression){ statement1;statement2;}.
  24. Do-while loop :The syntax is Do{ block of statements} while (expression).
  25. For loop syntax is: for ( exp1 ; exp2 ; exp3), where exp1 is initialization block, exp2 is condition test block, exp3 is alter initial value assigned to exp1.
  26. Break statement is used to exit from the switch control or control loop.
  27. Continue is used when we want to stop further processing of loop statements and start at the beginning of the control loop.

Exercise Questions

Objective Questions

  1. Char data type supported by Java takes
    1. 4 bytes
    2. 3 bytes
    3. 2 bytes
    4. 1 byte
  2. Float data type supported by Java takes
    1. 2 bytes
    2. 8 bytes
    3. 4 bytes
    4. 1 byte
  3. Which of the following statements are true in respect of Boolean constants?
    1. Enclosed in single quote
    2. Enclosed in double quotes
    3. Occupies a single bit in memory
    4. Can be used as identifiers
    1. i
    2. i and ii
    3. i, ii and iii
    4. iii
  4. Which of the following statements are true in respect of data types of Java?
    1. Byte takes 1 byte
    2. Short lakes 1 byte
    3. Integer takes 2 bytes
    4. Long takes 8 bytes
    1. iv
    2. i and ii
    3. i, ii and iii
    4. iii
  5. Which of the following statements are true in respect of variables of Java?
    1. Instance variables belong to all instances of class
    2. Class variables are declared inside or outside the class
    3. Object is a class variable
    4. Scope of the variable is local
    1. ii and iii
    2. i and ii
    3. i, ii and iii
    4. iii and iv
  6. Which of the following statements are true in respect of operators of Java?
    1. Arithmetic operators have the same priority
    2. * / % have the same priority
    3. The priority of + - is higher than the priority of * /
    4. Association for arithmetic operators is from left to right
    1. ii and iv
    2. i and ii
    3. i, ii and iii
    4. iii and iv
  7. Modulus operator can only be applied to integer data types     TRUE/FALSE

    Short-answer Questions

  8. What are the different data types of Java?
  9. Distinguish a variable and constant with examples.
  10. Explain type casting with examples.
  11. What are relational and logical operators? Discuss their priorities.
  12. What is the difference between & , && operators?
  13. What is the difference between = , = = operators?
  14. Explain ? operator.
  15. Explain new and instanceof operator.
  16. Show the working of bit-wise AND operator with examples. What is masking operation?
  17. Show the working of bit-wise OR and Exclusive OR operators with examples.
  18. Distinguish unary and binary operators.
  19. What is >>> operator in Java?

    Long-answer Questions

  20. What are the literal constants and data types provided by Java? Explain with suitable examples.
  21. Distinguish type casting and type conversion with examples.
  22. Explain the usage of bit-wise operators of Java.
  23. What is operator precedence and Associativity? Discuss with examples.
  24. Explain the difference between if–else–if and switch statements. Which is better and why?
  25. Explain variations in for loop statements in Java with examples.
  26. Which one of these are better for control loop: for, while, do while?
  27. Distinguish continue and break statement.

    Assignment Questions

  28. Write a c module to compute simple and compound interest using the formula
              SI =P*N*R/100 and CI= P*(1+R/100)^N
  29. Write a program to store number, age and weight in three separate arrays for 10 students. At the end of data entry, print what has been entered.
  30. Using the formula A=Squareroot(s*(s-a)*(s-b)*(s-c)), compute area of the triangle. S = (a+b+c)/2, and a, b, and c are sides of the triangle
  31. Write a Java program to count the number of lines, the number of words, the number of open braces and the number of close braces in an input file.
  32. Write a program to convert a given integer into
    1. hexadecimal numbers and
    2. octal numbers.
  33. Write a program to shift given integer to 2 positions to the left.
  34. Write a program to test if the given integer has 1 in 4 bit position. If it is 0, set it to 1.
  35. Write a Java program to mask given integer of the low 4 bits.
  36. Using priorities of the operators evaluate z= 4 * 5/6 + 10 / 5 + 8 – 1 + 7/8.
  37. Write a program to print the ASCII table for range 30 to 122.

Solutions to Objective Questions

  1. c
  2. c
  3. d
  4. a
  5. d
  6. a
  7. False
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.5