Вы находитесь на странице: 1из 56

II YEAR / IV SEMESTER

(ELECTRICAL AND ELECTRONICS ENGINEERING)


CS6456 - OBJECT ORIENTED PROGRAMMING
UNIT - IV
OVERVIEW OF JAVA

COMPILED BY
M.KARTHIKEYAN, M.E., (AP/IT)
VERIFIED BY

HOD

PRINCIPAL

CORRESPONDENT

DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING


SENGUNTHAR COLLEGE OF ENGINEERING TIRUCHENGODE
1

UNIT IV
OVERVIEW OF JAVA

Data types
Variables and arrays
Operators
Control statements
Classes and Objects
Methods
Inheritance

LIST OF IMPORTANT QUESTIONS


UNIT IV
OVERVIEW OF JAVA
2

PART-A
1. What is a byte code? [M/J2016] [A/M2015] [M/J2012]
2. What is JVM? [A/M2015] [or] What is Java Virtual Machine? [M/J2012]
3. Write the iteration statements with syntax. [M/J2014]
4. Mention the bitwise logical operator with example. [M/J2014]
5. What is an Applet in Java? [N/D2014]
6. What is the use of Super keyword in Java? [N/D2014]
8. List the various data types in Java. [M/J2013]
9. Define the term Class. [M/J2013]
10. What is meant StringBuffer? [A/M2011]
11. Java is robust .Comment.[M/J2016]
12. Difference between Static binding and Dynamic binding in java ?

PART-B
1. Discuss the various types of operators in Java and explain with suitable examples.
(16m) [A/M2015] (4m) [N/D2014]
2. What is an access modifier? Differentiate between private, protected and public
access modifiers with examples. (16m) [A/M2015]
3. What are the selection statements available in Java? Explain with suitable examples.
(16m) [M/J2014] [or] Discuss in detail about control statements with programming
examples. (16m) [M/J2013]
4. Explain about Inheritance in Java with an example program. (16m) [N/D2014] [or]
what are the different forms of inheritance supported in Java? (8m) [M/J2012] [or] How
will you create multilevel hierarchy? Discuss with clear example. (16m) [M/J2014]
5. Describe the features of java. (8m) [N/D2014] [OR] List out the characteristics of
Java. [M/J2016] [8m]
6. Expalin in detail about Data types in java. (4m) [N/D2014]
7. Explain about Classes and objects with programming examples.(16m) [M/J2013]
8. Explain about dynamic method dispatch with an example. [M/J2016] [8m]

9. Implement a class Student. A student has a name and a total quiz score. Supply an
appropriate constructor and methods getName(), addQuiz(int score), getTotalScore(),
and getAverageScore(). To compute the latter, you also need to store the number of
quizzes

that

the

student

took.

[M/J2016][10m]

10. Distinguish between instance method and class method with an example?[M/J2016]
[6m]

NOTES
UNIT IV
OVERVIEW OF JAVA
PART-A

1. What is a byte code? [A/M2015] [M/J2012]


Bytecode is the compiled format for Java programs. Once a Java program has
been converted to bytecode, it can be transferred across a network and executed by
Java Virtual Machine (JVM). Bytecode files generally have a .class extension
2. What is JVM? [A/M2015] [or] What is Java Virtual Machine? [M/J2012]
4

JVM (Java Virtual Machine) is an abstract machine. It is a specification that


provides runtime environment in which java bytecode can be executed. JVMs are
available for many hardware and software platforms (i.e.JVM is plateform dependent).

3. Write the iteration statements with syntax. [M/J2014]


Java provides three iteration statements.

4. Mention the bitwise logical operator with example. [M/J2014]


The bitwise logical operators are &, |, ^, and ~. The following table shows the
outcome of each operation.

5. What is an Applet in Java? [N/D2014]


5

Applet is a special type of program that is embedded in the webpage to generate


the dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:

It works at client side so less response time.

Secured

It can be executed by browsers running under many plateforms, including Linux,


Windows, Mac Os etc.

6. What is the use of Super keyword in Java? [N/D2014]


The super keyword is used to access a member of an immediate base class, from a
derived class. Whenever you create the instance of subclass, an instance of parent
class is created implicitly i.e. referred by super reference variable.
7. Define a trim() function in JAVA. [A/M2011]
This method returns a copy of the string, with leading and trailing whitespace
omitted.
Syntax: public String trim()
8. List the various data types in Java. [M/J2013]

9. Define the term Class. [M/J2013]


A class is a blue print from which individual objects are created.
A sample of a class is given below:
public class Dog{
String breed;
int age;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
10. What is meant StringBuffer? [A/M2011]
Java StringBuffer class is used to created mutable (modifiable) string. The
StringBuffer class in java is same as String class except it is mutable i.e. it can be
changed.
Important Constructors of StringBuffer class
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
7

2. StringBuffer(String str): creates a string buffer with the specified string.


3. StringBuffer(int capacity): creates an empty string buffer with the specified
capacity as length.

11. Java is robust .Comment.[M/J2016]


Java is Robust because it is highly supported language. It is portable across
many Operating systems. Java also has feature of Automatic memory management and
garbage collection. Strong type checking mechanism of Java also helps in making Java
Robust. Bugs, especially system crashing bugs, are very rare in Java.
12. Difference between Static binding and Dynamic binding in java ?
Static binding in Java occurs during compile time while dynamic binding occurs during
runtime. Static binding uses type(Class) information for binding while dynamic binding
uses instance of class(Object) to resolve calling of method at run-time. Overloaded
methods are bonded using static binding while overridden methods are bonded using
dynamic binding at runtime.

13. Define Recursion in Java. [N/D2011]


Java supports recursion. Recursion is the process of defining something in terms
of itself. As it relates to java programming, recursion is the attribute that allows a method
to call itself. A method that calls itself is said to be recursive. The classic example of
recursion is the computation of the factorial of a number.
14. Define method overloading.
Java enables 2 or more methods with same name but with different signatures.
The signature includes the number of type, and sequence of the arguments passed to a
method. The capability to overload a method is referred to as overloading methods.
15. Define Garbage Collection in Java?
8

Garbage

Collection

also

referred

as

automatic

memory

management.

Periodically frees the memory used by objects that are no longer needed. The garbage
collector in java scans dynamic memory areas for objects and marks those that are
referenced. After all possible paths to objects are investigated the unreferenced objects
are freed.

16. Define API.


Java API are libraries of compiled code that can be used in the programs. They let you
add readymade and customizable functionality to save your programming time.
17. What are features does not supported by java?
1. Goto statement
2. Multiple inheritance
3. Operator overloading
4. Structures and Unions allowed
5. Pointers
18. What are the JDK Tools
1. Javac- Java Compiler
2. Java Java interpreter
3. Jdb Java Debugger
4. Javap- Java Disassembler
5. Javadoc- Java Documentation
6. Javah - Java Header file Generator
7. The Appletviewer
19. Java is platform independent language. Justify.
Platform is the hardware or system software environment in which the program

runs. Moreover java language run by any operating system, thats why java is called
platform independent languages.

PART - B
1. Discuss the various types of operators in Java and explain with suitable
examples. (16m) [A/M2015] (4m) [N/D2014]
Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:

Arithmetic Operators

Relational Operators

Bitwise Operators

Logical Operators

Assignment Operators

Misc Operators

The Arithmetic Operators:


Arithmetic operators are used in mathematical expressions in the same way that
they are used in algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20, then:

10

The Relational Operators:


There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then:

11

The Bitwise Operators:


Java defines several bitwise operators, which can be applied to the integer types,
long, int, short, char, and byte. Bitwise operator works on bits and performs bit-by-bit
operation.
Assume if a = 60; and b = 13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
----------------a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:

12

The Logical Operators:


The following table lists the logical operators:
Assume Boolean variables A holds true and variable B holds false, then:

13

The Assignment Operators:


There are following assignment operators supported by Java language:

14

Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator
consists of three operands and is used to evaluate Boolean expressions. The goal of
the operator is to decide which value should be assigned to the variable. The operator is
written as:

Following is the example,

15

public class Test {


public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}

Output:
Value of b is : 30
Value of b is : 20

Instanceof Operator:
This operator is used only for object reference variables. The operator checks
whether the object is of a particular type(class type or interface type). instanceof
operator is wriiten as:

If the object referred by the variable on the left side of the operator passes the ISA check for the class/interface type on the right side, then the result will be true.
Following is the example:
Example:

Output:

public class Test {

true

public static void main(String args[]){


String name = "James";
// following will return true since name is
type of String
boolean result = name instanceof String;
System.out.println( result );
}
}
This operator will still return true if the object being compared is the assignment
compatible with the type on the right. Following is one more example:
16

class Vehicle {}

Output:

public class Car extends Vehicle

true

{ public static void main(String args[])


{
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result );
}
}
Precedence of Java Operators:
Operator precedence determines the grouping of terms in an expression. This
affects how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has higher precedence than the addition
operator:
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has
higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7. Here,
operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

17

2. What is an access modifier? Differentiate between private, protected and public


access modifiers with examples. (16m) [A/M2015]
Access Modifier
Java provides a number of access modifiers to set access levels for classes,
variables, methods and constructors. The four access levels are:

Visible to the package(the default- No modifiers are needed).

Visible to the class only (private).

Visible to the world (public).

18

Visible to the package and all subclasses (protected).

Default Access Modifier - No keyword


Default access modifier means we do not explicitly declare an access modifier for
a class, field, method, etc.
A variable or method declared without any access control modifier is available to
any other class in the same package. The fields in an interface are implicitly public static
final and the methods in an interface are by default public.
Example:
Variables and methods can be declared without any modifiers, as in the following
examples:
String version = "1.5.1";
boolean processOrder() {
return true;
}
Private Access Modifier - private

Methods, Variables and Constructors that are declared private can only be

accessed within the declared class itself.


Private access modifier is the most restrictive access level. Class and interfaces

cannot be private.
Variables that are declared private can be accessed outside the class if public

getter methods are present in the class.


Using the private modifier is the main way that an object encapsulates itself and
hide data from the outside world.

Example:
The following class uses private access control:
public class Logger {
private String format;
public String getFormat() {
return this.format;
}
19

public void setFormat(String format) {


this.format = format;
}
}
Here, the format variable of the Logger class is private, so there's no way for other
classes to retrieve or set its value directly. So to make this variable available to the
outside world, we defined two public methods: getFormat(), which returns the value of
format, and setFormat(String), which sets its value.
Public Access Modifier - public

A class, method, constructor, interface etc declared public can be accessed from
any other class. Therefore fields, methods, blocks declared inside a public class

can be accessed from any class belonging to the Java Universe.


However if the public class we are trying to access is in a different package, then

the public class still need to be imported.


Because of class inheritance, all public methods and variables of a class are
inherited by its subclasses.

Example:
The following function uses public access control:
public static void main(String[] arguments) {
// ...
}
The main() method of an application has to be public. Otherwise, it could not be called
by a Java interpreter (such as java) to run the class.
Protected Access Modifier - protected

Variables, methods and constructors which are declared protected in a


superclass can be accessed only by the subclasses in other package or any
class within the package of the protected members' class.

20

The protected access modifier cannot be applied to class and interfaces.


Methods, fields can be declared protected, however methods and fields in a

interface cannot be declared protected.


Protected access gives the subclass a chance to use the helper method or
variable, while preventing a nonrelated class from trying to use it.

Example:
The following parent class uses protected access control, to allow its child class
override openSpeaker() method:
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}
Here, if we define openSpeaker() method as private, then it would not be accessible
from any other class other than AudioPlayer. If we define it as public, then it would
become accessible to all the outside world. But our intension is to expose this method to
its subclass only, thats why we used protected modifier.
3. What are the selection statements available in Java? Explain with suitable
examples. (16m) [M/J2014] [or] Discuss in detail about control statements with
programming examples. (16m) [M/J2013]
Looping Mechanisms
There may be a situation when we need to execute a block of code several
number of times, and is often referred to as a loop. Java has very flexible three looping
mechanisms. Can use one of the following three loops:

while Loop
21

do...while Loop

for Loop

The while Loop


A while loop is a control structure that allows you to repeat a task a certain
number of times.
Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}

When executing, if the boolean_expression result is true, then the actions inside
the loop will be executed. This will continue as long as the expression result is
true. Here, key point of the while loop is that the loop might not ever run.

When the expression is tested and the result is false, the loop body will be
skipped and the first statement after the while loop will be executed.

Example:

Output:

public class Test {


public static void main(String args[]) {
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The do...while Loop


A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.
Syntax:
The syntax of a do...while loop is:
22

do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the
statements in the loop execute once before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the
statements in the loop execute again. This process repeats until the Boolean
expression is false.

Example:

Output:

public class Test {


public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The for Loop


A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times. A for loop is useful when you know
how many times a task is to be repeated.
Syntax:
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}

23

Here is the flow of control in a for loop:

The initialization step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to put a
statement here, as long as a semicolon appears.

Next, the Boolean expression is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of control
jumps to the next statement past the for loop.

After the body of the for loop executes, the flow of control jumps back up to the
update statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after
the Boolean expression.

The Boolean expression is now evaluated again. If it is true, the loop executes
and the process repeats itself (body of loop, then update step, then Boolean
expression). After the Boolean expression is false, the for loop terminates.

Example:

Output:

public class Test {


public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Enhanced for loop in Java:


As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{

24

//Statements
}

Declaration: The newly declared block variable, which is of a type compatible


with the elements of the array you are accessing. The variable will be available
within the for block and its value would be the same as the current array element.

Expression: This evaluates to the array you need to loop through. The
expression can be an array variable or method call that returns an array.

Example:

Output:

public class Test {


10,20,30,40,50,
public static void main(String args[]){
James,Larry,Tom,Lacy
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom",
"Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
} }
}
The break Keyword
The break keyword is used to stop the entire loop. The break keyword must be
used inside any loop or a switch statement. The break keyword will stop the execution
of the innermost loop and start executing the next line of code after the block.
Syntax:
The syntax of a break is a single statement inside any loop:
break;
Example:

Output:

public class Test {


public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {

10
20

25

if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
} }
}
The continue Keyword
The continue keyword can be used in any of the loop control structures. It causes the
loop to immediately jump to the next iteration of the loop.

In a for loop, the continue keyword causes flow of control to immediately jump to
the update statement.

In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.

Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example

Output:

public class Test {


public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}

10
20
40
50

}
Decision Making Statements
There are two types of decision making statements in Java. They are:

if statements
switch statements
26

The if Statement
An if statement consists of a Boolean expression followed by one or more
statements.
Syntax:
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the boolean expression evaluates to true then the block of code inside the if statement
will be executed. If not the first set of code after the end of the if statement (after the
closing curly brace) will be executed.
Example:

output

public class Test {


public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("This is if statement");
}
}
}

This is if statement

The if...else Statement


An if statement can be followed by an optional else statement, which executes
when the Boolean expression is false.
Syntax:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else
{
//Executes when the Boolean expression is false
}
27

Example:

output

public class Test {


This is else statement
public static void main(String args[]){
int x = 30;
if( x < 20 ){
System.out.print("This is if
statement");
}else{
System.out.print("This is else
statement");
}
}
}
The if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is
very usefull to test various conditions using single if...else if statement. When using if ,
else if , else statements there are few points to keep in mind.

An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of he remaining else if's or else's will be tested.

Syntax:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
} else if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3)
{
//Executes when the Boolean expression 3 is true
} else
{
//Executes when the none of the above condition is true.
28

}
Example:

output

public class Test {


Value of X is 30
public static void main(String args[]){
int x = 30;
if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else
statement");
}
}
}
Nested if...else Statement
It is always legal to nest if-else statements, which means you can use one if or
else if statement inside another if or else if statement.
Syntax:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.

Example:

output
29

public class Test {


X = 30 and Y = 10
public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y =
10");
}
}
}
The switch Statement
A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked for
each case.
Syntax:
switch(expression)
{

case value1 :
//Statements
break; //optional
case value2 :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements

}
The following rules apply to a switch statement:

The variable used in a switch statement can only be a byte, short, int, or char.
You can have any number of case statements within a switch. Each case is

followed by the value to be compared to and a colon.


The value for a case must be the same data type as the variable in the switch,
and it must be a constant or a literal.
30

When the variable being switched on is equal to a case, the statements following

that case will execute until a break statement is reached.


When a break statement is reached, the switch terminates, and the flow of

control jumps to the next line following the switch statement.


Not every case needs to contain a break. If no break appears, the flow of control

will fall through to subsequent cases until a break is reached.


A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none
of the cases is true. No break is needed in the default case.

Example:
public class Test {
public static void main(String args[]){
char grade = args[0].charAt(0);
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try
again");
break;

default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " +
grade);
}
}
Output
$ java Test a
Invalid grade
Your grade is a a
$ java Test A
Excellent!
Your grade is a A
$ java Test C
Well done
Your grade is a C

4. Explain about Inheritance in Java with an example program. (16m) [N/D2014]


[or] What are the different forms of inheritance supported in Java? (8m)
[M/J2012] [or] How will you create multilevel hierarchy? Discuss with clear
example. (16m) [M/J2014]
31

1) Single Inheritance
When a class extends another one class only then we call it a single inheritance.
The below flow diagram shows that class B extends only one class which is A. Here A is
a parent class of B and B would be a child class of A.

Example:
Class A
{
public void methodA()
{
System.out.println("Base class
method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class
method");
}

public static void main(String args[])


{
B obj = new B();
obj.methodA(); //calling super class
obj.methodB(); //calling local method

2) Multiple Inheritance
Multiple Inheritance refers to the concept of one class extending (Or inherits)
more than one base class. The inheritance we learnt earlier had the concept of one
base class or parent. The problem with multiple inheritance is that the derived class
will have to manage the dependency on two base classes.

32

3) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can
inherit from a derived class, thereby making this derived class the base class for the
new class. As you can see in below flow diagram C is subclass or child class of B and B
is a child class of A

Example
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
} }

Class Z extends Y
{ public void methodZ()
{ System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent
class method
obj.methodY(); //calling parent class
method
obj.methodZ(); //calling local method
} }

33

4) Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below
example class B,C and D inherits the same class A. A is parent class (or base class)
of B,C & D.

Example
Class A
{ public void methodA()
{
System.out.println("method of Class
A");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
Class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
Class D extends A
{
public void methodD()

{
System.out.println("method of Class D");
}
}
Class MyClass
{
public void methodB()
{
System.out.println("method of Class B");
}
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}

34

5) Hybrid Inheritance
In simple terms Hybrid inheritance is a combination of Single and Multiple
inheritance. A typical flow diagram would look like below. A hybrid inheritance can be
achieved in the java in a same way as multiple inheritance by using interfaces. By
using interfaces you can have multiple as well as hybrid inheritance in Java.

Case 1: Using classes: If in above figure B and C are classes then this inheritance is
not allowed as a single class cannot extend more than one class (Class D is extending
both B and C).
Case 2: Using Interfaces: If B and C are interfaces then the above hybrid inheritance is
allowed as a single class can implement any number of interfaces in java.
Example: Using classes to form hybrid
public class A
{
public void methodA()
{
System.out.println("Class A
methodA");
}
}
public class B extends A
{
public void methodA()

Example: Hybrid inheritance


implementation using interfaces.
interface A
{
public void methodA();
}
interface B extends A
{
public void methodB();
}
interface C extends A
{
35

{
System.out.println("Child class B is
overriding inherited method A");
}
public void methodB()
{
System.out.println("Class B
methodB");
}
}
public class C extends A
{
public void methodA()
{
System.out.println("Child class C is
overriding the methodA");
}
public void methodC()
{
System.out.println("Class C
methodC");
}
}
public class D extends B, C
{
public void methodD()
{
System.out.println("Class D
methodD");
}
public static void main(String args[])
{
D obj1= new D();
obj1.methodD();
obj1.methodA();
}
}
Output:
Error!!

public void methodC();


}
class D implements B, C
{
public void methodA()
{
System.out.println("MethodA");
}
public void methodB()
{
System.out.println("MethodB");
}
public void methodC()
{
System.out.println("MethodC");
}
public static void main(String args[])
{
D obj1= new D();
obj1.methodA();
obj1.methodB();
obj1.methodC();
}
}
Output:
MethodA
MethodB
MethodC

36

5.Describe the features of java. (8m) [N/D2014] [OR] List out the characteristics
of Java. [M/J2016] [8m]
The various features of java are as follows,

Object Oriented : In java everything is an Object. Java can be easily extended

since it is based on the Object model.


Platform independent the web and interpreted by virtual Machine (JVM) on

whichever platform it is being run.


Simple :Java is designed to be easy to learn. If you understand the basic

concept of OOP java would be easy to master.


Secure : With Java's secure feature it enables to develop virus-free, tamper-

free systems. Authentication techniques are based on public-key encryption.


Architectural-neutral : Java compiler generates an architecture-neutral object
file format which makes the compiled code to be executable on many

processors, with the presence Java runtime system.


Portable :being architectural neutral and having no implementation dependent
aspects of the specification makes Java portable. Compiler and Java is written

in ANSI C with a clean portability boundary which is a POSIX subset.


Robust :Java makes an effort to eliminate error prone situations by

emphasizing mainly on compile time error checking and runtime checking.


Multi-threaded : With Java's multi-threaded feature it is possible to write
programs that can do many tasks simultaneously. This design feature allows

developers to construct smoothly running interactive applications.


Interpreted :Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is more
rapid and analytical since the linking is an incremental and light weight

process.
High Performance: With the use of Just-In-Time compilers Java enables high

performance.
Distributed :Java is designed for the distributed environment of the internet.
Dynamic : Java is considered to be more dynamic than C or C++ since it is
designed to adapt to an evolving environment. Java programs can carry

37

extensive amount of run-time information that can be used to verify and


resolve accesses to objects on run-time.
6. Expalin in detail about Data types in java. (4m) [N/D2014]
Data type specifies the size and type of values that can be stored in an identifier.
The Java language is rich in its data types. Different data types allow you to select the
type appropriate to the needs of the application.
Data types in Java are classified into two types:
1. Primitivewhich include Integer, Character, Boolean, and Floating Point.
2. Non-primitivewhich include Classes, Interfaces, and Arrays.
Primitive Data Types
1. Integer
Integer types can hold whole numbers such as 123 and 96. The size of the values that
can be stored depends on the integer type that we choose.

2. Floating Point
Floating point data types are used to represent numbers with a fractional part.
Single precision floating point numbers occupy 4 bytes and Double precision floating
point numbers occupy 8 bytes. There are two subtypes:

38

3. Character
It stores character constants in the memory. It assumes a size of 2 bytes, but
basically it can hold only a single character because char stores unicode character sets.
It has a minimum value of u0000 (or 0) and a maximum value of uffff (or 65,535,
inclusive).
4. Boolean
Boolean data types are used to store values with two states: true or false.
Java Tokens
A token is the smallest element in a program that is meaningful to the compiler.
These tokens define the structure of the language. The Java token set can be divided
into five categories: Identifiers, Keywords, Literals, Operators, and Separators.
1. Identifiers
Identifiers are names provided by you. These can be assigned to variables,
methods, functions, classes etc. to uniquely identify them to the compiler.
2. Keywords
Keywords are reserved words that have a specific meaning for the compiler.
They cannot be used as identifiers. Java has a rich set of keywords. Some examples
are: boolean, char, if, protected, new, this, try, catch, null, threadsafe etc.
3. Literals
Literals are variables whose values remain constant throughout the program.
They are also called Constants. Literals can be of four types. They are:
a. String Literals
String Literals are always enclosed in double quotes and are implemented using
the java.lang.String class. Enclosing a character string within double quotes will
automatically create a new String object. For example, String s = "this is a
39

string";. String objects are immutable, which means that once created, their
values cannot be changed.
b. Character Literals
These are enclosed in single quotes and contain only one character.
c. Boolean Literals
They can only have the values true or false. These values do not correspond to 1
or 0 as in C or C++.
d. Numeric Literals
Numeric Literals can contain integer or floating point values.
5. Operators
An operator is a symbol that operates on one or more operands to produce a
result.
6. Separators
Separators are symbols that indicate the division and arrangement of groups of
code. The structure and function of code is generally defined by the separators. The
separators used in Java are as follows:

parentheses ( ) -

Used to define precedence in expressions, to enclose

parameters in method definitions, and enclosing cast types.

braces { } - Used to define a block of code and to hold the values of arrays.

brackets [ ] - Used to declare array types.

semicolon ; - Used to separate statements.

comma , - Used to separate identifiers in a variable declaration and in the


forstatement.

period . - Used to separate package names from classes and subclasses and to
separate a variable or a method from a reference variable.

Non-primitive datatypes(object references)


1.Classes

40

An object is a collection of variables, associated methods, and other associated


classes. Objects in Java are described by classes; a particular object is an instance of a
particular class. A class describes the behavior of an object by defining methods for the
class and possibly other auxiliary classes.
2.Interfaces
Java provides a construct called an interface to support certain multiple
inheritance features that are desirable in an object-oriented language. An interface is
similar to a class, in that an interface declaration can define both variables and
methods.
3.Arrays
Array is one type of variable which store multiple value with same data type. It
has many dimensions such as one dimension, two dimension, or multidimensional.
Array is non-primitive data type.
Example: int array_variable_name[ ]; //

Variable_array_name = new Datatype[size];

7. Explain about Classes and objects with programming examples.(16m)


[M/J2013]
Objects in Java:

Object - Objects have states and behaviors. Example: A dog has states-color,
name, breed as well as behaviors -wagging, barking, eating. An object is an

instance of a class.
If you compare the software object with a real world object, they have very similar

characteristics.
Software objects also have a state and behavior. A software object's state is
stored in fields and behavior is shown via methods. So in software development,
methods operate on the internal state of an object and the object-to-object
communication is done via methods.

Classes in Java:
A class is a blue print from which individual objects are created.
A sample of a class is given below:
41

public class Dog


{

String breed;
int age;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}

}
A class can contain any of the following variable types.

Local variables: Variables defined inside methods, constructors or blocks are


called local variables. The variable will be declared and initialized within the

method and the variable will be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside
any method. These variables are instantiated when the class is loaded. Instance
variables can be accessed from inside any method, constructor or blocks of that

particular class.
Class variables: Class variables are variables declared within a class, outside
any method, with the static keyword.

A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods. Below
mentioned are some of the important topics that need to be discussed when looking into
classes of the Java Language,
1) Constructors: Every class has a constructor. If we do not explicitly write a
constructor for a class the Java compiler builds a default constructor for that class.Each
time a new object is created, at least one constructor will be invoked. The main rule of

42

constructors is that they should have the same name as the class. A class can have
more than one constructor.
Example of a constructor is given below:
public class Puppy{
public Puppy(){
}
public Puppy(String name){
// This constructor has one parameter, name.
}
}
Java also supports Singleton Classes where you would be able to create only one
instance of a class.
2) Singleton Classes: The Singleton's purpose is to control object creation, limiting the
number of objects to one only. Since there is only one Singleton instance, any instance
fields of a Singleton will occur only once per class, just like static fields.
Singletons often control access to resources such as database connections or
sockets. For example, if you have a license for only one connection for your database or
your JDBC driver has trouble with multithreading, the Singleton makes sure that only
one connection is made or that only one thread can access the connection at a time.
Implementing Singletons:
Example 1:
The easiest implementation consists of a private constructor and a field to hold its
result, and a static accessor method with a name like getInstance(). The private field
can be assigned from within a static initializer block or, more simply, using an initializer.
The getInstance( ) method (which must be public) then simply returns this instance:

Example

// File Name: SingletonDemo.java


43

public class Singleton{

public lassSingletonDemo{

private static Singleton singleton =new

public staticvoid main(String[] args){

Singleton();

Singleton tmp =Singleton.getInstance();


tmp.demoMethod();

private Singleton(){

/* Static 'instance' method */

Output

public static Singleton getInstance(){

demoMethod for singleton

return singleton;

Creating

an

/* Other methods protected by singleton-

Object:

ness */
protected static void demoMethod()
{
System.out.println("demoMethod for
singleton");
}
}
As mentioned previously, a class provides the blueprints for objects. So basically an
object is created from a class. In Java the new keyword is used to create new objects.
There are three steps when creating an object from a class:

Declaration: A variable declaration with a variable name with an object type.


Instantiation: The 'new' keyword is used to create the object.
Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.

Example

Output

public class Puppy{

PassedNameis:tommy
44

public Puppy(String name){


// This constructor has one parameter,
name.
System.out.println("Passed Name is :"+
name );
}
public static void main(String[]args){
// Following statement would create an
object myPuppy
Puppy myPuppy =new Puppy("tommy");
}
}
Accessing Instance Variables and Methods:
Instance variables and methods are accessed via created objects. To access an
instance variable the fully qualified path should be as follows:
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();
Example

Output

public class Puppy{


PassedName is:tommy
int puppyAge;
Puppy's age is :2
public Puppy(String name){
Variable Value :2
// This constructor has one parameter,
name.
System.out.println("Passed Name is :"+
name );
}
public void setAge(int age ){
puppyAge = age;
}
public int getAge(){
System.out.println("Puppy's age is :"+
puppyAge );
45

return puppyAge;
}
public static void main(String[]args){
/* Object creation */
Puppy myPuppy =newPuppy("tommy");
/* Call class method to set puppy's age */
myPuppy.setAge(2);
/* Call another class method to get puppy's
age */
myPuppy.getAge();
/* You can access instance variable as
follows as well */
System.out.println("Variable
Value
:"+
myPuppy.puppyAge );
}
}
Java Package:
In simple, it is a way of categorizing the classes and interfaces. When developing
applications in Java, hundreds of classes and interfaces will be written, therefore
categorizing these classes is a must as well as makes life much easier.
Import statements:
In Java if a fully qualified name, which includes the package and the class name,
is given, then the compiler can easily locate the source code or classes. Import
statement is a way of giving the proper location for the compiler to find that particular
class. For example,the following line would ask compiler to load all the classes available
in directory
java_installation/java/io
import java.io.*;

8. Explain about dynamic method dispatch with an example. [M/J2016] [8m]

46

Runtime Polymorphism or Dynamic method dispatch


Dynamic method dispatch is a mechanism by which a call to an overridden method is
resolved at runtime. This is how java implements runtime polymorphism. When an
overridden method is called by a reference, java determines which version of that
method to execute based on the type of object it refer to. In simple words the type of
object which it referred determines which version of overridden method will be called.

When Parent class reference variable refers to Child class object, it is known as
Upcasting
class Game
{
public void type()
{ System.out.println("Indoor & outdoor"); }
}
Class Cricket extends Game
{
public void type()
{ System.out.println("outdoor game"); }
public static void main(String[] args)
{
Game gm = new Game();
Cricket ck = new Cricket();
gm.type();
ck.type();
gm=ck;
//gm refers to Cricket object
gm.type(); //calls Cricket's version of type
47

}
}
Output :
Indoor & outdoor
Outdoor game
Outdoor game
Notice the last output. This is because of gm = ck; Now gm.type() will call Cricket
version of type method. Because here gm refers to cricket object.

9. Implement a class Student. A student has a name and a total quiz score. Supply
an appropriate constructor and methods getName(), addQuiz(int score),
getTotalScore(), and getAverageScore(). To compute the latter, you also need to
store the number of quizzes that the student took. [M/J2016][10m]

Implement a class Student. For the purpose of this exercise, a student has a name and
a total quiz score. Supply an appropriate constructor and methods getName(),
addQuiz(int score), getTotalScore(), and getAverageScore(). To compute the latter, you
also need to store the number of quizzes that the student took.
Now from what we understand, this is what each method should do:
getName() gets the name of the student
addQuiz(int score) adds another score of a quiz (for example the student has an initial
85, and then the methods gets used to add a 95, so that's 2 quizzes now)
getTotalScore() adds all the scores of the quizzes together (for example 85 + 95) and
returns that total
getAverageScore() returns the average score of all the quizzes (such as ((85 + 95) / 2) )
I'm having trouble implement the method getAverageScore(), how would I store the
number of quizzes that the student took?
Here is the code so far:
Code:
public class Student
{
// instance variables
private String name;
48

private double quizScore;


/**
* Constructs a Student object with a name "RickyBobby" and zero total quiz score
*/
public Student()
{
name = "RickyBobby";
quizScore = 0;
}
/**
* Constructs a Student object with an initial name and total quiz score
*/
public Student(String pName, double pQuizScore)
{
name = pName;
quizScore = pQuizScore;
}
/**
* Returns the name of a student
*
* @return the name of the student
*/
public String getName()
{
return name;
}
/**
* Adds a quiz score to the total quiz score of the student
*
* @param score the score of a quiz
*/
public void addQuiz(int score)
{
quizScore = quizScore + score;
}
/**
* Returns the total score of all the quizzes combined of the student
*
* @return
the value of quizScore
*/
public double getTotalScore()
{
49

return quizScore;
}
/**
* Returns the average score of all the quizzes a student took
*
* @return
*/
public double getAverageScore()
{
//getAverageScore code goes here
}
}

10. Distinguish between instance method and class method with an example?
[M/J2016] [6m]
Class methods are methods which are declared as static. The method can be
called without creating an instance of the class. Class methods can only operate
on class members and not on instance members as class methods are unaware
of instance members. Instance methods of the class can also not be called from
within a class method unless they are being called on an instance of that class.

Java static method example


This Java Example shows how to declare and use static methods inside
a java class.
public class StaticMethodExample {
public static void main(String[] args) {
int result = MathUtility.add(1, 2);
System.out.println("(1+2) is : " + result);
}
}

50

class MathUtility{
/*
* To declare static method use static keyword.
* Static methods are class level methods and can not access any instance
* member directly. However, it can access members of a particular object
* using its reference.
* Static methods are generally written as a utility method or it performs
* task for all objects of the class.
*/

public static int add(int first, int second)


{
return first + second;
}
}

Instance methods on the other hand require an instance of the class to exist before they
can be called, so an instance of a class needs to be created by using the new keyword.
Instance methods operate on specific instances of classes. Instance methods are not
declared as static.
Example of instance method and instance variable
class Circle
{
// Instance Variables
51

double x;
double y;
double radius;

// Instance Method
void scale(double a)
{
radius *= a;
}
}

11. Explain the concept of method overriding with example? How the parameters are
specified in methods. (16m) [M/J2012]
Method overriding
If a class inherits a method from its superclass, then there is a chance to override
the method provided that it is not marked final. The benefit of overriding is: ability to
define a behavior that's specific to the subclass type which means a subclass can
implement a parent class method based on its requirement. In object-oriented terms,
overriding means to override the functionality of an existing method.
Example:
classAnimal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and

This would produce the following result:


Animals can move
Dogs can walk and run

52

run");
}
}
public class TestDog{
public static void main(String args[]){
Animal a =new Animal();// Animal
reference and object
Animal b =new Dog();// Animal reference
but Dog object
a.move();// runs the method in Animal
class
b.move();//Runs the method in Dog class
}
}

In the above example, you can see that the even though b is a type of Animal it runs the
move method in the Dog class. The reason for this is: In compile time, the check is
made on the reference type. However, in the runtime, JVM figures out the object type
and would run the method that belongs to that particular object. Therefore, in the above
example, the program will compile properly since Animal class has the method move.
Then, at the runtime, it runs the method specific for that object.
Example:

public class TestDog{

class Animal{

public static void main(String args[]){

public void move(){

Animal

System.out.println("Animals can move");

reference and object

Animal b =new Dog();// Animal reference

but Dog object

class Dog extendsAnimal{

a.move();// runs the method in Animal

public void move(){

class

=new

Animal();//

Animal

System.out.println("Dogs can walk and b.move();//Runs the method in Dog class


run");

b.bark();

public void bark(){

53

System.out.println("Dogs can bark");

Output

TestDog.java:30: cannot find symbol

symbol : method bark()


location:class Animal
b.bark();

^
This program will throw a compile time error since b's reference type Animal doesn't
have a method by the name of bark.
Rules for method overriding:

The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in

the original overridden method in the superclass.


The access level cannot be more restrictive than the overridden method's access
level. For example, if the superclass method is declared public, then the

overriding method in the subclass cannot be either private or protected.


Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited, then it cannot be overridden.
A subclass within the same package as the instance's superclass can override

any superclass method that is not declared private or final.


A subclass in a different package can only override the non-final methods

declared public or protected.


An overriding method can throw any uncheck exceptions, regardless of whether
the overridden method throws exceptions or not. However the overriding method
should not throw checked exceptions that are new or broader than the ones
declared by the overridden method. The overriding method can throw narrower

or fewer exceptions than the overridden method.


Constructors cannot be overridden.

Using the super keyword:


When invoking a superclass version of an overridden method the super keyword is
used.
Example

}
54

class Animal{

public class TestDog{

public void move(){

public static void main(String args[]){

System.out.println("Animals can move");

Animal b =new Dog();// Animal reference

but Dog object

class Dog extends Animal{

b.move();//Runs the method in Dog class

public void move(){

super.move();// invokes the super class }


method

Output

System.out.println("Dogs can walk and Animals can move


run");

Dogs can walk and run

9. Write a Java program for alphabetical ordering of strings.(8m) [M/J2012]


Program:

b[k]=b[k+1];

import java.io.*;

b[k+1]=t;

class AlphabeticalOrder

static String n;

static int l;

System.out.println("\nOriginal word : "

public static void main(String args[]) throws

+n);

IOException

System.out.print("Sorted word : ");

for(int m=0;m<l;m++)

BufferedReader br = new BufferedReader

System.out.print(b[m]);

(new InputStreamReader(System.in));

System.out.print("\n");

System.out.print("Enter a word : ");

n = br.readLine();

l = n.length();
alphabetical();

Output:

Enter a word : computer

public static void alphabetical()

Original word : computer


55

Sorted word : cemoprtu

char b[] = new char[l];


for(int i=0;i<l;i++)
b[i] = n.charAt(i);
char t;
for(int j=0;j<l-1;j++)
{
for(int k=0;k<l-1-j;k++)
{
if(b[k]>b[k+1])
{
t=b[k];

56

Вам также может понравиться