Unit 4 - Mahalakshmi Engineering College

advertisement
QUESTION BANK
DEPARTMENT:EEE
SEMESTER: V
SUBJECT CODE / Name: CS2311 – OBJECT ORIENTED PROGRAMMING
UNIT – IV
PART - A (2 Marks)
1. Is JVM’s platform independent? Justify. (AUC MAY 2013)
JVM refers Java Virtual Machine. JVM is a program which will convert byte code
instructions into machine language instructions understandable by Micro processor. Java
program write once, later on run anywhere.
JVM is a system dependent, because it was developed in C language, where as class
file is a system independent.
2. How do we allocate an array dynamically in Java? (AUC MAY 2013)
An array can be created dynamically with an initializer.
For ex:
int numbers[] = {1, 2, 4, 8, 16, 32, 64, 128};
This syntax dynamically creates an array and initializes its elements to the specified values.
3. Why is Java called as ‘robust’? (AUC DEC 2012)
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.
4. What is byte code?(AUC MAY 2012)
Bytecode is nothing but the intermediate representation of Java source code which is
produced by the Java compiler by compiling that source code. This byte code is an machine
independent code.
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
5. What are packages?(AUC MAY 2012)
Packages are java’s way of grouping a variety of classes and/or interfaces together. Packages
are container for the classes . It is the header file in c++.
It is stored in a hierarchical manner. If we want to use the packages in a class, we want to
import it
6. What is an abstract class? (AUC DEC 2011)
An abstract class is a class that is declared abstract—it may or may not include
abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
public abstract class GraphicObject
{
// declare fields
// declare non-abstract methods
abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all
of the abstract methods in its parent class. However, if it does not, the subclass must also be
declared abstract.
7. Under which contexts would you use ‘final’ and ‘finalize’. (AUC DEC 2011)
‘final’ - To restrict the user from further access.
finalize () method is used just before an object is destroyed and can be called just prior to
garbage collection
8. What are different types of access modifiers (Access specifiers)?(AUC DEC
2010)
Access specifiers are keywords that determine the type of access to the member of a
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
class. These keywords are for allowing privileges to parts of a program such as functions and
variables. These are:
public: Any thing declared as public can be accessed from anywhere.
private: Any thing declared as private can’t be seen outside of its class.
protected: Any thing declared as protected can be accessed by classes in the same package
and subclasses in the other packages.
default modifier : Can be accessed only to classes in the same package.
9. What is the purpose of getBytes() method? (AUC DEC 2010)
This method has following two forms:
getBytes(String charsetName): Encodes this String into a sequence of bytes using the
named charset, storing the result into a new byte array.
getBytes(): Encodes this String into a sequence of bytes using the platform's default
charset, storing the result into a new byte array.
10. Java is platform independent language. Justify.
Platform is the hardware or system software environment in which your program
runs. Moreover java language run by any operating system, thats why java is called platform
independent languages.
11. What are features of java
Simple
Object Oriented
Distributed
Interpreted
Robust
Secure
Architecture-Neutral
Portable
High Performance
Multithreaded
Dynamic Language
12. What are features does not supported by java?
Goto statement
Multiple inheritance
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
Operator overloading
Structures and Unions allowed
Pointers
13. Define Garbage Collection in Java?
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.
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. Explain the usage of Java packages.
This is a way to organize files when a project consists of multiple modules. It also helps
resolve naming conflicts when different packages have classes with the same names.
Packages access level also allows you to protect data from being used by the non-authorized
classes.
16. What is Static member classes?
A static member class is a static member of a class. Like any other static method, a
static member class has access to all static methods of the parent, or top-level, class.
17. Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computing machine which
first converts .java file into .class file by using Compiler (.class is nothing but byte code file.)
and Interpreter reads byte codes.
18. What is the difference between this() and super()?
this() can be used to invoke a constructor of the same class whereas super()
can be used to invoke a super class constructor.
19. What is meant by abstraction?
Abstraction defines the essential characteristics of an object that distinguish it from all
other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative
to the perspective of the viewer. Its the process of focussing on the essential characteristics
of an object. Abstraction is one of the fundamental elements of the object model.
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
20. What is the difference between String and String Buffer?
a) String objects are constants and immutable whereas StringBuffer objects are not.
b) String class supports constant strings whereas StringBuffer class supports growable and
modifiable strings.
PART – B (16 Marks)
1. Write a Java program using arrays to do the following.
(i)to copy one array content to another array.
(ii)to arrange the numbers in ascending order.
(iii)find the maximum of an array (AUC MAY 2013)
Program to search an element in an array
import java.io.*;
class arr
{
public static void main(String arg[])
{
int a[]=new int[10];
int b[]=new int[10];
DataInputStream ins=new DataInputStream(System.in);
int i,n=0,q=0;
System.out.print("Enter no. of elements ");
n=Integer.parseInt(ins.readLine());
System.out.println("Enter elements ");
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(ins.readLine());
}
//copying
for(i=0;i<n;i++)
{
b[i]=a[i];
}
//maximum of array
int big=a[0];
for(i=0;i<n;i++)
{
if(a[i]>big)
big=a[i];
}
System.out.println("Maximum element: "+big);
//searching
System.out.println("Enter element to be searched ");
q=Integer.parseInt(ins.readLine());
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
for(i=0;i<n;i++)
{
if(a[i]==q)
System.out.println("Element found at "+(i+1)+" position");
}
//sorting
for(i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println(“Ascending order”);
for(i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}
2. (i)Write a simple java program to find a given string in a string array. (8)
import java.util.Arrays;
public class StringArrayContainsExample
{
public static void main(String args[]
{
//String array
String[] strMonths = new String[]{"January", "February", "March", "April", "May"};
//Strings to find String
strFind1 = "March"; String
strFind2 = "December";
boolean contains = false;
//iterate the String array
for(int i=0; i < strMonths.length; i++)
{
//check if string array contains the string
if(strMonths[i].equals(strFind1))
{
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
//string found
contains = true;
break;
}
}
if(contains)
{
System.out.println("String array contains String " + strFind1);
}
else
{
System.out.println("String array does not contain String " + strFind1);
}
}
}
(ii)Write a Java program to split a string into multiple java string objects. (8)
(AUC MAY 2013)
import java.util.Arrays;
import java.util.regex.Pattern;
public class StringManipulation {
public static void main(String[] args) {
String str = "red,green,blue,yellow,pink"; String[] splitArr =
Pattern.compile(",").split(str); System.out.println("\nOriginal
String: " + str); System.out.println("Split Array: " +
Arrays.toString(splitArr) + "\n");
}
}
3. (i) Explain about various string operations in Java. (8)
The Java String class (java.lang.String) is a class of object that represents a
character array of arbitrary length. While this external class can be used to handle string
objects,
Java
integrates
internal,
built-in strings
into the
language.
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
An important attribute of the String class is that once a string object is
constructed, its value cannot change (note that it is the value of an object that cannot
change, not that of a string variable, which is just a reference to a string object). All String
data members are private, and no string method modifies the string’s value.
String Methods
Although a string represents an array, standard array syntax cannot be used to inquire into
it. These are detailed in the below Table.
String Comparison
String comparison methods listed in below Table.
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
String Searching
The String class also provides methods that search a string for the occurrence of a
single character or substring. These return the index of the matching substring or
character if found, or - 1 if not found.
int indexOf (char ch)
int indexOf (char ch, int begin)
int lastIndexOf (char ch)
int lastIndexOf (char ch, int fromIndex)
int indexOf (String str)
int indexOf (String str, int begin)
int lastIndexOf (String str)
int lastIndexOf (String str, int fromIndex)
The following example shows the usage of these functions
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
String Concatenation
The String class provides a method for concatenating two strings: String concat
(String otherString)
The + and += String operators are more commonly used: The Java compiler
recognizes the + and += operators as String operators. For each + expression, the
compiler generates calls to methods that carry out the concatenation. For each +=
expression, the compiler generates calls to methods that carry out the concatenation
and assignment.
Converting Objects To Strings
The String + operator accepts a non-string operand, provided the other operand
is a string. The action of the + operator on non-string operands is to convert the nonstring to a string, then to do the concatenation. Operands of native types are converted
to string by formatting their values. Operands of class types are converted to a string by
the method toString() that is defined for all classes. Any object or value can be converted
to a string by explicitly using one of the static valueOf() methods defined in class String:
String str = String.valueOf (obj); If the argument to valueOf() is of class type, then
valueOf() calls that object’s toString() method. Any class can define its own toString()
method, or just rely on the default. The output produced by toString() is suitable for
debugging and diagnostics. It is not meant to be an elaborate text representation of the
object, nor is it meant to be parsed. These conversion rules also apply to the right-hand
side of the String += operator.
Converting Strings To Numbers
Methods from the various wrapper classes, such as Integer and Double, can be used to
convert numerical strings to numbers.
The wrapper classes contain static methods such as parseInt() which convert a
string to its own internal data type.
(ii) Write a Java program to find the maximum number of the given array. (8)
(AUC DEC 2012)
[refer Q.No.1]
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
4. (i) Explain about packages in Java. (8)
Packages are java’s way of grouping a variety of classes and/or interfaces together. Packages are
container for the classes . It is the header file in c++.
It is stored in a hierarchical manner. If we want to use the packages in a class, we want to import it.
The two types of packages are:
1.System package.
2.User defined package.
Uses of Packages:
Packages reduce the complexity of the software because a large number of classes can be grouped
into a limited number of packages.
We can create classes with same name in different packages.
Using packages we can hide classes.
Java API Packages
Using system packages.
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
We may like to use many of the classes contained in a package.it can be achieved by:
Import packagename .classname
Or
Package name
Import packagename.*
Creating the package
To create our own packages
packagefirstpackage;// package declaration
public class FirstClass //class definition
,…..
(body of class)
…….The file is saved as FirstClass.java,located at firstpackage directory. when it is compiled .class file will
be created in same directory.
Access a package
The import statement can be used to search a list of packages for a particular class. The general form
of import statement for searching class is a as follows.
Import package1 [.package2] [.package3].classname;
Using the package
package package1 ;
public class classA
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
{
public void displayA()
{
System.out.println(“class A”);
}
}
Adding a class to package
Define the class and make it public, Place the package statement
Package P1
Before the class definition as follows
Package p1;
Public class B{
// body of B
}
Example:
Package college
Class student
{
Int
regno; String
name;
Student(intr,stringna);
{ Regno=r
Name=na
}
Public void print()
{
System.out.println(“Regno”+regno );
System.out.println(“Name”+name );
}
}
Package Course
Class engineering
{ Intregno;
String branch;
String year;
Engineering(int r, string br, string yr)
{
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
Regno=br;
Branch=br;
Year=yr;
}
public void print()
{
Systems.out.println(“Regno”+regno);
Systems.out.println(“Branch”+branch);
Systems.out.println(“Year”+year);
}
}
import college.*;
import course.*;
Class demo
{
Public static void main(string args[])
{
Student sl=new Engineering(1,”CSE”,”III Year”);
Sl.print();
El.print();
}
}
(ii) Write a program to convert an Integer array to String. (8) (AUC DEC 2012)
toString method:
public static String toString(Object[] a)
Returns a string representation of the contents of the specified array. If the array contains other
arrays as elements, they are converted to strings by the Object.toString() method inherited from
Object, which describes their identities rather than their contents.
The value returned by this method is equal to the value that would be returned by
Arrays.asList(a).toString(), unless a is null, in which case "null" is returned.
Parameters:
a - the array whose string representation to return
Returns:
a string representation of a
import java.util.Arrays;
public class ConvertIntArrayToStringExample {
public static void main(String args[]){
//int array
int[] intNumbers = new int[]{1, 2, 3, 4, 5};
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
//create new StringBuffer object
StringBuffer sbfNumbers = new StringBuffer();
//define the separator you want in the string. This example uses space.
String strSeparator = " ";
if(intNumbers.length > 0){
sbfNumbers.append(intNumbers[0]);
for(int i=1; i < intNumbers.length; i++)
{
sbfNumbers.append(strSeparator).append(intNumbers[i]);
}
}
System.out.println("int array converted to String using for loop");
//finally convert StringBuffer to String using toString method
System.out.println(sbfNumbers.toString());
String strNumbers = Arrays.toString(intNumbers);
System.out.println("String generated from Arrays.toString method: " + strNumbers);
//you can use replaceAll method to replace brackets and commas
strNumbers = strNumbers.replaceAll(", ", strSeparator).replace("[", "").replace("]", "");
System.out.println("Final String: " + strNumbers);
}
}
5. Write a Java program to create two single dimensional array, initialize them
and add them, store the result in another array.(AUC MAY 2012)
import java.io.*;
class arr
{
public static void main(String arg[])
{
int a[]=new int[10];
int b[]=new int[10];
int sum[]=new sum[10];
DataInputStream ins=new DataInputStream(System.in);
int i,n=0,q=0;
System.out.print("Enter no. of elements ");
n=Integer.parseInt(ins.readLine());
System.out.println("Enter elements of first array ");
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(ins.readLine());
}
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
System.out.println("Enter elements of second array ");
for(i=0;i<n;i++)
{
b[i]=Integer.parseInt(ins.readLine());
}
//array addition
for(i=0;i<n;i++)
{
sum[i]=a[i]+b[i];
}
System.out.println(“Array sum:”);
for(i=0;i<n;i++)
{
System.out.println(sum[i]);
}
}}
6. Write a Java program to perform all string operations using String class. (AUC
MAY 2012)
[Refer Q.No 3(i)]
7. (i) Describe the structure of typical Java program and give the steps to execute
it.(10)
JAVA Program structure
A file containing Java source code is considered a compilation unit. Such a compilation unit contains
a set of classes and, optionally, a package definition to group related classes together. Classes
contain data and method members that specify the state and behavior of the objects in your
program. Java programs come in two flavors:
1. Standalone applications that have no initial context such as a pre-existing main window
2. Applets for WWW programming
Execution begins when you launch the java virtual machine and tell it to find a particular class. After
finding the class, java executes the enclosed main() method with signature: public static void
main(String*+ args) , ………... -
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
Program Execution
Create a source code file using a text editor. The source code is then compiled using the java
compiler javac. Each java program is converted into one or more class files. The content of the class
file is a set of instructions called bytecode to be executed by Java Virtual Machine (JVM).Java
introduces bytecode to create platform independent program. JVM is an interpreter for bytecode
which accepts java bytecode and produces result.
(ii)Explain the importance of JVM in JRE. (6) (AUC DEC 2011)
[Refer Q.No 10]
8. (i) Create a Complex number class in Java. The class should have a
constructor and methods to add, subtract and multiply two complex numbers,
and to return the real and imaginary parts. (10)
class Complex
{
private double real;
private double imaginary;
public String toString() {
// We could use a DecimalFormat object here to make the
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
// String representation of the doubles more compact.
return real + " + " + imaginary + "*i";
}
}
public class ComplexDemo {
public static void main(String[] args) {
// Test the no-arg constructor, setter, and toString methods
Complex c1 = new Complex();
System.out.println("Zero: " + c1);
c1.setRealPart(1.0);
c1.setImaginaryPart(2.5);
System.out.println("After setting real and imaginary parts: " + c1);
// Test the getter methods
System.out.println("Real part is: " + c1.getRealPart());
System.out.println("Imaginary part is: " + c1.getImaginaryPart());
// Test the other two constructors Complex
c2 = new Complex(-7.5);
System.out.println("A real number: " + c2);
Complex c3 = new Complex(5.0, 2.0);
System.out.println("Another complex number: " + c3);
// Test the arithmatic ops
System.out.println("(" + c1 + ") + (" + c2 + ") = " +
Complex.add(c1, c2));
System.out.println("(" + c1 + ") - (" + c2 + ") = " +
Complex.subtract(c1, c2));
System.out.println("(" + c2 + ") - (" + c1 + ") = " +
Complex.subtract(c2, c1));
System.out.println("(" + c2 + ") * (" + c3 + ") = " +
Complex.multiply(c2, c3));
System.out.println("(" + c1 + ") * (" + c3 + ") = " +
Complex.add(c1, c3));
}
}
(ii)What are packages? How are they created and used? (AUC DEC 2011)
[Refer Q.No: 4(i)
9. Write a menu based java program that can calculate the area of a triangle,
circle or square, based on the user’s choice. (AUC DEC 2010)
import rand.*;
import java.io.*;
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
class pk4
{
public static void main(String ar[])throws IOException
{
chpackage c=new chpackage();
c.put("AREA OF VARIOUS GEOMETRICAL FIGURES");
{
c.put("MAIN MENU");
c.put("1.Area of circle");
c.put("2.Area of triangle");
c.put("3.Area of cylinder");
c.put("4.Area of square");
c.put("5.Exit");
c.put("Enter your choice");
int sn=Integer.parseInt(c.read());
switch(sn)
{
case 1:
{
double r,area; c.put("Enter the
radius");
r=Double.parseDouble(c.read());
area=3.14*r*r;
c.put("The area of circle"+area);
break;
}
case 2:
{
double b,h,area; c.put("Enter the
breath");
b=Double.parseDouble(c.read());
c.put("Enter the height");
h=Double.parseDouble(c.read());
area=0.5*b*h;
c.put("The area of circle"+area);
break;
}
case 3:
{
double r,h,area; c.put("Enter the
radius");
r=Double.parseDouble(c.read());
c.put("Enter the height");
h=Double.parseDouble(c.read());
area=3.14*r*r*h;
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
c.put("The area of cylinder"+area);
break;
}
case 4:
{
int si,area;
c.put("Enter the side");
si=Integer.parseInt(c.read());
area=si*4;
c.put("The area of square"+area);
break;
}
case 5:
{
}
}
}
}
}
10. Explain the Virtual Machine concept with reference to Java. (AUC DEC 2010)
A Java Virtual Machine (JVM) is a set of computer software programs and data structures
that use a virtual machine model for the execution of other computer programs and scripts.
The model used by a JVM accepts a form of computer intermediate language commonly
referred to as Java bytecode. This language conceptually represents the instruction set of a stack-
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
oriented, capability architecture. Sun claims there are over 4.5 billion JVM-enabled devices.
Java Virtual Machines operate on Java bytecode, which is normally (but not necessarily)
generated from Java source code; a JVM can also be used to implement programming languages
other than Java. For example, Ada source code can be compiled to Java bytecode, which may then
be executed by a JVM. JVMs can also be released by other companies besides Sun (the developer of
Java) - JVMs using the "Java" trademark may be developed by other companies as long as they
adhere to the JVM specification published by Sun (and related contractual obligations).
The JVM is a crucial component of the Java Platform. Because JVMs are available for many
hardware and software platforms, Java can be both middleware and a platform in its own right hence the trademark write once, run anywhere. The use of the same bytecode for all platforms
allows Java to be described as "compile once, run anywhere", as opposed to "write once, compile
anywhere", which describes cross-platform compiled languages. The JVM also enables such features
as Automated Exception Handling that provides 'root-cause' debugging information for every
software error (exception) independent of the source code.
The JVM is distributed along with a set of standard class libraries that implement the Java API
(Application Programming Interface). An application programming interface is what a computer
system, library or application provides in order to allow data exchange between them. They are
bundled together as the Java Runtime Environment.
11. What is javaDoc? Explain the comments for classes, methods, fields and link.
The basic structure of writing document comments is embed them inside /** ... */.
The Javadoc is written next to the items without any separating newline. The class declaration
usually contains:
/**
* @author FirstnameLastname<address @ example.com>
* @version 1.6 (The Java version used)
* @since 2010.0331 (E.g. ISO 8601 YYYY.MMDD)
*/
public class Test {
// class body
}
For methods there is
(1) a short, concise, one line description to explain what the itemdoes. This is followed by
[2] a longer description that may span in multiple paragraphs. In those the details can be explained
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
in full. This section, marked in brackets [], is optional.
(3) a tag section to list the accepted input arguments and return values of the method.
/**
* Short one line description.
*
* Longer description. If there were any, it would be
* here.
*
* @param variable Description text texttext.
* @return Description text texttext.
*/
Variables are documented similarly to methods with the exception that part (3) is omitted. Here the
variable contains only the short description:
/**
* Description of the variable here.
*/
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
12. Write about static members of java.
A class member must be accessed only in conjunction with an object of its class. However, it is
possible to create a member that can be used by itself, without reference to a specific instance.
To create such a member, precede its declaration with the keyword static. When a member is
declared static, it can be accessed before any objects of its class are created, and without reference
to any object.
Declare both methods and variables to be static. The most common example of a static member is
main ( ).
main ( ) is declared as static because it must be called before any objects exist.
Instance variables declared as static are global variables. When objects of its class are declared, no
copy of a static variable is made. Instead, all instances of the class share the same static variable.
Methods declared as static have several restrictions:
They can only call other static methods.
They must only access static data.
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
They cannot refer to this or super in any way.
Example:
class box
{
static double w = 3;
static double h;
static void vol(int x)
{
System.out.println("x = " + x);
System.out.println("w = " + w);
System.out.println("h = " + h);
}
static
{
System.out.println("Static block initialized.");
h = w * 4;
}
public static void main(String args[])
{
vol(42);
}
}
Output:
Static block initialized.
x = 42
w=3
h = 12
box class is loaded, all of the static statements are run. First, w is set to 3, then the static block
executes (printing a message), and finally, h is initialized to w * 4 or 12. Then main ( ) is called, which
calls vol( ), passing 42 to x.
The three println( ) statements refer to the two static variables w and h, as well as to the local
variable x.
To call a static method from outside its class, the general form is:
classname.method( )
Classname is the name of the class in which the static method is declared.
class box
{
static double w = 42;
static double h = 99;
static void vol()
{
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
System.out.println("w = " + w);
}
}
class ex
{
public static void main(String args[])
{
box.vol();
System.out.println("h = " + box.h);
}
}
Output:
w = 42
h = 99
13. Write down the basic features of Java.
Simple:
Java is a small and simple language. Many features of C and C++ that are either redundant or
source of unreliable code are not part of java.
Java does not use pointer, header files, goto statement and many others. It also eliminates
operator overloading and multiple inheritance.
Secure:
Security becomes an important issue for a language that is used for programming on
Internet. Threat of viruses and abuse of resources is everywhere.
Java systems not only verify all memory access but also ensure that no viruses are
communicated with an applet.
The absence of pointers in Java ensures that programs cannot gain access to memory
locations without proper authorization.
Platform independent and Portable:
The most significant contribution of Java over other languages is its portability. Java
programs can be easily moved from one computer system to another, anywhere and anytime.
Changes and upgrades in operating systems, processors and system resources will not force any
changes in Java programs.
Java ensures portability in two ways. First, Java compiler generates bytecode instructions
that can be implemented on any machine. Secondly, the sizes of the primitive data types are
machine-independent.
Object oriented:
Java is a pure object-oriented language. Almost everything in Java is an object. All program
code and data reside within objects and classes.
Java comes with an extensive set of classes, arranged in packages, that we can use in our
programs by inheritance. The object model in Java is simple and easy to extend.
Robust:
Java is a robust language. It provides many safeguards to ensure reliable code. It has trict
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
compile time and run time checking for data types. It is designed as a garbage-collected language
relieving the programmers virtually all memory management problems.
Java also incorporates the concept of exception handling which captures series errors and
eliminates any risk of crashing the system.
Multithreaded:
Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded
programs, so no need to wait for the application to finish one task before beginning another.
For example
We can listen to an audio clip while scrolling a page and at the same time download an
applet from a distant computer. This feature greatly improves the interactive performance of
graphical applications.
Architecture neutral:
The main issues are code longevity and portability.Operating system upgrades, processor
upgrades, and changes in core system resources can all combine and make program malfunction.
To overcome this problem (JVM) Java Virtual Machine is used. Main goal is “write once; run
anywhere, any time, forever.”
Interpreted:
A computer language is either compiled or interpreted. Java combines both these
approaches thus making Java a two-stage system.
First, Java compiler translates source code into bytecode instructions. Bytecodes are not
machine instructions , in the second stage, Java interpreter generates machine code that can be
directly executed by the machine.
High performance:
Java performance is impressive for an interpreted language, mainly due to the use of
intermediate bytecode.Java architecture is also designed to reduce overheads during runtime.
Distributed:
Java is designed as a distributed language for creating applications on networks. It has the
ability to share data and programs.
Java applications can open and access remote objects on Internet as easily as they can do in
a local system.This enables multiple programmers at multiple remote locations to collaborate and
work together on a single project.
Dynamic:
Java is a dynamic language. It can dynamically linking in new class libraries, methods and
objects.
Java can also determine the type of class through a query, making it possible to either
dynamically link or abort the program, depending on the response.
14. Explain about the constructors in Java.
Constructors have the same name as the class itself. They do not specify a return type, not even
void. This is because they return the instance of the class itself.
Rewrite the Box example so that the dimensions of a box are automatically initialized when an
object is constructed. To do so, replace setDim( ) with a constructor.
class Box
{
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
double width;
double height;
double depth;
Box()
{
System.out.println ("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
double volume()
{
return width * height * depth;
}
}
class BoxDemo6
{
public static void main(String args[])
{
Box b1 = new Box();
Box b2 = new Box();
double vol;
vol = b1.volume();
System.out.println("Volume is " + vol);
vol = b2.volume();
System.out.println("Volume is " + vol);
}
}
When this program is run, it generates the following results:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
Both b1 and b2 were initialized by the Box ( ) constructor when they were created. Since the
constructor gives all boxes the same dimensions,10 by 10 by 10, both b1 and b2 will have the same
volume.
The println ( ) statement inside Box ( ) is for the sake of illustration only. Most constructors will not
display anything. They will simply initialize an object.
Allocate an object, use the following general form:
class-var = new classname( );
What is actually happening is that the constructor for the class is being called. Thus, in the line
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
Box b1 = new Box ();
new Box( ) is calling the Box( ) constructor. When you do not explicitly define a constructor for a
class, then Java creates a default constructor for the class.
The default constructor automatically initializes all instance variables to zero. The default
constructor is often sufficient for simple classes, but it usually won’t do for more sophisticated ones.
Once you define your own constructor, the default constructor is no longer used.
Parameterized Constructors:
While the Box( ) constructor in the preceding example does initialize a Box object, it
is not very useful—all boxes have the same dimensions.
To construct Box objects of various dimensions. The easy solution is to add parameters
to the constructor.
For example, the following version of Box defines a parameterized constructor which sets
the dimensions of a box as specified by those parameters.
class Box
{
double width;
double height;
double depth;
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
double volume()
{ return width * height * depth;
}
}
class BoxDemo7
{
public static void main(String args[])
{
Box b1 = new Box(10, 20, 15);
Box b2 = new Box(3, 6, 9);
double vol;
vol = b1.volume();
System.out.println("Volume is " + vol);
vol = b2.volume();
System.out.println("Volume is " + vol);
}
}
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
Output:
Volume is 3000.0
Volume is 162.0
Each object is initialized as specified in the parameters to its constructor. For example, in the
following line,
Box b1 = new Box (10, 20, 15);
the values 10, 20, and 15 are passed to the Box( ) constructor when new creates the object. Thus,
b1’s copy of width, height, and depth will contain the values 10, 20, and 15, respectively.
CS2311 OBJECT ORIENTED PROGRAMMING - -UNIT IV / V Sem EEE
Download