You are on page 1of 13

1

B.Sc (Computer Sc ience) Object Oriente d Programming with Java and Data Structures Unit- II

1. Classify the operators in Java. Java operators can be classified into a number of categories as below: 1. Arithmetic operators 2. Relational operators 3. Logical operators 4. Assignment operators 5. Increment and Decrement operators 6. Conditional operators 7. Bitwise operators 8. Special operators 2. Disc uss about Arithmetic ope rators.

Arithmetic operators are used to construct mathematical expressions as in algebra. Operator + * / % Meaning Addition or unary plus Subtraction or unary minus Multiplication Division Modulo Div ision (Remainder)

3. Explain a bout Re lational ope rators. Comparison in Java is done w ith the help of Relational operators. An expression which contains a relational operator is termed as Relational Expression. Java supports six relational operators in all. Operator < <= > >= == != Meaning Is less than Is less than or equal to Greater than Greater than or equal to Is equal to Is not equal to

The general form of relational expression is: AE1 (relational operator) AE2 Where AE1 is Arithmetic expression1 Where AE2 is Arithmetic expression2 4. What a re the Logica l operators?

IIMC

Prasanth Kumar K

2
Java has three logical operators. Operator && || ! Meaning Logical AND Logical OR Logical NOT

The logical operators && and || are used when we want to form compound conditions by combining one or more relations. Eg: a>b && x==10 An expression of this kind which combines two or more relational expressions is termed as logica l expression or a compound re lational expression. A logical expression yields a value of true or fa lse. Op1 && op2 is true if both op1 and op2 are true and false otherwise. Op1 || op2 is true if atleast op1 or op2 are true and false otherw ise. 4. What is an Assignment Ope rator? Assignment operator is used to assign the value of an expression to a variable. It is represented with the symbol = . In addition, Java has a set of shorthand assignment operator which are used in the form of V op=exp; Where V is a variable, op is a Java binary operator and exp is an expression. Eg: x+=5 is similar to x=x+5 Assignment ope rator a=a+1 a=a-1 a=a*1 a=a/1 a=a%1 Shortha nd Assignme nt Operator a+=1 a-=1 a*=1 a/=1 a%=1

Advantages: 1. What appears on the left-side need not be repeated and therefore it becomes very easy to write. 2. The statement is more concise and easier to read 3. Use of shorthand operator results in a more efficient code.

5. What a re Increme nt a nd Dec rement Operators?

Java has two very useful operators called increment (++) and decrement (--) operators. Both are unary operators and are used in the follow ing form: ++a or a++ ; --a or a--; While ++a and a++ mean the same thing when they form statements independently, they behave differently when they are used in expressions on the right-hand side of an assignment statement.

IIMC

Prasanth Kumar K

3
6. Explain conditional operator. The character pair ? : is a ternary operator available in Java. This operator is used to construct conditional expressions of the form: Exp1? Exp2 : Exp3 Where Exp1, Exp2 and Exp3 are expressions. Exp1 is evaluated first. If it true, then Exp2 is evaluated otherw ise Exp3 is evaluated. Only one expression among Exp2 and Exp3 is evaluated. 7. What a re Bitwise ope rators? Java has supporting special operators known as Bitwise operators for manipulating of data values of bit values. These operators are used for testing the bits or shifting them to the right or left. Operator & | ^ ~ << >> >>> Meaning Bitwise AND Bitwise OR Bitwise exclusive OR Ones complement Left shift Right shift Right shift with zero fill

8. Explain a bout instanceof a nd membe r selection.

instanceof: The instanceof is an object reference operator and return true if the object on the left-hand side is an instance of the class given on the right-hand side. This operator allows us to determine w hether the object belongs to a particular class or not. Eg: person instanceof student Is true if the object person belongs to the class student, otherwise false. Member Se lection: The member selection or dot operator is used to access the instance variables and methods of class objects. Eg: person.age Reference to the variable age Person.calsal() Reference to the method calsal() 9. Which of the following a rithmetic expressions a re valid?

a) 25/3 % 2 Valid. Because 25/3 is 8 and 8%2 is 0. b) +9/4+5 Valid. Because +9/4 is 2 and 2+5 is 7. c) 7.5%3 Invalid. Because modulo div ision is an integer div ision. d) 14%3+7% 2 Valid. Because 14%3 is 2, 7%2 is 1 and 2+1=3. e) -14%3 Valid. Because -14%3 is 2 as % is applicable to both +ve and ve integers.

IIMC

Prasanth Kumar K

4
f) 15.25 + -5. 0 Valid. g) (5/3)*3+5%3 Valid. Because 5/3 y ield 1 and 1*3=3 and 5%3=2. Totally 3+2=5. h) 21%(int)4.5 Valid. Because 4.5 is typecasted into integer and yield 4. Finally 21%4=1 10. Write Java assignments to evaluate the following quations. a) Area = r2 + 2 rh double Area=pi*Math.pow(r, 2) +2*pi*r*h b) Torquee=(2m1m2 )/(m1+m2)*g double Torquee=((2* m1 * m2 )/( m1 +m2 ))*g c) Side = (a2+b2+2ab cos(x)) double side= Math.sqrt(Math.pow(a,2)+Math.pow(b,2)+2*a*b*Math.cos(x)) d) Energy =mass(acceleration*he ight+(velocity 2/2)) double energy =mass*(acceleration*height +Math.pow(velocity,2)/2) 11. Identify unnecessary pare nthesis in the following arithmetic expressions. a) (x-(y/5)+z)% 8+25 The above expression can be written as (x-y/5+z)%8+25 because / is given high priority than b) ((x-y)*p)+q The above expression can be written as (x-y)*p+q c) (m*n)+(-x/y) The above expression can be written as m*n+- x/y d) x/(3*y) There is no change in the above expression. 12. F ind errors if a ny, in the following assignment statements a nd rectify them. a) x=y=z=0.5,2. 0,-5.75; Error. The assignment statement is written as x=0.5,y =2.0,z=-5.75; b) m=++a*5; No Error. c) Y=sqrt(1000); Error. The assignment statement is written as Y=Math.sqrt(1000); d) P*=x/y; No Error. e) S=/5;

IIMC

Prasanth Kumar K

5
Error. It is an illegal statement because it is not a short hand assignment statement. f) A=b++-c*2; No Error.

13. Dete rmine the va lue of each of the following logical ex pression if a =5, b=10 a nd c=-6. a) a>b&&a<c False b) a<b&&a>c True c) a==c||b>a True d) b>15&&c<0||a>0 True e) (a/2.0==0.0&&b/2.0!=0.0)||c<0.0 True 14. In what way switch statement differs from if stateme nt? if statement: if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a two-way decision statement and is used in conjunction with an expression. It allows the computer to evaluate the expression first and then depending on whether the value of the expression is true or false. It transfers the control to a particular statement. This point of program has two paths to follow, one for the true condition and the other for the false condition. The if statement is implemented in four forms: Simple if statement ifelse statement Nested ifelse statement else if ladder

1. 2. 3. 4.

switch statement: The complexity of a program increases when the number of alternatives increases in if statement. The program becomes difficult to read and follow. It may confuse even the designer. Java has a built-in multi way decision statement known as switch. The switch statement tests the value of a given variable against a list of case values and when a match is found, a block of statements associated with that case is executed.

The general form of the switch statement is as below: switch(expression) { case value1: stat1;

IIMC

Prasanth Kumar K

6
break; case value2: stat2; break; . . . . . case valuen: statn; break; default: defaultstat; } The expression is an integer or character expression. value1,value2,valuen are know as case labels. There is no need to put braces around these blocks but it is important to note that case labels end with a colon. When the switch statement is executed, the value of the expression is successively compared against the values value1,value2,valuen. If a case is found whose value matches with the value of the expression, then the block of the statements that follow the case are executed. The break statement at the end of each block signals the end of a particular case and causes an exit from the sw itch statement. The default is an optional case. When preset, it will be executed if the value of the expression does not match with any of the case values. 14. Write a program to find the numbe r of a nd sum of a ll intege rs greater than 100 and less tha n 200 that a re divisible by 7.
class div7 { public static void main(String[] args) { int i=0,sum=0; for(int n=101;n<200;n++) { if(n%7==0) { sum=sum+n; i=++i; System.out.println(n); } } System.out.println("No of integers divisible by 7 which are >100 and <200 are:" + i); System.out.println("Sum of integers divisible by 7 which are >100 and <200 are:" + sum); }

15. Compare while and do while.

While: The while is an entry-controlled loop statement. The test condition is evaluated and if the condition is true, then the body of the loop is executed. After execution of the body, the test condition is once again evaluated and if it true, the body is executed once again. This process of repeated execution of the body

IIMC

Prasanth Kumar K

7
continues until the test condition finally becomes false and the control is transferred out of the loop. On exit, the program continues with the statement immediately after the body of the loop. The body of the loop may have one or more statements. The braces are needed only if the body contains two or more statements. However, it is a good practice to use if the body has only statement. while(condition) { Body of the loop;

} do while: The while makes a test condition before the loop is executed. Therefore, the body of the loop may not be executed at all if the condition is not satisfied at the very first attempt. On some occasions it might be necessary to execute the body of the loop before the test is performed. Such situations can be handled w ith the help of the dowhile statement. do { Body of the loop; }while(condition); On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end of the loop, the test condition in the while statement is evaluated. If the condition is true, the program continues to evaluate the body of the loop once again. This process continues as long as the condition is true. When the condition becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement. Since the test condition is evaluated at the bottom of the loop, the dow hile construct provides an exit-controlled loop and therefore the body of the loop is always executed atleast once. 15. Ex pla in for statement.

The for loop is entry-controlled loop that prov ides a more concise loop control structure. The general form of for loop is: for(initialization; test condition;increment/decrement) { Body of the loop; } The execution of for statement is as follows: 1. Initialization of the control variables is done first, using assignment statements such as i=1 and count =0. These variables are known as loop-control variables.

IIMC

Prasanth Kumar K

8
2. The value of the control variable is tested using the test condition. The test condition is a relational expression such as i<10 that determines when the loop will exit. If the condition is true, the body of the loop is executed; otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop. 3. When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop. Now, the control variable is incremented/decremented using an assignment statement such as i=i+1 and the new value of the control variable is again tested to see whether it satisfies the loop condition. If the condition is satisfied, the body of the loop is again executed. This process continues till the value of the control variable fails to satisfy the test condition. 16. Compare break and continue.

brea k: an early exit from a loop can be accomplished by using the break statement. When the break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop. When the loops are nested, the break would only exit from the loop containing it. That is, the break will exit only a single loop. continue: Java supports similar statement called the continue statement. However, unlike the break w hich causes the loop to be terminated, the continue as the name implies causes the loop to be continued with the next iteration after skipping any statements in between. 17. Write a program using while loop to display reverse the digits of the given number.

import java.io.*; class reverse { public static void main(String[] args) throws IOException { int i,k; System.out.println("Enter a number to reverse"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine(); i=Integer.parseInt(s); System.out.print("Reversed Number:"); while(i>0) { k=i%10; System.out.print(k); i=i/10; } }

18. Write a program to compute the sum of the digits of a given number.

IIMC

Prasanth Kumar K

9
import java.io.*; class sum { public static void main(String[] args) throws IOException { int i,k,sum=0; System.out.println("Enter a number"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine(); i=Integer.parseInt(s); while(i>0) { sum=sum+i%10; i=i/10; } System.out.println("Sum of the digits:" + sum);

} }

20. What is a class? A class is a user-defined data type with a template that serves to define its properties. Once the class type has been defined, we can create variables of that type using declarations that are similar to the basic type declaration. These variables are termed as instance of classes. The basic form a class definition is: class classname [extends superclass] { [fields declaration] [methods declaration] } The keyword extends indicates that the properties of the superclass are extended to the subclass. 21. What is a n empty class? A class which does not contain any properties is called an empty class. This means the following code is a valid class definition class empty { } Programmer can compile and create objects for the above class.

22. What is a n Object? How is an object c reated? An instance of a class is called Object.

IIMC

Prasanth Kumar K

10
Objects in Java are created using ne w operator. The new operator creates an object of the specified class and returns a reference to that object. Rectangle r; R=new Rectangle(); Both statements can be combined into one as below: Rectangle r=new Rectangle(); 23. How is a method defined? A class with is a Java function. The general form of method is: type methodname(parameter list) { Body of the method } Method declaration have four basic parts: The name of the method The type of the value the method returns A list of parameters The body of the method. The type specifies the type of the value the method would return. This could be a simple data type such as int, float,char and so on. It could be even void, if the method doesnt return any value. The parameter list is always enclosed in parenthesis. This list contains variable names and types of all values which are given as input. In case where no input data is required, the declaration must retain empty parenthesis. The body actually describes the operations to be performed. class Rectangle { int length; int width; void getdata(int x,int y) { length=x; width=y; } } 24. When do we declare a member of a class as static? The variables and methods are called as instance variables and instance methods. Static is used to create a member that is common to all the objects and accessed without a particular object. That is, the member belongs to the class as a whole rather than the objects created from the class. Such members can be defined as follows: static int count; static int max(int x,int y);

IIMC

Prasanth Kumar K

11
The members that are declared static are called as static members. Since these members are associated with the class itself rather than individual objects, the static variables and static methods are often referred as class variables and class methods. Java creates only one copy for a static variable which can be used even if the class is never actually instantiated. Static methods can be called without using the objects. They are also available for use by other classes. Static methods have several restrictions. They can only call other static methods. They can only access static data. They cannot refer to this or super in any way.

25. What is a Constructor? What a re its spec ial prope rties?

Java supports a special type of method called Constructor that enables an object to initialize itself when it is created. class Rectangle { int length; int width; Rectangle(int x,int y) { length=x; width=y; } } Specia l Cha racters: Constructors have the same name as the class itself. They dont have any return type, not even void. This is because they return the instance of the class. 26. Ex pla in about inheritance in Java. Java classes can be reused in several ways. This is basically done by creating new classes, reusing the properties of existing ones. The mechanism of deriv ing a new class from old one is called inheritance. The old class is know n as base class or super c lass or pa rent c lass and the new one is called the subclass or de rived class or child class. The inheritance allows subclasses to inherit all the variables and the methods of their parent classes. Inheritance may take different forms: Single inheritance (only one super class) Multiple inheritance (several super class) Hierarchical inheritance (one super class, many subclasses) Multilevel inheritance (derived from a derived class) De fining a subclass: A subclass is defined as follows:

IIMC

Prasanth Kumar K

12
class subclass extends superclass { Variable declarations; Methods declarations; } The keyword extends signif ies that the properties of the superclass are extended to the subclass. The subclass will now contain its own variables and methods as well those of the superclass. This kind of situation occurs when we want to add some more properties. 27. When do we declare a method or c lass as fina l?

All methods and variables can be overridden by default in subclasses. A class that cannot be sub classed is called final class. This is achieved in Java using the keyword final as follows: final class A { Body of the class } Making a method final ensures that the functionality defined in the method will never be altered in any way. Similarly, the value of a final variable can never be changed. 28. When do we declare a method or c lass as a bstract?

Java allows the programmer to override a method compulsory. This can be done using the keyword abstract in the method defined. abstract class Shape { .. .. abstract void draw(); .. } When a class contains atleast one abstract method, it should be declared as abstract. When using the abstract classes, we must satisfy the following conditions: We cannot use abstract classes to instantiate objects directly. For example Shape s=new Shape() is illegal because Shape is an abstract class. The abstract methods of an abstract class must be defined in its subclass. We cannot declare abstract constructors or abstract static methods. 29. Discuss the differe nt levels of access protection available in Java.

When inheriting all the members of a class by a subclass, it may be necessary in some situations to restrict the access to certain variables and methods from outside the class. This can be achieved in Java by applying v isibility modifie rs to the

IIMC

Prasanth Kumar K

13
instance variables and methods. The visibility modifiers are also known as access modifie rs. Java prov ides three types of visibility modif iers: public private protected public access: Any variable or method to the entire class in which it is defined. This is possible by simply declaring the variables or methods as public. public int number; public void sum() { } A variable or method declared as public has the widest possible visibility and accessible everywhere. private access: private fields enjoy the highest degree of protection. They are accessible only with their own class. They cannot be inherited by subclasses and therefore not accessible in subclasses. A method declared as private behaves like a method declared as final. It prevents the method from being subclassed. friendly access: When no access modifier is specified, the member defaults to a limited version of public accessibility known as friendly level of access. The difference between the public access and the friendly access is that the public modifier makes fields visible in all classes, regardless of their package while the friendly access makes fields visible only in the same package, but not in other package. protected access: The visibility level of a protected field lies in between the public access and friendly access. That is, the protected modifier makes the fields visible not only to all classes and subclasses in the same package but also to subclasses in other packages. private protected access: A f ield can be declared with two keywords private and protected together like: private protected int codenumber; This gives a visibility level in between the protected and private access. This modifier makes all f ields visible to all subclasses regardless of what package. The fields are not accessible by other classes in the same package.

IIMC

Prasanth Kumar K

You might also like