Tuesday, December 20, 2005

java basics to advanced faq

1.The Java interpreter is used for the execution of the source code. True
2) On successful compilation a file with the class extension is created.a) True
3) The Java source code can be created in a Notepad editor.a) True
4) The Java Program is enclosed in a class definition.a) True
5) What declarations are required for every Java application?
Ans: A class and the main( ) method declarations.
6) What are the two parts in executing a Java program and their purposes?
Ans: Two parts in executing a Java program are: Java Compiler and Java Interpreter.
The Java Compiler is used for compilation and the Java Interpreter is used for execution of the application.
7) What are the three OOPs principles and define them?
Ans : Encapsulation, Inheritance and Polymorphism are the three OOPs
Principles.
Encapsulation:Is the Mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse.
Inheritance:Is the process by which one object acquires the properties of another object.
Polymorphism:Is a feature that allows one interface to be used for a general class of actions.
8) What is a compilation unit? Ans : Java source code file.
9) What output is displayed as the result of executing the following statement?
System.out.println("// Looks like a comment.");
// Looks like a comment
10) In order for a source code file, containing the public class Test, to successfully compile, which of the following must be true?
a)It must have a package statement b)It must be named Test.java Ans : b
11) What are identifiers and what is naming convention?
Ans : Identifiers are used for class names, method names and variable names. An identifier may be any descriptive sequence of upper case & lower case letters, numbers or underscore or dollar sign and must not begin with numbers.
12) What is the return type of program’s main( ) method? Ans : void
13) What is the argument type of program’s main( ) method? Ans : string array.
14) Which characters are as first characters of an identifier?A : A – Z, a – z, _ ,$
15) What are different comments?Ans : 1) // -- single line comment
2) /* -- */ multiple line comment 3) /** --*/ documentation
16) What is the difference between constructor method and method?
Ans : Constructor will be automatically invoked when an object is created. Whereas method has to be call explicitly.
17) What is the use of bin and lib in JDK?
Ans : Bin contains all tools such as javac, applet viewer, awt tool etc., whereas Lib
contains all packages and variables.






Data types,variables and Arrays
1) What is meant by variable?
Ans: Variables are locations in memory that can hold values. Before assigning any value to a variable, it must be declared.
2) What are the kinds of variables in Java? What are their uses?
Ans: Java has three kinds of variables namely, the instance variable, the local variable and the class variable.
Local variables are used inside blocks as counters or in methods as temporary variables and are used to store information needed by a single method.
Instance variables are used to define attributes or the state of a particular object and are used to store information needed by multiple methods in the objects.
Class variables are global to a class and to all the instances of the class and are useful for communicating between different objects of all the same class or keeping track of global states.
3) How are the variables declared?
Ans: Variables can be declared anywhere in the method definition and can be initialized during their declaration.They are commonly declared before usage at the beginning of the definition. Variables with the same data type can be declared together. Local variables must be given a value before usage.
4) What are variable types?
Ans: Variable types can be any data type that java supports, which includes the eight primitive data types, the name of a class or interface and an array.
5) How do you assign values to variables?
Ans: Values are assigned to variables using the assignment operator =.
6) What is a literal? How many types of literals are there?
Ans: A literal represents a value of a certain type where the type describes how that value behaves.There are different types of literals namely number literals, character literals, boolean literals, string literals,etc.
7) What is an array? Ans: An array is an object that stores a list of items.
8) How do you declare an array?
Ans: Array variable indicates the type of object that the array holds.Ex: int arr[];
9) Java supports multidimensional arrays. a)True
10) An array of arrays can be created. a)True
11) What is a string? Ans: A combination of characters is called as string.
12) Strings are instances of the class String. a)True
13) When a string literal is used in the program, Java automatically creates instances of the string class. a)True
14) Which operator is to create and concatenate string?
Ans: Addition operator(+).
15) Which of the following declare an array of string objects?
String[ ] s; String [ ]s: String[ s]: String s[ ]: Ans : a, b and d
16) What is the value of a[3] as the result of the following array declaration?
1 2 3 4 Ans : d
17) Which of the following are primitive types?
byte String integer Float Ans : a.
18) What is the range of the char type?
0 to 216 0 to 215 0 to 216-1 0 to 215-1 Ans. d
19) What are primitive data types?
Ans : byte, short, int, long, float, double, Boolean, char
20) What are default values of different primitive types?
Ans : int – 0, short – 0, byte – 0, long - 0 l, float - 0.0 f, double - 0.0 d , boolean - false
char - null
21) Converting of primitive types to objects can be explicitly. A)False
22) How do we change the values of the elements of the array?
Ans : The array subscript expression can be used to change the values of the elements of the array.
23) What is final varaible?
Ans : If a variable is declared as final variable, then you can not change its value. It becomes constant.
24) What is static variable?
Ans : Static variables are shared by all instances of a class.

Operators
1) What are operators and what are the various types of operators available in Java?
Ans: Operators are special symbols used in expressions.
The following are the types of operators:
Arithmetic operators, Assignment operators, Increment & Decrement operators,
Logical operators, Biwise operators, Comparison/Relational operators and
Conditional operators
2) The ++ operator is used for incrementing and the -- operator is used for
decrementing. a)True
3) Comparison/Logical operators are used for testing and magnitude. a)True
4) Character literals are stored as unicode characters. a)True
5) What are the Logical operators? Ans: OR(), AND(&), XOR(^) AND NOT(~).
6) What is the % operator?
Ans : % operator is the modulo operator or reminder operator. It returns the reminder of dividing the first operand by second operand.
7) What is the value of 111 % 13?
3 5 7 9 Ans : c.
8) Is &&= a valid operator? Ans : No.
9) Can a double value be cast to a byte? Ans : Yes
10) Can a byte object be cast to a double value ?
Ans : No. An object cannot be cast to a primitive value.
11) What are order of precedence and associativity?
Ans : Order of precedence the order in which operators are evaluated in expressions.
Associativity determines whether an expression is evaluated left-right or right-left.
12) Which Java operator is right associativity? Ans : = operator.
13) What is the difference between prefix and postfix of -- and ++ operators?
Ans : The prefix form returns the increment or decrement operation and returns the value of the increment or decrement operation.
The postfix form returns the current value of all of the expression and then
performs the increment or decrement operation on that value.
14) What is the result of expression 5.45 + "3,2"?
The double value 8.6 The string ""8.6" The long value 8.
The String "5.453.2" Ans : d
15) What are the values of x and y ? x = 5; y = ++x; Ans : x = 6; y = 6
16) What are the values of x and z? x = 5; z = x++; Ans : x = 6; z = 5

Control Statements
1) What are the programming constructs? Ans: a) Sequential
b) Selection -- if and switch statements
c) Iteration -- for loop, while loop and do-while loop
2) class conditional {
public static void main(String args[]) {
int i = 20;
int j = 55;
int z = 0;
z = i < s1 = "abc" s2 = "def" s3 =" s1.concat(s2.toUpperCase(" s="new" ibegin="1;" iend="3;" s1="new" s2="new" s3="new" s3="s1" s3="s1" s3="s1" s3="s1" ten="new" nine="new" i="1;" f1 =" new" f2 =" new" context =" getAppletContext();" l =" new" dim =" getSize" appletwidth =" dim.width">tag contains two attributes namely _________ and _______.
Ans : Name , value.

Passing values to parameters is done in the _________ file of an applet.
Ans : .html.
12) What tags are mandatory when creating HTML to display an applet
name, height, width
code, name
codebase, height, width
d) code, height, width
Ans : d.
Applet’s getParameter( ) method can be used to get parameter values.
True.
False.
Ans : a.
What are the Applet’s Life Cycle methods? Explain them?
Ans : init( ) method - Can be called when an applet is first loaded.
start( ) method - Can be called each time an applet is started.
paint( ) method - Can be called when the applet is minimized or refreshed.
stop( ) method - Can be called when the browser moves off the applet’s page.
destroy( ) method - Can be called when the browser is finished with the applet.
What are the Applet’s information methods?
Ans : getAppletInfo( ) method : Returns a string describing the applet, its author ,copy
right information, etc.
getParameterInfo( ) method : Returns an array of string describing the applet’s parameters.
All Applets are subclasses of Applet.
True.
False.
Ans : a.
All Applets must import java.applet and java.awt.
True.
False.
Ans : a.
What are the steps involved in Applet development?
Ans : a) Edit a Java source file,
b) Compile your program and
c) Execute the appletviewer, specifying the name of your applet’s source file.
Applets are executed by the console based Java run-time interpreter.
True.
False.
Ans : b.
Which classes and interfaces does Applet class consist?
Ans : Applet class consists of a single class, the Applet class and three interfaces: AppletContext,
AppletStub and AudioClip.
What is the sequence for calling the methods by AWT for applets?
Ans : When an applet begins, the AWT calls the following methods, in this sequence.
init( )
start( )
paint( )
When an applet is terminated, the following sequence of method cals takes place :
stop( )
destroy( )
Which method is used to output a string to an applet?
Ans : drawString ( ) method.
Every color is created from an RGB value.
True. False
Ans : a.


AWT : WINDOWS, GRAPHICS AND FONTS
How would you set the color of a graphics context called g to cyan?
g.setColor(Color.cyan);
g.setCurrentColor(cyan);
g.setColor("Color.cyan");
g.setColor("cyan’);
g.setColor(new Color(cyan));
Ans : a.
The code below draws a line. What color is the line?
g.setColor(Color.red.green.yellow.red.cyan);
g.drawLine(0, 0, 100,100);
Red
Green
Yellow
Cyan
Black
Ans : d.
What does the following code draw?
g.setColor(Color.black);
g.drawLine(10, 10, 10, 50);
g.setColor(Color.RED);
g.drawRect(100, 100, 150, 150);
A red vertical line that is 40 pixels long and a red square with sides of 150 pixels
A black vertical line that is 40 pixels long and a red square with sides of 150 pixels
A black vertical line that is 50 pixels long and a red square with sides of 150 pixels
A red vertical line that is 50 pixels long and a red square with sides of 150 pixels
A black vertical line that is 40 pixels long and a red square with sides of 100 pixel
Ans : b.
Which of the statements below are true?
A polyline is always filled.
b) A polyline can not be filled.
c) A polygon is always filled.
d) A polygon is always closed
e) A polygon may be filled or not filled
Ans : b, d and e.
What code would you use to construct a 24-point bold serif font?
new Font(Font.SERIF, 24,Font.BOLD);
new Font("SERIF", 24, BOLD");
new Font("BOLD ", 24,Font.SERIF);
new Font("SERIF", Font.BOLD,24);
new Font(Font.SERIF, "BOLD", 24);
Ans : d.
What does the following paint( ) method draw?
Public void paint(Graphics g) {
g.drawString("question #6",10,0);
}
The string "question #6", with its top-left corner at 10,0
A little squiggle coming down from the top of the component, a little way in from the left edge
Ans : b.


What does the following paint( ) method draw?
Public void paint(Graphics g) {
g.drawString("question #6",10,0);
}
A circle at (100, 100) with radius of 44
A circle at (100, 44) with radius of 100
A circle at (100, 44) with radius of 44
The code does not compile
Ans : d.
8)What is relationship between the Canvas class and the Graphics class?
Ans : A Canvas object provides access to a Graphics object via its paint( ) method.
What are the Component subclasses that support painting.
Ans : The Canvas, Frame, Panel and Applet classes support painting.
What is the difference between the paint( ) and repaint( ) method?
Ans : The paint( ) method supports painting via a Graphics object. The repaint( ) method is used
to cause paint( ) to be invoked by the AWT painting method.
What is the difference between the Font and FontMetrics classes?
Ans : The FontMetrics class is used to define implementation-specific properties, such as ascent
and descent, of a Font object.
Which of the following are passed as an argument to the paint( ) method?
A Canvas object
A Graphics object
An Image object
A paint object
Ans : b.
Which of the following methods are invoked by the AWT to support paint and repaint operations?
paint( )
repaint( )
draw( )
redraw( )
Ans : a.
Which of the following classes have a paint( ) method?
Canvas
Image
Frame
Graphics
Ans : a and c.
Which of the following are methods of the Graphics class?
drawRect( )
drawImage( )
drawPoint( )
drawString( )
Ans : a, b and d.
Which Font attributes are available through the FontMetrics class?
ascent
leading
case
height
Ans : a, b and d.
Which of the following are true?
The AWT automatically causes a window to be repainted when a portion of a window has been minimized and then maximized.
The AWT automatically causes a window to be repainted when a portion of a window has been covered and then uncovered.
The AWT automatically causes a window to be repainted when application data is changed.
The AWT does not support repainting operations.
Ans : a and b.
Which method is used to size a graphics object to fit the current size of the window?
Ans : getSize( ) method.
What are the methods to be used to set foreground and background colors?
Ans : setForeground( ) and setBackground( ) methods.
19) You have created a simple Frame and overridden the paint method as follows
public void paint(Graphics g){

g.drawString("Dolly",50,10);

}
What will be the result when you attempt to compile and run the program?
The string "Dolly" will be displayed at the centre of the frame
b) An error at compilation complaining at the signature of the paint method c) The lower part of the word Dolly will be seen at the top of the form, with the top hidden. d) The string "Dolly" will be shown at the bottom of the form
Ans : c.
20) Where g is a graphics instance what will the following code draw on the screen.
g.fillArc(45,90,50,50,90,180);
a) An arc bounded by a box of height 45, width 90 with a centre point of 50,50, starting at an angle of 90 degrees traversing through 180 degrees counter clockwise.
b) An arc bounded by a box of height 50, width 50, with a centre point of 45,90 starting at an angle of 90 degrees traversing through 180 degrees clockwise.
c) An arc bounded by a box of height 50, width 50, with a top left at coordinates of 45, 90, starting at 90 degrees and traversing through 180 degrees counter clockwise.
d) An arc starting at 45 degrees, traversing through 90 degrees clockwise bounded by a box of height 50, width 50 with a centre point of 90, 180.
Ans : c.
21) Given the following code import java.awt.*;public class SetF extends Frame{public static void main(String argv[]){SetF s = new SetF();s.setSize(300,200);s.setVisible(true);}} How could you set the frame surface color to pink
a)s.setBackground(Color.pink);b)s.setColor(PINK);c)s.Background(pink);d)s.color=Color.pink
Ans : a.
Utility Package
1) What is the Vector class?
ANSWER : The Vector class provides the capability to implement a growable array of objects.
2) What is the Set interface?
ANSWER : The Set interface provides methods for accessing the elements of a finite mathematical set.Sets do not allow duplicate elements.
3) What is Dictionary class?
ANSWER : The Dictionary class is the abstarct super class of Hashtable and Properties class.Dictionary provides the abstarct functions used to store and retrieve objects by key-value.This class allows any object to be used as a key or value.
4) What is the Hashtable class?
ANSWER : The Hashtable class implements a hash table data structure. A hash table indexes and stores objects in a dictionary using hash codes as the objects' keys. Hash codes are integer values that identify objects.
5) What is the Properties class?
Answer : The properties class is a subclass of Hashtable that can be read from or written to a stream.It also provides the capability to specify a set of default values to be used if a specified key is not found in the table. We have two methods load() and save().
6) What changes are needed to make the following prg to compile?
import java.util.*;
class Ques{
public static void main (String args[]) {
String s1 = "abc";
String s2 = "def";
Vector v = new Vector();
v.add(s1);
v.add(s2);
String s3 = v.elementAt(0) + v.elementAt(1);
System.out.println(s3);
}
}
ANSWER : Declare Ques as public B) Cast v.elementAt(0) to a String
C) Cast v.elementAt(1) to an Object. D) Import java.lang
ANSWER : B) Cast v.elementAt(0) to a String

8) What is the output of the prg.
import java.util.*;
class Ques{
public static void main (String args[]) {
String s1 = "abc";
String s2 = "def";
Stack stack = new Stack();
stack.push(s1);
stack.push(s2);
try{
String s3 = (String) stack.pop() + (String) stack.pop() ;
System.out.println(s3);
}catch (EmptyStackException ex){}
}
}
ANSWER : abcdef B) defabc C) abcabc D) defdef
ANSWER : B) defabc
9) Which of the following may have duplicate elements?
ANSWER : Collection B) List C) Map D) Set
ANSWER : A and B Neither a Map nor a Set may have duplicate elements.
10) Can null value be added to a List?
ANSWER : Yes.A Null value may be added to any List.
11) What is the output of the following prg.
import java.util.*;
class Ques{ public static void main (String args[]) {
HashSet set = new HashSet();
String s1 = "abc";
String s2 = "def";
String s3 = "";
set.add(s1); set.add(s2); set.add(s1); set.add(s2);
Iterator i = set.iterator();
while(i.hasNext()) { s3 += ( String) i.next(); }
System.out.println(s3); } }
A) abcdefabcdef B) defabcdefabc C) fedcbafedcba D) defabc
ANSWER : D) defabc. Sets may not have duplicate elements.
12) Which of the following java.util classes support internationalization?
A) Locale B) ResourceBundle C) Country D) Language
ANSWER : A and B . Country and Language are not java.util classes.
13) What is the ResourceBundle?
The ResourceBundle class also supports internationalization.
ResourceBundle subclasses are used to store locale-specific resources that can be loaded by a program to tailor the program's appearence to the paticular locale in which it is being run. Resource Bundles provide the capability to isolate a program's locale-specific resources in a standard and modular manner.
14) How are Observer Interface and Observable class, in java.util package, used? ANSWER : Objects that subclass the Observable class maintain a list of Observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
15) Which java.util classes and interfaces support event handling?
ANSWER : The EventObject class and the EventListener interface support event processing.
16) Does java provide standard iterator functions for inspecting a collection of objects? ANSWER : The Enumeration interface in the java.util package provides a framework for stepping once through a collection of objects. We have two methods in that interface.
public interface Enumeration {
boolean hasMoreElements();
Object nextElement();
}
17) The Math.random method is too limited for my needs- How can I generate random numbers more flexibly?
ANSWER : The random method in Math class provide quick, convienient access to random numbers, but more power and flexibility use the Random class in the java.util package.
double doubleval = Math.random();
The Random class provide methods returning float, int, double, and long values.
nextFloat() // type float; 0.0 <= value < r =" new" floatval =" r.nextFloat();" url = "jdbc:odbc:Fred" con =" DriverManager.getConnection(url," stmt =" con.createStatement();" rs =" stmt.executeQuery(" s =" rs.getString(" updatesales =" con.prepareStatement(" sales =" ?" updatesales =" con.prepareStatement(" sales =" ?" updatetotal =" con.prepareStatement(" total =" TOTAL" cs =" con.prepareCall(" rs =" cs.executeQuery();" warning =" stmt.getWarnings();" warning =" warning.getNextWarning();" stmt =" con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE," srs =" stmt.executeQuery(" stmt =" con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE," srs =" stmt.executeQuery(" name =" srs.getString(" price =" srs.getFloat(" con =" DriverManager.getConnection(" stmt =" con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE," uprs =" stmt.executeQuery(" add1 =" InetAddress.getByName(" add2 =" InetAddress.getByName(" url =" new" conection =" url.openConnection();" href="http://javaquestions.homepage.com/definition.html">What Is a Socket ? A socket is one end-point of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes--Socket and ServerSocket--which implement the client side of the connection and the server side of the connection, respectively.
What information is needed to create a TCP Socket?
ANSWER : The Local System’s IP Address and Port Number.
And the Remote System's IPAddress and Port Number.
5) What are the two important TCP Socket classes?
ANSWER : Socket and ServerSocket.
ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets. getInputStream() and getOutputStream() are the two methods available in Socket class.
When MalformedURLException and UnknownHostException throws?
ANSWER : When the specified URL is not connected then the URL throw MalformedURLException and If InetAddress’ methods getByName and getLocalHost are unabletoresolve the host name they throwan UnknownHostException.

0 Comments:

Post a Comment

<< Home