Q1. Write a short note on web browsers.
Ans. Web browser is special software, which is used to execute web pages.
It can do following functions:
Connect to an appropriate server.
Query the server for the information to be read.
Provides an interface to read the information returned by the server.
To access information stored in the form of web pages, users must connect to a web server. Computers that offer the facility to read information stored in the web pages are called web clients. Some of the most popular browsers software that clients run to allow them to query web servers for information is Netscape Communicator, Internet Explorer. Internet Explorer is most commonly used now days because it is free with windows operating system.
Q2. Why java is known as an Internet Language? Discuss.
Ans. The Internet helped catapult java to the forefront of programming, and java, in turn, has had a profound effect on the Internet. The reason for this is quite simple: Java expands the universe of objects that can move about freely in cyberspace. In a network, two very broad categories of objects are transmitted between the server and your personal computer: passive information and dynamic, active programs. For example, when you read your E-mail, you are viewing passive data. Even when you download a program, the program’s code is still only passive data until you execute it. However, a second type of object can be transmitted to your computer: a dynamic, self-executing program. Such a program is an active agent on the client computer. Java provides applets for Internet programming.
Ans. Java can be used to create two types of programs: applications and applets. An applet is a Java program that runs within the Java enabled web browsers like Netscape Communicator and Internet explorer. Applets often use a graphical user interface and may have text, images, buttons, scrollbars, and sound. Applets can be embedded in HTML. It is automatically executed by applet-enabled we-browser. Every applet is a subclass of java.applet.Applet
Q4. Explain the important features of java.
Ans. Features of java
Simple
Object-oriented
Robust
Multithreading
Architecture-neutral
Interpreted
Dynamic
Distributed
Simple: Java was designed to be easy for the professional programmer to learn and use efficiently. If you are experienced in C++ programmers, moving to java will require very little effort.
Interpreted: Java enables the creation of cross-platform programs by compiling into an intermediate representation called java byte code. This code can be interpreted on any system that provides a java virtual machine.
Distributed: Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols. RMI provides Remote Method Invocation.
Dynamic: Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time.
Q5. What is operator ‘+’: Concatenation or Addition?
Ans. Java uses the + operator for both addition and concatenation. Parsers can unambiguously figure out what your intent is from the context.
public class Concat_Add {
public static void main(String[] args)
{
int x = 10, y = 10;
System.out.printIn("x+y " + x+y);
System.out.printIn(x+y + " x+y " );
System.out.printIn("value: " + x + 1 );
}
}
Output:
x+y 1010
20 x+y
value: 101
Q6. What are the command line arguments? How they are used?
Ans. Command line arguments are parameters that are supplied to the application program at the time of invoking it for execution. These command line arguments are used with the main function with is the program. The following examples shows
class xyz {
public static void main (String ap[ ]) {
System out print (“How are you!” + ap [0]);
}
}
Output
Java xyz Raman
How are you! Raman
Q7. List a few areas of application of oops technology.
Ans. APPLICATIONS OF OOP
OOP is one of the programming buzzwords today. There appears to be a great deal of excitement and interest among software engineers in suing OOP. Applications of OOP are beginning to gain importance in many areas. The most popular application of object-oriented programming, up to now, has been in the area of user interface design such as windows. There are hundreds of windowing systems developed using OOP techniques.
The promising areas for application of OOP includes:
Real –time systems
Simulation and modeling
Hypertext, hypermedia and expert text
AI and expert systems
Neural networks and parallel programming
Decision support and office automation systems
CIM/CAD/ CAD system
Q8. Write the characteristics of object oriented Programming.
Ans. An object-oriented program has three explicit characteristics and one implicit characteristic. The three explicit characteristics are encapsulation, inheritance, and polymorphism. The implicit characteristic is abstraction. The implicit chrematistics of abstraction is used to specify new abstract data types (ADT).
Encapsulation is used to gather an ADT’s data representation and its behavior into one encapsulated entity. For example automotive engineers encapsulated the specifications for the steering mechanism of car into an object where they exposed the interface (steering wheel) and hide the implantation (levels and bolts, etc.). In all likelihood the steering mechanism object contains a number other more specialized embedded objects, each of which has state and behavior and has interface and implementation. The interfaces to those embedded objects are not exposed, but they are exposed to other parts of steering mechanism that use them.
Inheritance is used to derive a new data type from an existing one.
Polymorphism is used to customize the behavior of an instance of a type based on existing conditions.
Q9. Explain the structure of Java Program.
Ans. Documentation Section: The documentation section comprises a set of comment lines giving the name of the program, other details, which the programmer would like to refer to a later stage. Comments must explain why and what of classes and how of algorithms. This would greatly help in maintaining the program. In addition to the two styles of comments. // or / * . . * /. A third style / * * . . . * * / is documentation comment. This form of comment is used for generating documentation automatically.
Package statement: The first statement allowed in a Java file is a package statement. This statement. Declares a package name and informs the compiler that the classes defined here belong to this package. Example-package emp;
The package statement is optional. That is, our classes for not have to be part of a package.
Import statements: The next thing after a package statement (but before any class definitions) may be a number of import statements. This is similar to #include in i.e. import emp.add;
This statement instructs the interpreter to load the add class contained in the package emp. Using import statements; we can have access to classes that are part of other named packages.
Interface statements: An interface is like a class but includes a group of method declarations. This is also an optional section and is used only, when we wish to implement the multiple inheritance features in the program.
Class definitions: A java program may contain multiple class definitions. Classes and the primary and essential elements of a java program. These classes are used to map the objects of real world problems. The number of classes used depends on the complexity of the problem.
Main method class: Since every Java stand alone program enquires a main method as its starting point, this classis the essential part of a Java program. A simple Java program may contain only this part. The main method creates objects of various classes and establishes communications between them on reaching the end of the main, the program terminator and the control passes back to the operating system.
Q10. Write a note on Java tokens.
Ans. Smallest individual units in a program are known as tokens. The compiler recognizes them for building up expressions and statements java language includes five types of tokens
Reserved keywords.
Identifiers
Literals
Operators
Separators
Keywords: Keywords are an essential part of language definition. They implement specific features of the language Java has reserved 60 works as keywords. Since keywords have specific meaning in Java, we cannot use them as names for variables, classes, methods and so on. All keywords are to be written in lower-case letters.
Identifiers: Identifiers are programmer-designed tokens. They are used for naming classes, methods, variables, objects, labels and interfaces in program Java identifiers follow the following rules:
They can have alphabets, digits and the underscore and dollar sign characters.
They must not begin with a digit.
Upper case and lower case letters are distinct.
They can be of any length.
Literals: Literals in Java are a sequence of character (digits, letters, and other characters) that represents constant values to be stored in variables. Java language specifies five major types of literals. They are:
Integer literals
Floating-point literals
Character literals
String literals
Boolean literals.
Operators: An operator is a symbol that takes one or more arguments and operates on them to produce a result. Java operates are of following categories.
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment and decrement operators
Conditional operators
Bitwise operators
Special operators like instance of and dot operator (.)
Separators: Separators are symbols used to indicate where groups of code are divided and arranged. They basically define the shape and function of our code.
E.g.
parentheses ()
Braces { }
Brackets [ ]
Semi colon;
Period.
Q11. Explain the scope of variables declared in Java.
Ans. Java variables are actually classified into three kinks:
Instance variable
Class variable
Local variable.
Instance and class variables are declared inside a class.
Instance variables: are created when the objects are instantiated and therefore they are associated with the objects. They take different values for each other on the other hand; class variables are global to a class and belong to entire set of objects that class creates. Only one memory location is created for class variable.
Variables declared inside methods are calls local variables. They are not available for use outside the method definition.
Q12. Explain the Bitwise logical and shift operators.
Ans. Bitwise Logical operators: There are three logical Bitwise operators. They are:
Bitwise AND (2)
Bitwise OR (1)
Bitwise exclusive OR (^)
These are binary operators and require two integer type operands. These operators work on their operands bit-by-bit starting from the least significant bit.
A B A &B A|B A^B
Bitwise Shift operators: The shift operators are used to move bit patterns either to the left or to the right. The shift operators are represented by the symbols <and > and are used in the following form:
Left shift: op < < n
Right shift: op < >n
Op is the integer expression that is to be shifted and n is the number of bit positions to be shifted. The left shift operation caused all the bits in the operand oop to be shifted to the left by n positions. The left most n bits in the original bit pattern will be lost and right most n bit positions that are vacated will be filled with os.
Similarly, the right-shift operation causes all the bits in the operand op to be shifted to the right by n position. The rightmost n bits will be lost. The leftmost n bit positions that are vacated will be filled with zero, if the op is a positive integer. If the variable to be shifted is negative, then the operation preserves the high –order bit of 1 and shifts only the lower 31 bits to the right. The n may not be negative and it may not exceed the number of bits used to represent the left operand op.
Bitwise complement operations: The complement operator is (Also called the one’s complement operator) is a unary operator and inverts all the bits represented by its operand. That is 0’s become 1’s and 1‘s become 0’s as.
E.g.
X = 1001 0110 1100 1000
U X= 0110 1001 0011 0111
Q13. Explain various tools that are used to create and run a program.
Ans. There are a number of tools available for creating and running java program. Some of these tools are listed below.
The java development kit
Visual j++, a Microsoft product
Jbuilder, an Inspire (formerly Borland Corporation) product.
JavaMaker, a Window 95/ Windows NT product.
Java Development Kit (JDK)
The Java Development kit (JDK) consists of a number of executables, which are command line driven. These executables are run in a MSDOS window under Windows 95. The java development environment is character based and not graphical. The tools available in the java Development kit are as follows.
Javac the Java compiler
Appletviewer Java’s Applet Viewer
Java Interpreter
Javap Java Disassembler.
Javah C header and Stub file creator.
Javadoc Java Document Generator.
Jdb Java Debugger.
All JDK’s tools including the compiler are called from the command prompt.
Q14. What do you mean by java is Architecture Neutral?
Ans. Java has been so designed that it can work on multiple networks. It supports a variety of systems with a variety of CPU’s and various operating systems. A java application can work anywhere on the network or on the Internet. This is because the java compiler generates an architecture neutral object file format. The compiled code can be run on a number of operating systems and hardware platforms provided that system is running a Java Virtual Machine (JVM).
A programmer first compiles java source into byte code using the java compiler. This byte code is binary and architecture neutral. This byte code is not complete until interpreted by a java run time environment, usually a browser that is java enabled. Since each java run time environment is for a specific platform, the byte code is going to work on that specific platform.
The JVM contains an element called a “linker” which checks data coming into the local machine to make sure that it contains neither deliberately harmful files nor files that could disrupt the normal functioning of the local computer.
Q15. Explain literals in java.
Ans. Literals in java are a sequence of (digits, letters, and other characters) that represent constant values to be stored in variables. Java language specifies five major types of literals. They are:
Integer literals
Floating point literals
Character literals
String literals
Boolean literals
The only valid literals of Boolean type are true and false. For example,
boolean isBig=true;
boolean isLittle=false;
Char Literals
A char literal can be expressed by enclosing the desired character in single
quotes.
char c =’N’;
Another way to express a character literal is a Unicode value specified using four hexadecimal digits, preceded by u, with the entire expression in single quote. For example,
Char c1=’u4567’;
Java supports a few escape for denoting special characters:
‘ ’ for new line
‘ ’ for return
‘ ’ for tab
‘’ for backspace
‘f’ for formfeed
‘’ ‘ for single quote
‘ ” ’ for double quote
‘\’ for backslash
28
034
0x1c
0x1C
0X1c
oX1c
oX1C
A decimal point: 1.414
The letter E or e, indicating scientific notation: 4.23e+21
The suffix F or f, indicating a float literal:1.828f
The suffix D or d, indicating a double literal:1234d
Java provides many advanced facilities for specifying non-literal string values, including a concatenation operator and some sophisticated constructors for String class.
Q16. Explain security in java.
Or
Ans. Java does not support pointer, that’s why java is very secure language. There are no verbs that allow java programs to write directly to memory locations. Java programs are always “contained” under the complete control of the operating system and its run time environment. Java does provide Direct Memory Access (DMA). Java programs are first compiled into byte code instructions, which are verified by the java compiler. JIT compiler is part of the JVM; it compiles byte code into executable code in real time, on a piece-by-piece, demand basis. It is important to understand that it is not possible to compile an entire java program into executable code all at once, because java perform various run time checks that can be done only at run time. Java is strictly typed language, it checks your code at compile time, it also checks your code at run time.
Ans. Java as a language has evolved from C++. James gosling, the creator of java, in 1991 began extending the C++ compiler to make it more platforms independent. He realized that this approach would not be sufficient and so he developed a new interpreter. This interpreter was named Oak.
Throughout 1992 and 1993 the team continued to develop Oak. In this meantime, Internet was growing with the first release of the NSCA Mosaic World Wide Web browser.
By the summer of 1994 the team realized that the platform independent technology they had invented could add some special features to a World Wide Web browser, so they began working on a browser named Web Runner. This browser was named as Hot Java and it was officially announced on May of 1995 at Sun World’s 95
Q18. Explain Mathematical Functions used in java.
Ans. Mathematical functions such as cos, sqrt, log etc. are frequently used in analysis of real-life problems. Java supports these basic math functions though math class defined in the java.lang package.
Sin(x)
Returns the sine of the angle x in radians.
Cos(x)
Returns the cosine of the angle x in radians.
Tan(x)
Returns the cosine of the angle x in radians.
asin(y)
Returns the angle whose sine is y.
Acos(y)
Returns the angle whose cosine is y.
atan(y)
Returns the angle whose tangent is y.
atan2(x,y)
Returns the angle whose tangent is x/y.
pow(x,y)
Returns x raised to y (Xy).
Exp(x)
Returns e raised to x (ex).
Log(x)
Returns the natural logarithm of x.
sqrt(x)
Returns the square root of x.
Ceil(x)
Returns the smallest whole number greater than or equal to x.
floor(x)
Returns the largest whole number less than or equal to x.
Abs(a)
Returns the absolute value of a.
max(a,b)
Returns the maximum of a and b.
Min(a,b)
Returns the minimum of a and b.
Q19. What do you mean by Internet? Explain the various services provided by Internet.
Ans. Internet: - A global networks connecting millions of computers. More than 100 countries are linked into exchanges of data, news and opinions. Unlike online services, which are centrally controlled, the Internet is decentralized by design. Each Internet computer, called a host, is independent.
` Originally designed by the US Defense Department so that a communication signal could withstand a nuclear war and serve military institutions worldwide, the Internet was first known as the ARPA net. The Internet is system of linked computer networks; international in scope that facilitates data communication services such as remote login, file transfer, electronic mail and newsgroups.
Services provided by Internet
FTP: - The File Transfer Protocol (FTP) allows an Internet user to move a file from one computer to another on the Internet. A file may contain any type of digital information, text documentation, image, artwork and software etc. Moving a file from remote computer to ones own computer is known as downloading he file, and moving from one own computer to a remote computer is known as Uploading.
E-Mail: - E-Mail is the facility of sending text-based messages and letters to any Internet user. You can send mail to your friend who is also on the Internet. Everybody on the Internet has his/her own unique e-mail address.
WWW: -WWW stands for World Wide Web. The World Wide Web is a collection of pages maintained on the Internet using a technique that is called hypertext.
IRC: - An Internet Relay Chat (IRC) is a party line over which you can have interesting conversations with other Internet users.
Gopher: - Gopher Invented at the University of Minnesota in 1993 just before the Web, gopher was a widely successful method of making menus of material available over the Internet. Gopher was designed to be much easier to use than FTP, while still using a text-only interface. Gopher is a Client and Server style program, which requires that the user have a Gopher Client program. Although Gopher spread rapidly across the globe in only a couple of years, it has been largely supplanted by Hypertext, also known as WWW (World Wide Web). There are still thousands of Gopher Servers on the Internet and we can expect they will remain for a while.
WAIS: - (Wide Area Information Servers) A commercial software package that allows the indexing of huge quantities of information, and then making those indices searchable across networks such as the Internet. A prominent feature of WAIS is that the search results are ranked (scored) according to how relevant the hits are, and that subsequent searches can find more stuff like that last batch and thus refine the search process.
Q20. Explain short circuit logical operator in java. Give an example of short circuit logical operator in java.
Ans. The short circuit logical operators && and || provide logical AND and OR operations on Boolean types.
For an AND operation, if one operand is false, the result is false, without regard to the other operand.
For an OR operation, if one operand is true, the result is true, without regard to the other operand.
If the left operand of a Boolean ‘And’ operation is false, then the result is definitely false, whatever the right operand. Similarly, if the left operand of a boolean OR operation is true, the result definitely true and the right operand need not be evaluated.
Example is:
If ((s! =null) && (s.length ()>20))
{
System.out.println(s);
}
In this syntax if both expressions are true it will return true otherwise it will return false.
Q21. List eight static methods of character class.
Ans. Character is a simple wrapper around a char.
Method
Static Boolean isDefined(char ch)
Returns true if ch is a defined by Unicode.Otherwise, it returns false
Static Boolean isDigit(char ch)
Returns true if ch is a digit.Otherwise, it returns false
Static Boolean isIdentifierIgnorable (char ch)
Returns true if ch should be ignorned in an identifier. Otherwise, it returns false.
Static boolean is ISOControl (char ch)
Returns true if ch is an ISO control character. Otherwise, it returns false
Static boolean isLetter (char ch)
Returns true if ch is a letter. Otherwise, it returns false.
Static boolean isLowerCase (char ch)
Returns true if ch is lowercase letter.otherwise, it returns false.
Static boolean isSpaceChar (char ch)
Returns true if ch is a Unicode space character. Otherwise, it returns false.
Static boolean isTitleCase (char ch)
Returns true if ch is a Unicode titlecase character .otherwise, it returns false.
Q22. Write a program to sort an array.
Ans. class numbersorting
{
public static void main(String args[])
{
int number[]={56,89,7,5,2,1};
int n=number.length;
System.out.println("unsorted elements");
for(int i=0;i<n;i++)
{
System.out.println(" "+ number[i]);
}
System.out.println(" ");
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(number[i]>number[j])
{
int temp=number[i];
number[i]=number[j];
number[j]=temp;
} } }
System.out.println("sorted list is");
for(int i=0;i<n;i++)
{
System.out.println(" "+number[i]);
}
System.out.println(" ");
}
}
Q23. Write any program in java using switch statement.
Ans. class switch1
{
public static void main(String args[])
{
String a;
a=args[0];
int i;
i=Integer.valueOf(a).intValue();
switch(i)
{
case 0:
System.out.println("ZERO");
break;
case 1:
System.out.println("ONE");
break;
case 2:
System.out.println("TWO");
break;
case 3:
System.out.println("THREE");
break;
default:
System.out.println("i is greater than three");
} } }
Q24. Write a program to find whether the given number is a prime number or not.
Ans. class prime
{
public static void main(String args[])
{
String a;
a=args[0];
int j,i;
j=Integer.valueOf(a).intValue();
for(i=2;i<j;i++)
{
if(j%i==0)
break;
}
if(i==j)
System.out.println("No is prime"+i);
else
System.out.println("No is not prime"+i);
} }
Ans. In looping, sequences of statements are executed until some conditions for the termination of the loop are satisfied. The test may either be to determine whether the loop has been repeated the specified number of times or to determine whether a particular condition has been met with.
The java language provides for three constructs for performing loop operations. They are:
1 The while statement
2 The do statement
3 the for statement
The simplest of all the looping structures in java is the while statement. The basic format of the while statement is
Initialization;
While (test condition)
{
Body of the loop
}
The while is an entry-controlled loop statement. If condition is true the body of the loop is executed. Otherwise the control is transferred out of the loop.
On some occasions it might be necessary to execute the body of the loop before the test is performed. Such situations can be handled with the help of the do statement. This takes the form:
Initialization
do
{
Body of the loop
}
while (Test condition);
The for loop is another entry-controlled loop that provides a more concise loop control structure. The general form of the loop is
for (initialization; test condition; increment)
{
Body of the loop
}
Q26. Differentiate between constructors and destructors in java.
Ans. Constructor: Constructors are the methods defining by the same name as the name of the class. It is use to initialize an object at the time of object creation. Special property of a constructor is that it doesn’t have any return type.
Destructor: There is no destructor in java. We can use finalize method instead of destructor.
Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non-java resources such as a file handling or window character font, then you might want to make sure these resources are freed before an object is destroyed. to handle such situations, java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector
The finalize () method has this general form:
protected void finalize()
{
//finalization code here
}
Ans. While declaring functions you can pass some arguments to it. Theses arguments are also called ‘parameters’.
Arguments represent the information being passed between the functions. Any number of arguments can be passed to a function. Arguments passed to the function from the called function are just name of the variables that the calling function have.
These are called actual arguments. To receive the values passed by the caller function, the called function must declare same type of variables in the brackets just after the function name. In this context the variables are known as formal arguments. The variable names between the actual and formal arguments may differ, but the type and/or order in which they are displayed and the number of actual and formal arguments must always be the same. If the differ, the program will display an error while compiled.
class final1
{
void add(int x,int y)
{
int sum;
sum=x+y;
System.out.println("sum is"+sum);
}
}
class param
{
public static void main(String args[])
{
int a,b;
a=10;b=19;
final1 aa= new final1();
aa.add(a,b);
}
}
In this program x,y are formal parameters and a,b are actual parameters
Q28. Write an application program to find the largest from the list of n elements.
Ans. import java.io.*;
class nval
{
public static void main(String args[])throws IOException
{
int i,l,n,m=0;
int a[]=new int[100];
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter how many numbers");
n=Integer.parseInt(br.readLine());
for(i=0;i<n;i++)
{
System.out.println("enter"+(i+1)+"number");
a[i]=Integer.valueOf(br.readLine()).intValue();
}
l=a.length;
System.out.println(i);
for(i=0;i<n;i++)
{
if(a[i]>m)
m=a[i];
}
System.out.println("greatest no is"+m);
}
}
Q29. What are string-handling features in java?
Ans. Implementing strings as built-in objects
Allows java to provide a full complement of features that make string handling convenient. For example, java has methods to compare two strings, search for a sub-string, concatenate two strings, and change the case of letters within a string.
Both the Strings and StringBuffer classes are defined in java.lang. They are available to all programs automatically. Both are declared final, which means that neither of these classes may be sub classed.
Following are the String functions:
1. String Length
The length of a string is the number of characters that it contains. To obtain this value, call the length () method
int length()
2. CharAt()
To extract a single character from a string, you can refer directly to an individual character via the charAt() method.
char charAt (int where)
where is the index of the character that you want to obtain.
3. getChars()
If you need to extract more than one character at a time, you can use the getChars() method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[], int targetStart)
4. getBytes()
There is an alternative to getChars() that stores the characters in an array of bytes. This method is called getBytes(), and it uses the default character to byte conversions provided by the platform.
byte[] getBytes()
5. toCharArray()
If you want to convert all the characters in a string object into a character array, the easiest way is to call toCharArray(). It returns an array of characters for the entire string.
It has this general form:
char[] toCharArray()
Q30. Give two different reasons for using named constants (declared with the final modifier).
Ans. Methods are declared final when we want to prevent these methods to override.
Classes are declared final so that these are not inherited.
Final keyword used with variables to make constant declaration, with classes to prevent inheritance, and with method to prevent overriding.
Q31. Write a subroutine with three parameters of type int. The subroutine should determine which of its parameters is smallest parameter should be returned as the value of the subroutine.
Ans. class nav
{
public int small(int a,int b,int c)
{
if(a<b)
{
if(a<c)
return (a);
else
return (c);
}
else
if(b<c)
return (b);
else
return (c);
}
}
class navjeet
{
public static void main(String aa[])
{
nav nn=new nav();
System.out.println(nn.small(34,5,7);
}
}
Q32. Write a subroutine named “stars” that will output a line of stars to standard output. (A star is the character”*”). The number of stars should be given as a parameter to the subroutine. Use a for loop. For example, the command star (20)” would output.
Ans. class nav1
{
void stars(int n)
{
int i;
for(i=1;i<=n;i++)
{
System.out.println(“*”);
}
System.out.println(“ “);
}
}
class navjeet2
{
public static void main(String af[])
{
int j=20;
nav1 nn=new nav1();
nn.stars();
} }
Q33. Write a function named count chars that has a String and a char as parameters. The function should count the number of times the character occurs in the string, and it should return the result as the value of the function.
Ans. class ch1
{
int countchars(String name,char p)
{ int i=0,c=0;
for(i=0;i<name.length();i++)
{
if(name.charAt(i)==p)
c++;
}
return c;
} }
class ch
{ public static void main(String as[])
{ ch1 cc=new ch1();
String s;
int i;
i=cc.countchars("navjeet",'e');
System.out.println("the value of i is"+i);
} }
Q35. Give two one dimensions array A and B, which are sorted ascending order. Write a program to merge them into a single array; the order of C should be n ascending.
Ans.
public clars asc
{
public state void main (string ap [ ])
{
int a[ ] = { 1,2,3,4,5,6};
int b[ ] = { 3,4,5,6,7,8}
int c[ ] = new int [ 12 ]
int I,j,k,
I = 0, j = 0 , k= 0;
while( I < a length & J<b length)
{
if ( a [ e ] < b [ j ];
c [k] = a [I];
I + +;
}
else
{
c [ k ] = b [ ] j;
j + + ;
{k + +;}
if (I < a length)
for (j I <a. length, I + +
c [k + + ] = a [I]
if ( j < b. length
for (; j<b. length; j++)
C [k + +] = b [ J ] ;
For (I = 0; I < C. length;i + +)
{
System. Out print (C [I]
}
}
}
Q36. Write a note on nested class.
Ans. It is possible to define a class within another class; such classes are known as nested classes. The scope of nested class is bounded by the scope of its enclosing class. Thus if class B is defined within class A, than B is known to A, but not outside of A. A nested class has access to the members including private members of the class in which it is nested. However the enclosing class does not have access to the members of nested class.
There are two types of nested classes; static and non-static. A static nested class is one, which has though static modifies applied. Because it is static, it must access the members of its enclosing class through an object, that is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used.
The most important type of nested class is the inner class. A inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static member of the outer class do. Thus, an inner class is fully with the scope of its enclosing class.
Q37. What is use of super keyword?
Ans. Whenever a subclass needs to refer to its immediate super class, it can do so by use of keyword super. Super has two general forms. The first calls the super class constructor. The second is used top access a member of the super class that has been hidden y a member of a subclass.
Example of using super to overcome name hiding.
Class A {
Int i j
}
class B extends A {
int i j
B (int a, int b)
{
super.i = a I \ i in A
I=b I || I in B
}
void show () {
System.out.printIn (“I ‘n superclass:” + super.i);
System.out.printin (“in subclass: “ + c):
} }
class Usesuper {
Public static void main (string args [])
{
B sub Ob = new B (1,2);
SubOb.show ();
}}
The output is :
I in superclass: 1
I in superclass: 2
Although the instance variable I in B hides the i in A super allows access to the I defined in the super class.
Q38. Discuss briefly the protected and private protected level of access protection available level of access protection available in java.
Ans. Classes and packages are both means of encapsulating and containing the name space and scope of variables and methods. Packages act as containers for classes and other subordinate packages. Classes act as containers for data and code. The class is Java’s smallest unit of abstraction. Because of the interplay between classes and packages, Java addresses four categories of visibility for class members.
The three access specifies, private, public and protected provide a variety of ways to produce the many level of access required by following categories.
Private
No modifier
Protected
Public
Same class
Yes
Yes
Yes
Yes
Same package subclass
No
Yes
Yes
Yes
Same package non-subclass
No
Yes
Yes
Yes
Different package subclass
No
No
Yes
Yes
Different package non-subclass
No
No
No
Yes
Q39. Write a Java program to create a Fibonacci series.
Ans. class feb
{
public static void main(String ap[])
{
int a=1,b=0,c=0;
while(c<=21)
{
System.out.println(c);
c=a+b;
a=b;
b=c;
}.
}
Q40. Write an application program to find the largest element from the given list.
{
public static void main(String ap[])
{
int a[]={23,43,4,5,5,67,23,12,23,21,34,56};
int i,max=0;
for(i=0;i<a.length;i++)
{
if(a[i]>max)
max=a[i];
}
System.out.println("largest element is "+max);
}
}
Q41. Write an application/applet to implement the binary search technique.
Ans. class xyz
{
public static void main(String ap[]) {
int t=0, beg=0,end=7,mid=0,i,f=0,j,a[]={5,2,3,4,5,7,9,23},item;
end=a.length-1;
for(i=0;i<a.length;i++)
{
for(j=i+1;j<a.length;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
} }
item=4;
mid=(beg+mid)/2;
while(beg<=end)
{
if(a[mid]==item)
{
f=1;
break;
}
else if(item>a[mid])
beg=mid+1;
else
end=mid-1;
}
if(f==1)
System.out.println(mid);
else
System.out.println("no match found");
}
}
Q42. Write an application program to print prime numbers 1 to 100.
Ans. class my
{
public static void main(String ap[])
{
int n,i,f=0;
for(n=1;n<=100;n++)
{
f=0;
for(i=2;i<n&&f==0;i++)
{
if(n%i==0)
f=1;
}
}
if(f==0)
System.out.print(“ “+n);
}
}
Ans. Java provides you with a special type of class, called an abstract class, which can help you, organize your classes based on common methods. An abstract class lets you put the common method names in one abstract class without having to write the actual implementation code. Following are the key points of abstract class –
Classes, which contain abstract methods, are called abstract classes.
A program cannot instantiated an abstract class as an object.
Abstract classes may contain a mixture of non-abstract and abstract methods. Non-abstract methods implement the method statements.
Any subclass, which extends the class containing abstract methods, must provide the implementation for all the abstract methods; otherwise the subclass itself becomes an abstract class.
Example:
public abstract Class Book{
public abstract String readBook();
public abstract void writeBook(String text);
}
Q44. Write an application program to find the largest from the list of n elements.
Ans. import java.io.*;
class nval
{
public static void main(String args[])throws IOException
{
int i,l,n,m=0;
int a[]=new int[100];
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter how many numbers");
n=Integer.parseInt(br.readLine());
for(i=0;i<n;i++)
{
System.out.println("enter"+(i+1)+"number");
a[i]=Integer.valueOf(br.readLine()).intValue();
}
l=a.length;
System.out.println(i);
for(i=0;i<n;i++)
{
if(a[i]>m)
m=a[i];
}
System.out.println("greatest no is"+m);
}
}
Q45. Write a function named count chars that has a String and a char as parameters. The function should count the number of times the character occurs in the string, and it should return the result as the value of the function.
Ans.
class ch1
{
int countchars(String name,char p)
{
int i=0,c=0;
for(i=0;i<name.length();i++)
{
if(name.charAt(i)==p)
c++;
}
return c;
}
}
class ch
{
public static void main(String as[])
{
ch1 cc=new ch1();
String s;
int i;
i=cc.countchars("navjeet",'e');
System.out.println("the value of i is"+i);
}
}
Q46. What is a Class?
Ans. A class is a programming data structure within which you can group an objects data with the methods that operate on the data.
Example: Here Book defines a class. Title, publisher and price are the properties of the book. Method Book() is the constructor and setBookTitle(String title) is the method that operates on the property of book. Given this book definition we can define as many as book objects that we need.
class Book {
String title;
String publisher;
float price;
Book(){
}
setBookTitle(String title){
}
}
Q47. What is an Object?
Ans. An object is a class variable. An object is a representation of a class that holds data and allows operations to be performed on it self. Class is a definition of a data type whereas an object is a variable or an instance of the class type. An object is a representation of a type that holds data and allows operations to be performed on it self. An Object lets us describe our concept, type or idea in terms of data and methods. Thus becomes a basis for a modular analysis of our problem. The whole problem and solution domain can be represented in terms of objects; objects can interact with themselves producing results.
Example: Here Book is our class which represents a Book type with its attributes and operations. The Book becomes a user defined type variable, which can be declared as an object and used to perform operations, a book type.
class Book
{
String title;
String publisher;
float price;
Book(String title, String pub, float price)
{
this.title=title;
this.publisher=pub
this.price=price;
}
setBookTitle(String title){
}
In the below book, book2 and book3 are objects that represent three different Book types.
public static void main(String args[])
{
Book book1 = new Book(“Chicken soup for soul”,”McGraw Hill”, 10.20);
Book book2 = new Book(“Core Java”,”Sun Press”, 11.20);
Book book3 = new Book(“Thinking in Java”,”Addison Wesley”, 12.20);
}
Q48. What is Inheritance?
Ans. A class inherits state and behavior from its super class. Inheritance provides a powerful and natural mechanism for organizing and structuring software programs. Benefit of inheritance is that subclasses provide specialized behaviors from the basis of common elements provided by the super class. Through the use of inheritance, programmers can reuse the code in the super class many times.
Inheritance extends the concept of Classes and Objects more to facilitate representation of types based on their similarities. Java uses the keywords ‘extends’ and ‘implements’ for applying inheritance. In the example the Class Tool is super class to class ScrewDriver and Saws. The inheriting classes acquire the properties of the super class.
class Tool
{
String color;
float price;
}
class ScrewDriver extends Tool
{
String handleType;
String tipType;
}
class Saws extends Tool
{
String bladeSize;
}
Q49. What is Polymorphism?
Ans. Polymorphism gives us the ultimate flexibility in extensibility. Polymorphism is a term that describes a situation where one name may refer to different methods. In java there are two type of polymorphism: overloading type and overriding type.
When you override methods, java determines the proper methods to call at the program’s run time, not at the compile time. Overriding occurs when a class method has the same name and signature as a method in parent class. Overloading occurs when several methods have same names with different method signature. Overloading is determined at the compile time.
Example: Overloading
Class Book{
String title;
String publisher;
float price;
setBook(String title){
}
setBook(String title, String publisher){
}
setBook(String title, String publisher,float price){
}
}
Example: Overriding
Class Tool{
void operateit(){
}
}
Class ScrewDriver extends Tool{
void operateit(){
}
}
Q50. What are Constructor Methods?
Ans. Constructors from a conceptual level enable the creation of an object of a given class. Constructor is a method of a class with no return parameters. Constructors also enable the initialization of any variables of a class. You can supply input parameters to constructors.
A class can have more than one constructor. It has the same name as the class itself. A default constructor doesn’t have any parameters. In case of inheritance
- If your subclass constructor does not explicitly call the superclass constructor, java will call the super class default constructor. If you want subclass constructor to call a specific superclass constructor, use the ‘super’ keyword.
Example:
class Book
{
String title;
String publisher;
float price;
public Book()
{
}
public Book(String title)
{
this.title = title;
}
}
class TextBook extends Book
{
public TextBook(){
}
public TextBook(String title)
{
super(title);
}
Q51. What Is Garbage Collection?
Ans. A key feature of Java is its garbage-collected heap, which takes care of freeing dynamically allocated memory that is no longer referenced. Because the heap is garbage-collected, Java programmers don't have to explicitly free allocated memory.
The name "garbage collection" implies that objects that are no longer needed by the program are "garbage" and can be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When the program no longer references an object, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such un-referenced objects. In the process of freeing un-referenced objects, the garbage collector must run any finalizes of objects being freed.
The Java programmer must keep in mind that it is not generally possible to predict exactly when un-referenced objects will be garbage collected so it is not possible to predict when object finalizes will be run. Java programmers, therefore, should avoid writing code for which program correctness depends upon the timely finalization of objects.
Although you can't tell Java to explicitly reclaim the memory of a specific de-referenced object, there is a way to tell the JVM to perform garbage collection, which may result in the desired memory being reclaimed. Invoking the garbage collector requires a simple two-step process. First you create a Java Runtime object. Then, after creating the Runtime object, you'll invoke the gc() method ("garbage collector") of the Runtime class.
Runtime r = Runtime.getRuntime();
r.gc();
Q52. Explain Arrays.
Ans. Declaring an array
An array variable is like other variables -- you must declare it, which means you must declare the type of elements that are in an array. All elements must be the same type. Write the element type name, then "[]", then the name of the array variable. The declaration only allocates space associated with a variable name for a reference to an array, but doesn't create the actual array object.
String[] args; // args is an array of Strings
int[] scores; // scores is an array of ints
Unlike some languages, never put the size of the array in the declaration because an array declaration only tells Java that the variable is an array and the element type. Allocating an array object Create an array using new. This example creates an array of 100 int elements, from a[0] to a[99].
int[] a; // Declares a to be an array of ints
a = new int[100]; // Allocates an array of 100 ints
Length of an array
Each array has a constant (final) instance variable that has its length. You can find out how many elements an array can hold by writing the array name followed by length. In the previous example, a.length would be 100. Remember that this is the number of elements in the array, one more than the maximum subscript.
Initial array element values -- zero/null/false
When an array is allocated (with new), all elements are set to an initial value. The initial value is 0 if the element type is numeric (int, float, ...), false for boolean, and null for all object types.
Array variables are references to arrays
When you declare an array variable, Java reserves only enuf memory for a reference (Java's name for an address or pointer) to an array object. When an array object is created with new, a reference is returned, and that reference can then be assigned to a variable. Similarly, you can assign one array variable to another, and it is only the reference that is copied.
For example,
int[] a = new int[]{100,99.98};
int[] b;
// "a" points to an array, and "b" doesn't point to anything
b = a; // now b points t the same array as "a"
b[1] = 0; // also changes a[1] because a and b are the same array.
// Both a and b point to same array with value {100,0,98}
Array Initialization
When you declare an array, you can also allocate a pre-initialized array object in the same statement. In this case, do not give the array size because Java counts the number of values to determine the size.
String[] days = {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};
Q53. Briefly explain how subroutines can be a useful tool in the top-down design of programs.
Ans. The major advantages of using subroutines or functions are as follows:
Efficiency of maintenance of code
The code written as the body of functions makes the task simpler. As it makes program writing easier by dividing the operations of a program into subprogram called functions. Separating the code into modular functions makes the program easier to design.
Ease of understanding
The use of functions makes the program understood easily as each operation performed is placed in a different function. So, it can also be written or checked independently.
Elimination of redundancy of code
This is the major advantage of functions, as we do not have to rewrite the code again and again to perform same type of task.
Functions once defined can be used any number of times just by calling them by their name. Thus, resuming the code once written is another major advantage.
Q55. Why is java known as an Internet Language? Discuss.
Ans. The Internet helped catapult java to the forefront of programming, and java, in turn, has had a profound effect on the Internet. The reason for this is quite simple: Java expands the universe of objects that can move about freely in cyberspace. In a network, two very broad categories of objects are transmitted between the server and your personal computer: passive information and dynamic, active programs. For example, when you read your E-mail, you are viewing passive data. Even when you download a program, the program’s code is still only passive data until you execute it. However, a second type of object can be transmitted to your computer: a dynamic, self-executing program. Such a program is an active agent on the client computer. Java provides applets for Internet programming.
Java can be used to create two types of programs: applications and applets.
An applet is a Java program that runs within the Java enabled web browsers like Netscape Communicator and Internet explorer. Applets often use a graphical user interface and may have text, images, buttons, scrollbars, and sound. Applets can be embedded in HTML.
It is automatically executed by applet-enabled we-browser. Every applet is a subclass of java.applet.Applet
Q56. Write an applet that accepts two texts and concatenates them.
Ans. import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class app extends Applet implements ActionListener
{
/*<applet code="app.class" width=300 height=300></applet>*/
TextField text1,text2;
Button b1;
String s1=" " ,s2=" ",s3=" ";
public void init()
{ text1=new TextField(8);
text2=new TextField(8);
b1=new Button("press for concatenation");
add(text1);
add(text2);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
try
{ s1=text1.getText();
s2=text2.getText();
s3=s1.concat(s2);
}
catch(Exception e1)
{ }
}
public void paint(Graphics g)
{
g.drawString(s3,10,150);
} }
Q57. Create a try block that is likely to generate three types of exception and then incorporate necessary catch block to catch and handle them appropriate.
Ans. class Multicatch {
public static void main (String args []) {
try {
int a = args. Length;
System.out.printin (‘a = + a);
int b = 42 /a;
int c [] = {1} I
c[42] = 99;
int d = “Muni”;
}
catch (ArithmeticExcception e) {
System.out.printin (Divide by 0:” + e);
}
catch (ArrayIndexOutofBoundsException e)
{
System.out.printIn (“Array index out of bound:” + e);
}
catch (NumberformatException e)
{
System.out.printin (“Invalid format;” + e);
}
System.out.printin (“After try/catch blocks”)’
}
}
Q58. Develop an applet that receives three numeric values as input from user and then display the largest of the three on the screen. Write a HTML page also.
Ans. import java.awt. *;
import java. Awt.event. *;
import java. Applet. *;
public class largest extends Applet
Implements Actionlistener {
TextField first, second, third;
public void init ()
{
Label |b|1 = new Label (“first:” Label. RIGHT);
Label |b|2 = new Label (‘Second:” Label. RIGHT);
Label |b|3 = new Label (“Third:” Label. RIGHT);
First = new TextField (3);
Second = new TextField (3);
Third = new TextField (3);
Add (lbl1)
Add (first);
Add (lbl2);
Add (second);
Add (lbl3);
Add (third);
First. add Action Listener (this);
Second.addAction Listener (this);
Third. add Actionlistener (this);
}
public Void action Performed (Action Event ae).
{ repaint();
}
public void paint (Graphics g)
{
int li
int a = parseInt (first. get Text () );
int b = parseInt (second.get.Text (() );
int c = parse Int (third. get. Text ());
if (a > b a>c)
l = ai
else if (b>c)
l = bi
else
l = ci
g.drawstring (“largest is :” t l, 6,60);
}
}
HTML code
<applet code = “Largest” width = 300, height = 50>
</applet>
Q59. Write a note on API.
Ans. The java standard Library includes hundred of classes and methods grouped into several functional packages. Most commonly used packages are:
Language support Package: A collection of classes and methods required for implementing basic features of java.
Utilities Package: A collection of classes to provide utility functions such as date and time functions.
Input/Output Package: A collection of classes required for input/output manipulation.
Networking package: A collection of classes for communicating with other computers via Internet.
AWT Package: The abstract window toolkit package contains classes that implements platform independent graphical user interface.
Applet Package: This includes a set of classes that allows us to create java applets.
Q60. Write a Program to draw lines.
Ans. import java.awt. *;
import java. Applet. *;
/ *
<applet code = “ Lines” width = 300 height = 200>
</applet>
* /
public class lines extends Applet {
public void paint (Graphics g) {
g.drawLine (0,0,100,100);
g.drawLine (0,100,100,0);
g.drawLine (20, 150, 400, 40);
}}
Q61. What are the methods to draw ellipse and circles? Give example.
Ans. Draw oval () in the method to draw circle or ellipse syntax is –
void draw Oval (int top.int left , int width, int height)
E.g.
import java.awt. * i
import java. applet. * i
/ *
< applet code= “Ellipse” width=300 height = 200>
</applet>
* /
public class Ellipse extends Applet {
public void paint (Graphics g) {
g.drawLine Oval (10,10,50,50);
g.fill Oval (100,10,75,50)
g.draw Oval (190, 10, 90, 30);
g.fill Oval ( 70, 90, 140, 100);
}
Q62. Write a Program to draw a polygon and arc.
Ans. import java.awt.* I
import java. applet. * I
/ *
<applet code= “Are poly” width = 400 height=300>
</applet?>
*/
public class Arcpoly extends Applet {
public void paint (Graphics I) {
g.draw Arc ( 10,40,70,70,0,75);
g.fill Arc (100,40,70,70,0,75);
int xpoints [] = { 130,300,130,300,30};
int ypoints [ ] = {130,130,300,300,130} ;
int num = 5;
g.drawPlygon (xpoints, ypoints, num);
}
}
Q63. How does applets differ from application program? Why do applet class need to be declared as public? Write the applet tag with arguments.
Ans.
Applet
Application
1.Applet executes on web browser
1. executes on Command prompt
2. no need of main function to execute
2. every application program need to define main() function in the program
3. no command line argument is passed
We can pass commandline arguments in an application
4. a fast and small program executed on the internet
Program those does not support web browsers
Applet class needs to declare public because applets are launched by the applet tag and that tag can be defined with in the same program and in different .html file. It is declared public because it can be called outside the package in which it is declared.
<applet code=abc.class height=200 width=200>
<param name=”name” value=”raj”>
<param name=”rollno” value=1>
<param name=”class” value=12>
</applet>
Q64. Write an applet that takes an integer and reverse that e.g. 756 to 657.
Ans. import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class app1 extends Applet implements ActionListener
{
/*<applet code=app1 height=200 width=200></applet> */
TextField t,t1;
Label l,r;
Button b;
public void init()
{
l=new Label("Enter no");
r=new Label("Result");
t=new TextField(10);
t1=new TextField(10);
b=new Button("click");
add(l);
add(t);
add(r);
add(t1);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent g) {
String s=t.getText();
int i=Integer.parseInt(s);
int r1=0;
while(i>0)
{
r1=r1*10+i%10;
i/=10;
}
t1.setText(" "+r1);
}
}
Q65. Write an applet that takes the input and compute the factorial.
Ans.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class fact1 extends Applet implements ActionListener
{
/*<applet code=fact1 height=200 width=300></applet> */
Label l,l1;
TextField t,t1;
Button b;
public void init() {
l=new Label("enter number for factorial");
l1=new Label("result");
t=new TextField(10);
t1=new TextField(10);
b=new Button("factorial");
add(l);
add(t);
add(l1);
add(t1);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String s=t.getText();
int n=Integer.parseInt(s);
int f=1;
while(n>1)
{ f=f*n;
n--; }
t1.setText(""+f);
}
}
Q66. Describe a package and its relationship with classes. What is the recommended naming convention for creating your own package?
Ans. The package is both a naming and a visibility control mechanism. You can define classes inside a package that are not accessible by code outside that package. You can define class members that are only exposed to other members of the same package. To create a package includes a package command as the first statement in a java source file. It defines a name space in which classes are stored. If you omit the package statement the class names are put into the default package which has no name.
Java uses file system directories to store packages.
The naming convention used to define package is
Package name must have same as the name of the directory.
A main package can be defined as
Package mypackage;
To define sub package
Package mypackage.mypackage1;
Q67. What is Exception? Also define the types of Exception.
Ans. A Java exception is an object that describes an exceptional condition that has occurred in a piece of code. When an exceptional condition arises an object representing that exception is created and thrown in the method that caused the error.
Types of Exception
All exception types are the subclass of built in class Throwable. Throwable is at the top of all exception class. Immediately below Throwable are two subclasses that partition exception into two distinct branches.
1.Exception 2.Error
Exception: - This class is used for exceptional conditions that user programs should catch. This is also the class that you will subclass to create your own custom exception types. The inbuilt Exception like ArrayIndexOutOfBounds, NumberFormat, SQL, and Arithmetic all are the sub class of Exception Class.
Error: - Which defines exceptions that are not expected to be caught under normal circumstances by your program. It is used by java runtime system to indicate errors.
Q68. Define all the tools used to Handle Exception.
Ans. Java provides different types of tools to handle the exceptions. These are as under.
Try: - In the try block of the Exception handling tool those code are define which can generate exceptions and generated exception is send to catch block to caught, this block is never used without the catch block.
Catch: - A catch block catch the exceptions send by the try block so that the appropriate message can be shown to the user. A try block can have multiple catch blocks but no catch block is used without try block.
Finally: - finally block is the last block and defined after all the try/catch blocks .it will be executed after a try/catch block has completed and before the code following the try/catch block. Finally block will execute whether or not an exception is thrown.
Throws: - A throws clause the list the types of exceptions that a method might throw. This is necessary for all the exception except those of type Error.
Throw: - throw statement is used to throw an exception explicitly by define the new exception class by extending the Exception class.
Q69. Define life cycle of an applet.
Ans. The life cycle of an applet consist of initialization, starting stopping destroying painting etc.
1. Initialization: - initialization occurs when the applet is first loaded. The initialization of an applet might include reading and parsing any parameters of the applet, creating any helper objects it needs, setting up an initial state, or loading images or fonts. To control the behavior of the applet, override the init () method in the applet class
public void init ()
{
}
Starting
After an applet is initialized m it started. Starting is different from initialization because it can happen many times during an applet’s lifetime, whereas initialization happens only once. Starting an also occur if the applet was previously stopped.
public void start ()
{
}
Stopping
Stopping and starting go hand in hand, stopping occurs when the reader leaves the page that contains a currently running objects, or by calling the stop () method. By default when the reader leaves a page, any threads the applet had started will continue running by overriding the stop (). One can suspend the execution of these threads and then restart them if the applet is viewed again.
Public void stop (){}
Destroying
Destroying enables the applet perform a clean up job just before it is destroyed or the browser exits. This object is to destroy an applet from the memory.
Painting
Painting is the way an applet actually draws something on the screen, any drawing object or text can be placed on the screen using draw object painting may occur number of times during an applets life cycle. It can be called again and again by using repaint ().
Q70. Describe the major features of Java exception handling. How is exception handling carried out in java? What are the major statements that are employed in java exception handling and what do they do?
Ans. An exception is a condition that is caused by a run-time error in the program. When the Java interpreter encounters an error such as dividing an integer by zero, it creates an exception object and throws it. The purpose of exception handling mechanism is to provide a means to detect and report an “exceptional circumstance” so that appropriate action can be taken.
Features
Structured exception handling.
Provide security from executing illegal instruction those prone to termination of the program.
Use the concept of object oriented approach to handle exceptions.
User defined exception can also be handled.
Following are the major statements to handle exceptions
Try: - Program statements that you want to monitor for exceptions are contained within a try block.
Catch: - If any exception occurs within the try block, it is thrown. These exceptions are caught in catch block.
Finally: - Finally is the last block that will always execute although exception is raised on not.
Throw: - Use to throw exception manually.
Throws: - To explicitly throws the exception.
Q71. Explain the methods used to create lines, circles, rectangles and ellipses.
Ans. Method to create Line: -
DrawLine () –The drawLine() method takes two pairs of coordinates,(x1,y1) and (x2,y2) as arguments and draws a lone between them. The following statement draws a straight line from the coordinate point (10,10) to (50,50):
E.g.
g.drawLine(10,10.50,50);
DrawOval ()— darwOval () method is used to draw circle as well as ellipse. This method takes four arguments: the first two arguments represents the top left corner of the imaginary rectangle and another two represents the width and height of the oval itself. Note: -if the width and height are same then the ellipse becomes circle.
E.g.
g.drawOval(20,20,200,120)//draws a ellipse
g.drawOval(70,30,100,100)//draws a circle.
g.drawRect( )—Used to draw a rectangle. This method takes four arguments the first two arguments represents the x and y coordinates of the top left corner of the rectangle,and the remaining two represent the width and height of the rectangle.
E.g. g.drawRect(10,10,50,50)
Q72. What do you mean by Layout Manager? What are the various types of Layout?
Ans. A layout refers to arranging and placing of the component in container. A Layout manager will determines how components will be arranged when they are added to a container.
Types of Layout
1. FlowLayout: - The default layout of the container. The FlowLayout class is the simplest of layout manager. It layouts the components in similar way as Word place data in there pages. It provides the following constructor
FlowLayout(), FlowLayout(FlowLayout.LEFT);
2. GridLayout: - The GridLayout manager arranges components into a grid of rows and columns. Components are added first to the top row of the grid.
The following constructor are provided by GridLayout
GridLayout(), GridLayout(row,col), GridLayout(row,col,hrz,vert);
3. BorderLayout: - Divide the container into five different sections. These sections are: SOUTH, EAST, WEST, NORTH, CENTER.
Provide two constructors
BorderLayout()
BorderLayout(int,int);
4. CardLayout: - In CardLayout the components are arranged in the card style and some of the components can be hidden or viewed using this layout. In this layout other layout can be mixed to manage different container components inside the main container.
Ans. AWT stands for abstract widows toolkit. It is one of the packages defined in java, which provides the graphical user interface defining different types of containers and components implementing different types of listeners for event handling. In the AWT class hierarchy component class is at the top of all classes , container comes after then window and panel classes.
AWT used different types of containers and components.
Containers
1. Window
2. Frame
3. Panel
Components
1. Label
2. TextField
3. Button
4. Choice
5. MenuItems
6. List
7. TextArea
8. Scrollbar
Q74. Write a program to draw parrellogram.
Ans. import java.awt. *;
import java.applet. *;
class pr extends Applet
{
public void extends Applet
{
int x[] = {10,100,150,50};
int y[] = {10,10,100,100};
g.drawPolygon (x,y,z);
}
}
Q75. What advantages do java’s Layout Managers provides over traditional windowing system?
Ans. Layout Mangers in java provides us the way to arrange components in windows programming or applet programming. There are different types of layout Manager provided by java using java.awt package.
1. Flow Layout 2. Border Layout 3. GridLayout. 4. Cardlayout.
Layout Manager helps us to place the components on the container, as we want to place. Every layout provides different types of style, to place the components and make easy to arrange component on traditional windowing system.
Flow layout is the difficult layout Manager for java window application.
Using layout managers we can align components to left and right.
Using Layout Manager we can place different component in different position like center, left, top, right and bottom. For this we can use, BorderLayout.
Required components can be hidden using CardLayout.
Components can be arranged in tabular form using GridLayout.
Q76. Write a short note on VPN.
Ans. Virtual Private Network (VPN) is a network that is connected by using public wires to connect nodes. For Example there are a number of systems that enables you to create networks using the Internet as the medium for transporting data. These systems are use encryption and and other security mechanisms to ensure that only authorized users can access the network and that the data cannot be intercepted.
VPN provide a logical connection over which data is encapsulated. Typically, both encapsulation and encryption are performed and the tunnel is a private, secure link between a remote user or host and a private network.
Advantages:
Allows mobile professionals and telecommuter’s access their corporate network over the Internet
it costs less than traditional remote access solutions3
Makes use of the telephone networks massive switching system
Accessing LAN is secure because the connection is encrypted.
Protocol used in VPN:
Pont to Point Tunneling Protocol
Layer 2 Tunneling Protocol
Q77. What is a stream class? How are the stream classes classified?
Ans. A stream in Java is a path along which data flows. It has a source and destination. Both the source and the destination may be physical devices or programs or other steams in the same program.
In java stream classes are categorized into two groups based on the data type on which they operate.
1 ByteStream classes
2 Character Stream classes
Byte Stream classes have been designed to provide functional feature for creating and manipulating streams and files for reading writing bytes. These streams are uni-directional; they can transmit bytes in only one direction. There are two kinds of byte stream classes: Input stream classes an Output stream classes.
Character Stream classes were not a part of the language when it was released. They were added later when the version 1.1 was announced. Character streams can be used to read and write 16 bit Unicode characters. There are two kinds of character stream classes, namely, Reader stream classes and Writer stream classes
Q78. What do you mean by system package?
Ans. Java provides predefined packages. User can import theses packages according to its requirements. In package you can define classes. All built in java classes stored in packages. There are no core java classes in the unnamed default package. All of the standard classes are stored in some named package. Classes within packages must be fully qualified with their package name. It could become tedious to type in the long dot separated package path name for every class you want to use. For this reason, java includes the import statement to bring certain classes, or entire packages, into visibility.
Once imported, a class can be referred to directly using only its name. The import statement is a convenience to the programmer and is not technically needed to write a complete java program. The general form of the import statement:
Import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top level package, and pkg2 is the name of a subordinate package inside the outer package separated by a dot.
Q79. What is a Servlet?
Ans. A Java application that, different from applets, runs on the server and generates HTML-pages that are sent to the client. Servlet technology was developed to replace the less efficient CGI technology. The Servlet class is not in the Core API for the JDK.
It can be thought of as an applet that runs on a server. The biggest difference between the two is that a Java applet is persistent. This means that once it is started, it stays in memory and can fulfill multiple requests. The persistence of Java applets makes them faster because there's no wasted time in setting up and tearing down the process.
Servlets can run on browsers that are not Java-enabled. Servlets are designed to support a request/response computing model that is commonly used in web servers. In a request/response model, a client sends a request message to a server and the server responds by sending back a reply message.
Q80. What is JDBC?
Ans. Java Database Connectivity - JDBC is a Java API for executing SQL statements. By using the JDBC API a program can access almost any data source, from relational databases to spreadsheets to flat files.
Following are some benefits of JDBC: Aside from being easy to write, using the JDBC API also brings the following benefits:
Since JDBC is included with the Java Platform, it is available everywhere Java is available. This makes the Java application that uses the JDBC API portable to a lot of platforms.
Since Java applications that uses the JDBC API uses only interfaces from the JDBC packages, the code has a high likelihood of being portable from one vendors database to another's.
The JDBC API encourages Java applications to be designed into multiple tiers, separating business logic from presentation logic. This will aid the scalability, reliability and maintainability of the application tremendously.
Robustness, security, automatically downloadable code, and other Java pluses. By virtual of being written in Java, the JDBC application automatically enjoys these benefits that Java offers.
Q81. What is Swing?
Ans. The javax.swing package of classes is used to create GUI (Graphical User Interface) components for applets and applications. Project Swing classes enable programmers to specify a different look and feel for each platform, or a uniform look across all platforms. Swing is the project code name for the lightweight GUI components.
Swing is a large set of components ranging from the very simple, such as labels, to the very complex, such as tables, trees, and styled text documents. Almost all Swing components are derived from a single parent called JComponent, which extends the AWT Container class. Thus, Swing is best described as a layer on top of AWT rather than a replacement for it.
If you compare this with the AWT Component hierarchy you will notice that for each AWT component there is a Swing equivalent with prefix "J". The only exception to this is the AWT Canvas class, for which JComponent, JLabel, or JPanel can be used as a replacement. You will also notice many Swing classes with no AWT counterparts.
Q82. What is JAVABEANS?
Ans. Java Beans is the software component architecture for the Java language.
A Java Bean is a Java class that defines properties and that communicates with other Beans via events. Software components have properties, which are attributes of the object. Customization is the process of configuring a Bean for a particular task. Properties can be defined within the Java Bean class definition, or they can be inherited from other classes. A Bean, however, is not required to inherit from any particular class or interface.
Java Beans that represent graphical components and that are meant to be visible must inherit from a java.awt.Component, so that they can be added to visual containers.
There are Beans that are not meant to be visible, and they are referred to as invisible Beans. They are identical to other Java Beans except that they have no GUI representation.
Q83. How does JSP differ from Servlets?
Ans. Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with dynamically generated HTML. Servlets, make you generate the entire page via your program, even though most of it is always the same. JSP lets you create the two parts separately. Java Server Pages (JSP) is a Sun Microsystems specification for combining Java with HTML to provide dynamic content for Web pages. When you create dynamic content, JSPs are more convenient to write than HTTP servlets because they allow you to embed Java code directly into your HTML pages, in contrast with HTTP servlets, in which you embed HTML inside Java code. JSP is part of the Java 2 Enterprise Edition (J2EE).
JSP enables you to separate the dynamic content of a Web page from its presentation. It caters to two different types of developers: HTML developers, who are responsible for the graphical design of the page, and Java developers, who handle the development of software to create the dynamic content. Example of JSP –
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>Welcome to Our Store</TITLE></HEAD>
<BODY>
<H1>Welcome to Our Store</H1>
<SMALL>Welcome,
<!-- User name is "New User" for first-time visitors -->
<% out.println(Utils.getUserNameFromCookie(request)); %>
To access your account settings, click
<A HREF="Account-Settings.html">here.</A></SMALL>
<P>
Regular HTML for all the rest of the on-line store's Web page.
</BODY>
</HTML>
Q84. What is Multithreading?
Ans. A thread executes a series of instructions. Every line of code that is executed is done so by a thread. Some threads can run for the entire life of the applet, while others are alive for only a few milliseconds.
Multithreading is the ability to have various parts of program perform program steps seemingly at the same time. Java let programs interleave multiple program steps through the use of threads. For example, one thread controls an animation, while another does a computation. In Java, multithreading is not only powerful, it is also easy to implement.
You can implement threads within a java program in two ways – Creating an object that extends Class Thread or implementing the interface Runnable.
The key difference between the two is that Thread class has a start() method which your program simple calls whereas the Runnable class does not have a start method and you must create a Thread object and pass your thread to its constructor method. You never call run() method directly; the start method calls it for you.
Example: Extending thread class
Class MyProcess extends Thread
{
Public void run()
{
}
public static void main(String args[])
{
MyProcess mp = new MyProcess();
mp.start();
}
}
Example: using Runnable interface
Class MyProcess implements Runnable
{
Public void run()
{
}
public static void main(String args[])
{
Thread mp = new Thread(new MyProcess());
mp.start();
}
}
Q85. What is Event Handling?
Ans. Almost all programs must respond to commands from the user in order to be useful. Java's AWT uses event driven programming to achieve processing of user actins: one that underlies all modern window systems programming. Within the AWT, all user actions belong to an abstract set of things called events. An event describes, in sufficient detail, a particular user action. Rather than the program actively collecting user-generated events, the Java run time notifies the program when an interesting event occurs. Programs that handle user interaction in this fashion are said to be event driven.
There are three parts to the event model in Java:
Event object - this is an instance of a Java class that contains the characteristics of the event. For example, if the event is generated from clicking a mouse button, the event object would contain information such as the coordinates of the mouse cursor, which button was clicked, how many times it was clicked, etc.
Dispatching class/method - this is an object, which detects that an event has occurred and is then responsible for notifying other objects of the event, passing the appropriate event object to those objects. These other objects are "listeners" for the event. Most AWT components, such as Button, List, Textfield, etc. are examples of dispatching classes.
A Button, for instance, is capable of notifying other components when it is "pushed." These classes will typically have a set of two methods that can be invoked by would-be "listeners": one to tell the class that the object wants to listen and another to tell the class that the object no longer wants to listen.
These methods are conventionally named i.e. addxxListener (to add an object as a listener) or removexxListener (to remove the object as a listener). Here ‘xx’ is the specific type of event to listen for. In the case of the Button, this would be "Action" to indicate the action of pushing the button. (So the methods would be addActionListener and removeActionListener).
Listener Interface - for the dispatching to work properly, the dispatching class must be able to rely on each of its listeners to contain the method that it executes when the event occurs. This is easily accomplished in Java through the use of an Interface class. The important point is that a class, which is going to be a listener, must implement that interface.
Q86. Discuss RMI architecture.
Ans. RMI architecture consists of four layers: the application, stubs/skeletons, remote references and the transport layer.
The following diagram shows the RMI layers:
The Application Layer: - This layer contains the actual implementation of the client and server applications. It is in this layer that high-level calls are made to access and export remote objects.
The proxy Server: - This layer contains the client stub and server skeleton objects. The application layer communicates with this proxy layer directly. All calls to remote objects and marshaling of parameters and return objects are done through these proxies.
The Remote Reference Layer: - The RRL handles packaging of a method call and its parameters and its return values for transport over the network.
The RRL uses a server-side and the client-side component to communicate via the network layer.
The Transport Layer: - The transport layer sets up connections, manages existing connections and handles remote objects residing in its address space.
Ans. InputStream is an abstract class that defines java’s model of steaming byte input. All of methods in this class will throw an I/O Exception or error conditions. It provides different methods to handle input
Int available(),void close(),void mark(int numBytes),Boolean markSupported(),int read(),void reset()
OutputStream: - OutputStream is an abstract class that defines streaming byte output. All of the methods in the class return void value and throw IOException in the case of error. Methods of OutputStream.
void close(),void flush(),void write(int b).
Reader: - Reader is an abstract class that defines java ‘s model of streaming character input. All of the methods in this class will throw an IOException on error condition.
abstract void close(),void mark(int numchars),boolean markSupported()
int read(),void reset()
Writer: - Writer is an abstract class that defines streaming character output. All of the methods in the class return a void value and throw an IOException in the case of errors.
Q88. How does multi threading improves the performance of java?
Ans. Multi threading is the new feature in programming languages. Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded programs. This means that we need not wait for the application to finish one task before beginning another. For example we can listen to an audio cup 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 application. It also facilitates to improve the performance of processor by decreasing idol ness of the processor, which also helps us to incur overall performance of java programs.
Q89. How does multi threading improves the performance of Java? Why are they used?
Ans. Multi threading enables user to write very efficient program that make maximum use of the CPU, because idle time can be kept to a minimum. This is especially important for the interactive, networked environment in which Java operates, because idle time is common. Some specific reasons for using threads:
Improved response to events: By assigning a thread to each event source or task, and prioritizing the threads, you might be able to make your programs more responsive because low priority tasks will yield to high-priority tasks.
Parallel computing: If you are using multiprocessor computer, you can use java’s threads to keep all your CPUs busy, there by earning a greater return on your hardware environment.
Internet concurrency in Java itself: Many of Java’s objects, particularly the Abstract Window Tool kit (AWT) objects, use threads.
Q90. Differentiate between dynamic binding and message passing.
Ans. Dynamic Binding: Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that code associated with a given procedure call is not known until the time of the call at runtime. It is associated with polymorphism and inheritance. A procedure call associated with a polymorphism reference depends on the dynamic type of that reference.
Message Communication: An object-oriented program consists of a set of objects that communicate with each other. The process of programming in an object oriented language, involvers the following steps;
Creating classes that define objects and their behaviors
Creating objects from class definition.
Establishing communication among objects. Objects communicate with one another by sending and receiving information much the same way as people pass message it one another.
A message for an object is a request before execution of a procedure, and therefore will invoke a method (procedure) in the receiving object that generates the desired result.
Q91. What is dynamic method dispatch? Explain with example.
Ans. Dynamic method dispatch in the mechanism by which a call to an overridden function is resolved at runtime, rather than compile time. Dynamics method dispatch is important because this is how java implements runtime polymorphism.
A subclass object can access a super class reference variable. Java uses this fact to resolve calls to overridden methods at runtime. When an overridden method is called through a super class reference, Java determines which version of that method to execute upon the type of object being referred to at the time the call occurs. Thus, this determination in made at runtime. When different types of objects are referred to, different versions of an overridden method will be called. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed. Therefore if a superclass contains a method that is overridden by a subclass, then when different types of objects are referred to through a superclass reference variable, different versions of the methods are executed.
Example: Dynamic method Dispatch
class A
{
void callme ()
{
System.out.printIn (“Inside B’s callme method”);
}
}
class B extends A
{
// override callme ( )
void callme ( )
{
System.out.printIn (“Inside B’s callme method”);
}
}
class C extends A
{
// override callme
void callme ( )
{
System.out.printIn (“Inside C’s callme”);
}
}
class Dispatch
{
public static void main (String args [])
{
A a = new A C);
B b = new B ();
C c = new C ();
A r;
R = a; // r refers to object of A
r.callme (); // calls A’s version of callme
r = b ; // r refers to B object
r. callme (): // calls B’s version of callme
r=c; // r refers to a C object
r.callme () ; // calls C’s version of callme
}
}
Q92. Write a short note of Collection Framework.
Ans. The Java collection framework standardizes the way in which groups of objects are handled by your programs. Java provides ad hoc classes like Dictionary, Vector, Stack and Properties to store and manipulate groups of objects. It was designed to meet several goals. First, the framework had to be big-performance. Another item created by the collections framework is the Iterator interface. An iterator gives you a general-purpose, standardized way of accessing the elements within a collection one at a time. An iterator provides a means of enumerating the contents of a collection. Because each collection implements Iterator, the elements of any collection class can be accessed through the methods defined by Iterator.
The framework defines several map interfaces and classes. Maps store key/value pairs although maps are not “collection” they are fully integrated with the collection view of map.
Q93. Java provides many I/O classes. Can you provide a summary to make things easier?
Ans. The I/O classes defined by the java.io package are:
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
CharArrayReader
BufferedReader class is one of the class define under the java.io package. Because System not define any method to take input from the keyboard. Buffered Reader class provides to read and readLine method read data from the keyword also generate exception called IOException. read () is used to read a character from keyboard and readLine() method is used to read a line of character from the keyboard. It can be explain by the following example.
class my
{
public static void main(Strring ap[]) throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
int a,b,c;
System.out.print (“Enter 1st no”);
a=Integer.parseInt(br.readLine());
System.out.print (“enter 2nd no”);
b=Integer.parseInt(br.readLine());
c=a+b;
System.out.println (“sum is “+c);
}
}
in this class file there is BufferedReader object which access the readLine() method to get the value from keyboard.
9 docs|1 tests
|
1. What are the important long questions for Core Java viva and interview preparation? |
2. How does inheritance work in Core Java? |
|
Explore Courses for Software Development exam
|