Академический Документы
Профессиональный Документы
Культура Документы
COMPILED BY
M.KARTHIKEYAN, M.E., (AP/IT)
VERIFIED BY
HOD
PRINCIPAL
CORRESPONDENT
UNIT IV
OVERVIEW OF JAVA
Data types
Variables and arrays
Operators
Control statements
Classes and Objects
Methods
Inheritance
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
Secured
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.
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
10
11
12
13
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:
15
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:
true
class Vehicle {}
Output:
true
17
18
Methods, Variables and Constructors that are declared private can only be
cannot be private.
Variables that are declared private can be accessed outside the class if public
Example:
The following class uses private access control:
public class Logger {
private String format;
public String getFormat() {
return this.format;
}
19
A class, method, constructor, interface etc declared public can be accessed from
any other class. Therefore fields, methods, blocks declared inside a public class
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
20
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
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:
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
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:
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
23
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:
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
24
//Statements
}
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:
Output:
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:
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
This is if statement
Example:
output
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
Example:
output
29
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
When the variable being switched on is equal to a case, the statements following
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
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");
}
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()
{
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!!
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,
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
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 ( ) -
braces { } - Used to define a block of code and to hold the values of arrays.
period . - Used to separate package names from classes and subclasses and to
separate a variable or a method from a reference variable.
40
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
String breed;
int age;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
A class can contain any of the following variable types.
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
public lassSingletonDemo{
Singleton();
private Singleton(){
Output
return singleton;
Creating
an
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:
Example
Output
PassedNameis:tommy
44
Output
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.*;
46
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
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.
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.
*/
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
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:
class Animal{
Animal
class
=new
Animal();//
Animal
b.bark();
53
Output
^
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
}
54
class Animal{
Output
b[k]=b[k+1];
import java.io.*;
b[k+1]=t;
class AlphabeticalOrder
static String n;
static int l;
+n);
IOException
for(int m=0;m<l;m++)
System.out.print(b[m]);
(new InputStreamReader(System.in));
System.out.print("\n");
n = br.readLine();
l = n.length();
alphabetical();
Output:
56