Java QB
Java QB
Ans The access specifiers in java specify accessibility (scope) of a data member,
method, constructor or class. There are 5 types of java access specifier:
• public
• private
• default (Friendly)
• protected
• private protected
Applet cannot run any program from local Application can run any program from local
computer. computer.
Q.Write all primitive data types available in Java with their storage Sizes in bytes.
Ans:
Data Type Size
Byte 1 byte
Short 2 byte
Int 4 byte
Long 8 byte
Double 8 byte
Float 4 byte
Char 2 byte
Boolean 1 Bit
Q.Give the usage of following methods
i) drawPolygon ()
ii) DrawOval ()
iii) drawLine ()
iv) drawArc ()
Ans
i) drawPolygon ():
public String getParent() Returns the pathname string of this abstract pathname's
parent, or null if this pathname does not name a parent
directory
public String getPath() Converts this abstract pathname into a pathname string.
Q Define an exception called 'No Match Exception' that is thrown when the
passward accepted is not equal to "MSBTE'. Write the program.
Ans import java.io.*;
class NoMatchException extends Exception
{
NoMatchException(String s)
{
super(s);
}
}
class test1
{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in) );
System.out.println("Enter a word:");
String str= br.readLine();
try
{
if (str.compareTo("MSBTE")!=0) // can be done with equals()
throw new NoMatchException("Strings are not equal");
else
System.out.println("Strings are equal");
}
catch(NoMatchException e)
{
System.out.println(e.getMessage());
}
}
}
Q.Compare array and vector. Explain elementAT( ) and addElement( ) methods
Ans:
Array Vector
1.An array is a structure that holds 1.The Vector is similar to array holds
multiple values of the same type. multiple objects and like an array; it
contains components that can be
accessed using an integer index.
2.An array is a homogeneous data type 2.Vectors are heterogeneous. You can
where it can hold only objects of one have objects of different data types
data type. inside a Vector.
3.After creation, an array is a fixed- 3.The size of a Vector can grow or shrink
length structure. as needed to accommodate adding and
removing items after the Vector has
been created.
4.Array can store primitive type data element. 4.Vector are store non-primitive type data
element
8.In array wrapper classes are not used. 8.Wrapper classes are used in vector
elementAT( ):
The elementAt() method of Java Vector class is used to get the element at the specified
index in the vector. Or The elementAt() method returns an element at the specified index.
addElement( ):
The addElement() method of Java Vector class is used to add the specified element to the
end of this vector. Adding an element increases the vector size by one.
Q.Write a program to check whether the string provided by the user is palindrome
or not.
Ans import java.lang.*;
import java.io.*;
import java.util.*;
class palindrome
{
public static void main(String arg[ ]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String:");
String word=br.readLine( );
int len=word.length( )-1;
int l=0;
int flag=1;
int r=len;
while(l<=r)
{
if(word.charAt(l)==word.charAt(r))
{
l++;
r--;
}
else
{
flag=0;
break;
}
}
if(flag==1)
{
System.out.println("palindrome");
}
else
{
System.out.println("not palindrome");
}
}
}
Q.Write a program to copy contents of one file to another.
Ans import java.io.*;
class copyf
{
public static void main(String args[]) throws IOException
{
BufferedReader in=null;
BufferedWriter out=null;
try
{
in=new BufferedReader(new FileReader("input.txt"));
out=new BufferedWriter(new FileWriter("output.txt"));
int c;
while((c=in.read())!=-1)
{
out.write(c);
}
System.out.println("File copied successfully");
}
finally
{
if(in!=null)
{
in.close();
}
if(out!=null)
{
out.close();
}
}
}
Class Interface
7)syntax 7)syntax
Class classname Inteface Innterfacename
{ {
Variable declaration, Final Variable declaration,
Method declaration abstract Method declaration
} }
Describe final variable and final method.
Ans Final method: making a method final ensures that the
functionality defined in this method will never be altered in any
way, ie a final method cannot be overridden.
Syntax:
final void findAverage()
{
//implementation
}
Example of declaring a final method:
class A
{
final void show()
{
System.out.println(“in show of A”);
}
}
class B extends A
{
void show() // can not override because it is declared with final
{
System.out.println(“in show of B”);
}}
Final variable: the value of a final variable cannot be changed.
Final variable behaves like class variables and they do not take
any space on individual objects of the class.
Example of declaring final variable: final int size = 100;
Q.
Q.Define package. How to create user defined package?
Explain with example.
Ans Java provides a mechanism for partitioning the class namespace
into more manageable parts. This mechanism is the package. The
package is both naming and visibility controlled mechanism.
Package can be created by including package as the first statement
in java source code. Any classes declared within that file will
belong to the specified package. Package defines a namespace in which classes are stored.
The syntax for defining a package is:
package pkg;
Here, pkg is the name of the package
eg : package
mypack;
Packages are mirrored by directories. Java uses file system
directories to store packages. The class files of any classes which
are declared in a package must be stored in a directory which has
same name as package name. The directory must match with the
package name exactly. A hierarchy can be created by separating
package name and sub package name by a period(.) as
pkg1.pkg2.pkg3; which requires a directory structure as
pkg1\pkg2\pkg3.
Syntax:
To access package In a Java source file, import statements
occur immediately following the package statement (if
it exists) and before any class definitions.
Syntax:
import pkg1[.pkg2].(classname|*);
Example:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
Source file:
import package1.Box;
class volume
{
Write a program to perform following task
(i) Create a text file and store data in it.
(ii) Count number of lines and words in that file.
6M
Ans import java.util.*;
import java.io.*;
class Model6B
{
public static void main(String[] args) throws Exception
{
int lineCount=0, wordCount=0;
String line = "";
BufferedReader br1 = new BufferedReader(new
InputStreamReader(System.in));
FileWriter fw = new FileWriter("Sample.txt");
//create text file for writing
System.out.println("Enter data to be inserted in
file: ");
String fileData = br1.readLine();
fw.write(fileData);
fw.close();
BufferedReader br = new BufferedReader(new
FileReader("Sample.txt"));
while ((line = br.readLine()) != null)
{
lineCount++; // no of lines count
String[] words = line.split(" ");
wordCount = wordCount + words.length;
// no of words count
}
System.out.println("Number of lines is : " +
lineCount);
System.out.println("Number of words is : " +
wordCount);
}
Q.Write a program to perform following task
(i) Create a text file and store data in it.
(ii) Count number of lines and words in that file.
Ans import java.util.*;
import java.io.*;
class Model6B
{
public static void main(String[] args) throws Exception
{
int lineCount=0, wordCount=0;
String line = "";
BufferedReader br1 = new BufferedReader(new
InputStreamReader(System.in));
FileWriter fw = new FileWriter("Sample.txt");
//create text file for writing
System.out.println("Enter data to be inserted in
file: ");
String fileData = br1.readLine();
fw.write(fileData);
fw.close();
BufferedReader br = new BufferedReader(new
FileReader("Sample.txt"));
while ((line = br.readLine()) != null)
{
lineCount++; // no of lines count
String[] words = line.split(" ");
wordCount = wordCount + words.length;
// no of words count
}
System.out.println("Number of lines is : " +
lineCount);
System.out.println("Number of words is : " +
wordCount);
}
Q Explain any two logical operator in java with example.
Ans Logical Operators: Logical operators are used when we want to
form compound conditions by combining two or more relations.
Java has three logical operators as shown in table:
Operator Meaning
|| Logical OR
! Logical
NOT
1.Overloading occurs when two or more 1.Overriding means having two methods with
methods in one class have the same method the same method name and parameters (i.e.,
name but different parameters. method signature)
2.In contrast, reference type determines 2.The real object type in the run-time, not the
which overloaded method will be used at reference variable's type, determines which
compile time. overridden method is used at runtime
Q.Describe the use of any methods of vector class with their syntax.
Ans:
• boolean add(Object obj)-Appends the specified element to the
end of this Vector.
• Boolean add(int index,Object obj)-Inserts the specified element at
the specified position in this Vector.
• void addElement(Object obj)-Adds the specified component to
the end of this vector, increasing its size by one.
•int capacity()-Returns the current capacity of this vector.
• void clear()-Removes all of the elements from this vector.
• Object clone()-Returns a clone of this vector.
• boolean contains(Object elem)-Tests if the specified object is a
component in this vector.
•void copyInto(Object[] anArray)-Copies the components of this
vector into the specified array.
• Object firstElement()-Returns the first component (the item at
index 0) of this vector.
• Object elementAt(int index)-Returns the component at the
specified index.
•int indexOf(Object elem)-Searches for the first occurence of the
given argument, testing for equality using the equals method.
• Object lastElement()-Returns the last component of the vector.
• Object insertElementAt(Object obj,int index)-Inserts the specified
object as a component in this vector at the specified index.