Prasanth Kumar K(Head-Dept of Computers)

Similar documents
Operators. Java operators are classified into three categories:

The Java language has a wide variety of modifiers, including the following:

CS260 Intro to Java & Android 03.Java Language Basics

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

JAVA OPERATORS GENERAL

STRUCTURING OF PROGRAM

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

CT 229 Java Syntax Continued

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Unit 3. Operators. School of Science and Technology INTRODUCTION

Chapter 3: Operators, Expressions and Type Conversion

Mobile Application Development ( IT 100 ) Assignment - I

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Operators in C. Staff Incharge: S.Sasirekha

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

1 Shyam sir JAVA Notes

UNIT 3 OPERATORS. [Marks- 12]

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Chapter 4 Introduction to Control Statements

Operators in java Operator operands.

Object Oriented Software Design

Chapter 5. Inheritance

Unit 1 Lesson 4. Introduction to Control Statements

Operators and Expressions

Operators and Expressions:

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Department of Computer Science

MODULE 2: Branching and Looping

Index COPYRIGHTED MATERIAL

CS201 Some Important Definitions

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

e) Implicit and Explicit Type Conversion Pg 328 j) Types of errors Pg 371

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

F I N A L E X A M I N A T I O N

Prepared by: Shraddha Modi

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Sri Vidya College of Engineering & Technology

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Class, Variable, Constructor, Object, Method Questions

Chapter 6 Introduction to Defining Classes

CMPT 125: Lecture 3 Data and Expressions

CSC 1214: Object-Oriented Programming

Learning the Java Language. 2.1 Object-Oriented Programming

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Introduction to Programming Using Java (98-388)

Prof. Navrati Saxena TA: Rochak Sachan

Operators & Expressions

Inheritance and Interfaces

SECTION II: LANGUAGE BASICS

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

CMSC 132: Object-Oriented Programming II

Decaf Language Reference Manual

Chapter 4: Basic C Operators

Full file at Chapter 2 - Inheritance and Exception Handling

CMSC 331 Second Midterm Exam

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Chapter 2. Outline. Simple C++ Programs

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

CS 231 Data Structures and Algorithms, Fall 2016

CH. 2 OBJECT-ORIENTED PROGRAMMING

Unit-2 (Operators) ANAND KR.SRIVASTAVA

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Pace University. Fundamental Concepts of CS121 1

A variable is a name that represents a value. For

Engineering Problem Solving with C++, Etter/Ingber

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Answer1. Features of Java

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

The PCAT Programming Language Reference Manual

Java Object Oriented Design. CSC207 Fall 2014

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

JAVA Programming Fundamentals

Computer Science II (20073) Week 1: Review and Inheritance

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Simple Java Reference

Cpt S 122 Data Structures. Introduction to C++ Part II

UNIT- 3 Introduction to C++

Transcription:

B.Sc (Computer Science) Object Oriented Programming with Java and Data Structures Unit-II 1 1. Define operator. Explain the various operators in Java. (Mar 2010) (Oct 2011) Java supports a rich set of operators. An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. They usually form a part of mathematical or logical operators. 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 1. Arithmetic operators: Arithmetic operators are used to construct mathematical expressions as in algebra. Operator Meaning + Addition or unary plus - Subtraction or unary minus * Multiplication / Division % Modulo Division (Remainder) 2. Relational operators: Comparison in Java is done with 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 3. Logical operators: Java has three logical operators.

2 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 logical expression or a compound relational expression. A logical expression yields a value of true or false. 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 otherwise. 4. Assignment Operator: How to give values to variables? (Oct 2010) 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 operator a=a+1 a=a-1 a=a*1 a=a/1 a=a%1 Shorthand Assignment 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. Increment and Decrement Operators: Java has two very useful operators called increment (++) and decrement (--) operators. Both are unary operators and are used in the following 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. 6. Conditional operator:

Explain Conditional operator. (Oct 2010) 3 Explain ternary operator with an example. (Mar 2012) 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 otherwise Exp3 is evaluated. Only one expression among Exp2 and Exp3 is evaluated. 7. Bitwise operators: 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. 8. Special Operators: Operator Meaning & Bitwise AND Bitwise OR ^ Bitwise exclusive OR ~ One s complement << Left shift >> Right shift >>> Right shift with zero fill Explain Special operator. (Oct 2010) (a). 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 whether 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. (b). Member Selection: 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() 2. Which of the following arithmetic expressions are 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 division is an integer division. 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. f) 15.25 + -5.0 Valid. g) (5/3)*3+5%3 Valid. Because 5/3 yield 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 4 3. Write Java assignments to evaluate the following quotations. a) Area = r 2 + 2 rh double Area=pi*Math.pow(r, 2) +2*pi*r*h b) Torquee=(2m 1 m 2 )/(m1+m2)*g double Torquee=((2*m 1 * m 2 )/( m 1 +m 2 ))*g c) Side= (a 2 +b 2 +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*height+(velocity 2 /2)) double energy=mass*(acceleration*height+math.pow(velocity,2)/2) 4. Identify unnecessary parenthesis 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. 5. Find errors if any, in the following assignment statements and 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; Error. It is an illegal statement because it is not a short hand assignment statement. f) A=b++-c*2; No Error. 5 6. Determine the value of each of the following logical expression if a=5, b=10 and 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 7. Explain different forms of if statements. (Oct 2011) Explain Nested-if-else and if else statements. (Mar 2010) Conditional control structure (Branching): a) if: If structure is also called as conditional statement. In If, statements get executed only when the condition is true. It omits the condition based statements when the condition is false. Braces are not necessary if only one statement is related to the condition. if (condition) statements b) if else: Statements in if block get executed only when the condition is true and statements in else block get executed only when the condition is false. if (condition) Statements else

Statements 6 (c). if-else if: Explain the if-elseif ladder. (Oct 2012) Statements get executed in loops only when the corresponding conditions are true. Statements in the final else block get executed when all other conditions are false. The control checks a condition only when all the afore-mentioned conditions are false. if ( x > 0 ) System.out.println( positive ); else if ( x < 0) System.out.println( negative ); else System.out.println( zero ); (d). nested if: Writing if in another if is nested-if. Inner if is processed only when outer if s condition is true. Hence, statements in inner-if get executed only when condition1 and condition2 are true. 8. In what way switch statement differs from if statement? (Mar 2011) 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: 1. Simple if statement 2. if else statement 3. Nested if else statement 4. else if ladder 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; break; 7 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 switch 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. 9. Write a program to find the number of and sum of all integers greater than 100 and less than 200 that are 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); 10. Compare while and do while. (Oct 2010) (Mar 2012) (Oct 2012) 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 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; 8 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 with the help of the do while 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 do while construct provides an exit-controlled loop and therefore the body of the loop is always executed atleast once. 11. Explain for statement. (Mar 2010) The for loop is entry-controlled loop that provides 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. 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. 9 12. Differentiate between break and continue. (Oct 2010) (Oct 2011) (Apr 2012) break: 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. class PrimeNumber public static void main (String args[]) int n=10,i; i=2; while(i<n) if(n%i= =0) system.out.println( Number is not prime ); break; i++; if(n==i) System.out.println( Given no is prime ); continue: Java supports similar statement called the continue statement. However, unlike the break which 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. class Demo public static void main(string args[]) int i; for(i=1;i<=10;i++) if(i<5)

continue; System.out.println(i); In the above program we are redirecting the flow of execution back to the next iteration of the loop till i<5. When i value changes from 1 to 4(i=1,2,3,4) continue statement will be executed and System.out.println is not executed. Whenever i value will become 5 i values will be displayed. 10 13. 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; 14. Write a program to compute the sum of the digits of a given number. 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); 15. Distinguish between a class and an object. (Oct 2012) 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. Object: An instance of a class is called Object. Objects in Java are created using new 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(); 11 16. What is an 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. 17. 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 doesn t 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; 12 18. What are static data member and static methods members? (Oct 2012) 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); 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. 19. What is a Constructor? (Oct 2010) 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; 13 Special Characters: Constructors have the same name as the class itself. They don t have any return type, not even void. This is because they return the instance of the class. 20. What is the need for copy Constructor? (Mar 2012) Copy Constructor is a constructor that takes the object of same class as argument. If all the properties of an object which has to be assigned to another object, this is advisable. Box b1=new Box(5); Box b2=new Box(b1); 21. Explain about inheritance in Java. (Mar 2010) (Mar 2011) 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 deriving a new class from old one is called inheritance. The old class is known as base class or super class or parent class and the new one is called the subclass or derived 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) Single inheritance: If a class is derived from another class, it can be called as single inheritance. Hierarchical inheritance: If two or more classes are derived from a class, it can be called as hierarchical inheritance.

14 Multiple inheritance:if a class is derived from two or more classes, it can be called as multiple inheritance. Java does not support this type of inheritance. Multilevel inheritance: (Oct 2012) If a class is derived from the class, which is derived from another class; it can be called as multilevel inheritance. Defining a subclass: A subclass is defined as follows: class subclass extends superclass Variable declarations; Methods declarations; The keyword extends signifies 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. 22. Difference between Overloading and Overriding methods. (Mar 2010) Method overloading:- Explain Method overloading in Java. (Mar 2011)

Methods are created with the same name but different parameter list and different definitions. This is called method overloading. 15 Method overloading is used when objects are required to perform similar task but using different. Input parameters. When we call a method in an object, java matches up the method name first and then the number of parameters and then type of parameters to decide which one of the definitions to execute. This process is known as polymorphism. In the below example, constructor overloading is used. (Mar 2012) class Room float length; float breadth; Room(float x,float y) length=x; breadth=y; Room(float x) length=breadth=x; Int area() Return length*breadth; Method overriding:- Explain Method overriding in Java with suitable example. (Mar 2011) A method defined in a super class can be inherited by its subclass and is used by the objects created by its subclass. Method inheritance enables us to define and use methods repeatedly in subclasses without having to define the methods again in the subclass. However, there may be occasions when an object to respond to the same method but have different behavior when that method is called. That means, the super-class method should be override. This is possible by defining a method in the subclass that has the same name, same arguments and same return type as a method in the super-class. When that method is called, the method defined in the subclass is invoked and executed instead of the one in the super-class. This is known as overriding. class A int i, j; A(int a, int b) i = a;

j = b; void show() System.out.println("i and j: " + i + " " + j); 16 class B extends A int k; B(int a, int b, int c) super(a, b); k = c; void show() System.out.println("k: " + k); class OverrideMethod public static void main(string args[]) B b = new B(1, 2, 3); b.show(); A a=new A(10,20); a.show(); 24. When do we declare a method or class as final? (Mar 2011) 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. 25. Explain Finalizer method? (Oct 2010) A constructor is used to initialize an object when it is declared. This is known as initialization. Similarly, Java supports a concept called finalization, which is just opposite to initialization. Java run-time is an automatic garbage collecting system. It automatically frees up the memory resources used by the objects. But objects may hold other non-object resources such as file descriptors or window system fonts. The garbage collector cannot free these resources in order to free these resources we must use a finalizer method. This is similar to destructors in C++, The finalizer method is simply finalize() and can be added to any class. Java calls that method whenever it is about to reclaim the space for that object. The finalize method should explicitly define the tasks to be performed.

Before an object is garbage collected, the runtime system calls its finalize() method. The intent is for finalize() to release system resources such as open files or open sockets before getting collected. finalize() is best used for the following transactions. Memory deallocations To free non-object resources To close file streams To close database connections To close network sockets. 17 26. When do we declare a method or class as abstract? (Oct 2011) 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. 27. Explain the different levels of access protection in Java. (Mar 2011) List and compare access modifiers in Java. (Oct 2010) How to access class members. (Mar 2010) 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 visibility modifiers to the instance variables and methods. The visibility modifiers are also known as access modifiers. Java provides three types of visibility modifiers: 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 field 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 fields visible to all subclasses regardless of what package. The fields are not accessible by other classes in the same package. 28. What are the different Mathematical Functions? 18 Mathematical Functions:- Java supports the basic mathematic functions through Math class defined in java.lang package. These functions should be used as follows. Math. functionname(); Function Description 1. sin(x) It returns the sine of the angle x in radius 2. cos(x) It returns the cosine of the angle x in radius 3. tan(x) It returns the tangent of the angle x in radius 4. pow(x,y) It returns x raised to y( 5. exp(x) It returns e raised to x( 6. sqrt(x) It returns square root of x 7. abs(x) It returns the absolute value of x 8. max(a,b) It returns the maximum of a and b. 9. min(a,b) It returns the minimum of a,b