Core Java - knowledgebounce

advertisement
SUBJECT: CORE JAVA
Section – A
[QUESTIONS 1 TO 31]
Q1.
Ans.
Q2.
Ans.
Q3.
Ans.
Q4.
Ans.
Q5.
Ans.
Q6.
Ans.
1/54
2 Marks Questions
[PAGE 1 TO 5]
How does java differ from c & c++?
The major difference between java and C: is that java is an object-oriented
language and has mechanism to define classes and objects. Whereas C is a
procedural language.
The major difference between java and C++: Java is a purely object oriented
language whereas C++ is not purely object oriented language. C++ is C with objectoriented extension.
What is object oriented programming?
Object oriented programming is a way to develop applications by using objects as
building blocks. Object oriented programming involves creating application-using
objects, which emulate real world objects in behavior and appearance. The oops is
as a set of objects that work together in predefined ways to accomplish tasks.
What is JAVA?
Java is a programming language developed by Sun Microsystems which is designed
after C++ programming language. However it is architect to be simpler and safer than
C++ hence takes away some language features of C++ and adds more to it. It is
Object-Oriented and portable across multiple platforms and operating systems.
Once compiled a java program can be executed on different platforms. Compiling
java program generates byte-code; an intermediate level of machine code that is
further interpreted by an engine that understands this intermediate level of machine
code to convert it to the native code of say different platforms like Windows, Solaris,
Linux and MacOS etc. This feature makes Java platform independent.
What is Byte-Code?
Byte-codes are the basis of Java’s platform independent. You either compile or
interpret a program in most programming languages. However a Java program is
both compiled and interpreted. With the compiler, a program is translated into an
intermediate language called Java byte-code, which is the platform-independent
code interpreted by the interpreter on the Java platform.
The interpreter parses and runs each Java byte-code instruction on the computer.
Compilation happens just once; interpretation occurs each time the program is
executed. Essentially, byte-codes are the machine language instructions of the Java
virtual machine. These byte-codes further get converted to the native machine code
by the interpreter engine.
What is JVM?
The Java virtual machine executes instructions that a Java compiler generates. Java
Virtual Machine is the base for the Java platform and is ported onto various
hardware-based platforms. Every Java interpreter, whether it's a development tool or
a Web browser that can run applets, is an implementation of the Java VM.
The Java virtual machine has a knowledge of the Java programming language. It
understands a particular binary format, the class file format. A class file contains Java
virtual machine instructions (or byte-codes) and a symbol table and other supportive
information. JVM imposes strong security by having format and structural constraints
on a class file. This leads to an interesting outcome, any language with functionality
that can be expressed in terms of a valid class file can be hosted by the Java virtual
machine.
What is JAVA Platform?
We need a software engine to write, compile and run programs in for any language,
be it C++, C# or Java. Java Platform is the most basic engine that you will require to
write and compile a Java Program. It is a software platform that you install on the top
of any Hardware Platform like Windows, Sun or Mac OS.
SUBJECT: CORE JAVA
2/54
Java Platform has two components
Java Virtual Machine (JVM) and Java Application Programming Interface (Java API).
Q7.
Ans.
Q8.
Ans.
Q9.
Ans.
What is JDK?
JDK is the acronym for Java Development Kit- essentially a Java platform, consisting
of the API classes, a Java compiler, and the Java Virtual Machine interpreter. The
JDK is used to compile Java applications and applets. The most current version is
the J2SE.
If you use J2SE 1.2 and later to develop applications, you are using what's known as
the Java 2 Platform. The latest Java 5 or J2SE 1.5 is Sun’s most ambitious upgrade
that has several enhancements to the Java language that did not exist so far.
What is Encapsulation?
Encapsulation provides the basis for again modularity- by hiding information from
unwanted outside access and attaching that information to only methods that need to
access it. This binds data and operations tightly together and separates them from
external access that may corrupt them intentionally or unintentionally.
Encapsulation is achieved by declaring variables as Private in a class- this gives
access to the data to only member functions of the class. A next level of accessibility
is provided by the Protected keyword which gives the derived classes the access to
the member variables of the base class- a variable declared as Protected can at
most be accessed by the derived classes of the class.
What are the advantages of encapsulation in object oriented software
development?
Advantages of encapsulation:
1. Encapsulation is the process to hide data from the outside world.
2. It provides security so that only valid object can access the data of a class
using class methods.
3. It helps in job specification by methods defined under the class.
Q10.
Ans.
Q11.
Ans.
Q12.
Ans.
What is casting?
Casting is the process to convert the data type of a variable from one to another
For a statement, Java provides two types of casting:
1. Implicit typecast happens when data type is automatically converted from lower
to higher data type.
2. Explicit typecast happens when we want to convert a higher data type to lower
type.
What is the difference between java 1.1 and java 1.2?
Java 1.2 provides some additional features those are not present in java1.1.
These features are
1. Swings programming
2. Collection Objects
3. JIT compiler
4. More flexible security features etc.
Name all the Lexical issues provided by java.
Whitespaces, identifiers, literals, comments, separators, keywords.
SUBJECT: CORE JAVA
Q13.
Ans.
Define all the Data types used in Java.
Name
Long
Int
Short
Byte
Float
Double
Float
Char
Boolean store true/false
Q14.
Ans.
Q16.
Ans.
Q17.
Ans.
Q18.
Ans.
Width
64
32
16
8
32
64
32
16
Name all bit wise operators used in Java.
Operator
~
&
|
^
>>
>>>
<<
&=
!=
^=
>>=
>>>=
<<=
Q15.
Ans.
3/54
Result
Bitwise unary Not
Bitwise And
Bitwise or
Bitwise exclusive or
Shift right
Shift right zero fill
Shift left
Bitwise and assignment
Bitwise or assignment
Bitwise exclusive or assignment
Shift right assignment
Shift right zero fill assignment
Shift left assignment
What is the use of Compiler class?
The Compiler class supports the creation of Java environments in which java byte
code is compiled into executable code rather than interpreted. It is not for normal
programming.
Which ‘+’ is addition? Which is concatenation?
If neither operand of + is a reference to a String object, the operator is the arithmetic
addition operator, not the string concatenation operator. The language defines the +
operator to have a meaning that is fundamentally different from arithmetic addition if
at least one of its operands is a String object. Then it is used to concatenate or
combine two strings.
Write a note on Abstraction.
It is an essential element of object-oriented programming. Humans manage
complexity through abstraction. It is the process of hiding details from user , those
are not necessary for users. A powerful way to manage abstraction is through the
use of hierarchical classifications. This allows you to layer the semantics of complex
systems, breaking into more manageable pieces.
What are hardware and software requirements to run Java?
Because java runs on many platforms, you can run java programs on any machine
and any operating system. It requires a fast processor, simple memory and 256 color
(or better) video support.
SUBJECT: CORE JAVA
Q19.
Ans.
Q20.
Ans.
Q21.
Ans.
Q22.
Ans.
Q23.
Ans.
Q24.
Ans.
Q25.
Ans.
Q26.
Ans.
4/54
More you needA text editor
Development tools like JDK KIT
Java enabled web browser- Netscape Navigator, Internet Explorer.
What is difference between Boolean & operator and the logical && operator?
Boolean and (&) operator, compares two number by every bit of that number but
Logical and (&&) operator, compares two numbers as whole.
When sending command-line arguments to java or javac the * character is
treated as a wildcard. How can I quote it?
class star
{
public static void main(String app[])
{
String h;
h=app[0];
System.out.println(h);
}
}
In this program, if we pass simple *(star) it will return any file name with class
extension which is stored in buffer.
For example abc.class
If we Quote it with “*” Then it will return * character.
For example *
Why java is Dynamic programming?
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. This makes it possible
to dynamically link code in a safe and expedient manner. In the applet environment,
byte code may be dynamically updated on a running machine.
What are the advantages of encapsulation in object oriented software
development?
Advantages of encapsulation
1. Encapsulation is the process to hide data from the outside world
2. It provide security so that only valid object can access the data of a
class using class methods.
3. It helps in job specification by methods defined under the class.
Why Java is important to the Internet?
Java expands the universe of objects that can move about freely in cyberspace. Java
provides the secure transaction on the Internet using applet programming. This
program can run on java enabled web browser with more security like firewall etc.
How java provides double security?
Java is both compiled and interpreter based language. Java compiles the program
and convert it into the byte code. All the syntax errors are checked at that time. After
that, it is converted into native and runtime exceptions are checked.
So a java program checked double time before it run and thus provide double
security.
Define Date class.
The Date class encapsulates the current date and time and provides numbers of
methods to manipulate Date.
What are stream classes?
Java’s stream based I/O is built upon four abstract classes : InputStream
OutputStream, Reader and Writer. Input/Output Stream are designed for byte
streams. Reader and Writer are designed for character streams. These classes have
the separate hierarchies.
SUBJECT: CORE JAVA
Q27.
Ans.
Q28.
Ans.
Q29.
Ans.
Q30.
Ans.
Q31.
Ans.
5/54
Byte Stream Classes: These are the classes that provide support for handling I/O
operations on bytes.
Character Stream Classes: These are the classes that provide support for managing
I/O operations on characters.
On the Internet, applet provides these security feature on the body that can alter the
applet if it is transfer to the client machine.
Define vector. What are advantages of Vector over arrays?
Vector class can be used to create a generic dynamic array known as vector that can
hold objects of any type and any number. The objects do not have to be
homogeneous. Vector are created like arrays:
E.g. Vector list = new Vector (5);
Advantages:
 It is convenient to use vectors to store objects.
 A vector can be used to store a list of objects that may vary in size.
Creation of an array involves three steps:
 Declare the array.
 Create memory locations.
 Put values into the memory locations.
E.g. int age[]= new int[5];
We can add and delete objects from the list as and when required.
Explain the syntax of for loop in java.
For (initialization; test condition; increment)
{
Body of loop
}
In this, first the number is initialized and then checks for the condition, if the condition
is true then body of the loop will be executed and then value is incremented
according to the increment condition given in the for loop.
What is the value of int variable ‘a’ after execution of the following program
segment?
Int a=-1;
a=a>>>24;
The answer is 225.
What is a symbolic constant?
Constants are fixed they cannot be changed. Symbolic constant names provided to
the values and that value can be accessed with that name.
For example pi and exp defined in the math class , which is defined in the java.lang
package.
What are the three parts of a simple empty class?
There are three parts of a class:
1.Class name
2.Body of the class
3.Closing of the body
SUBJECT: CORE JAVA
Section – A
[QUESTIONS 1 TO 20]
Q1.
Ans.
Q2.
Ans.
Q3.
Ans.
Q4.
Ans.
6/54
5 Marks Questions
[PAGE 5 TO 13]
Write a short note on web browsers.
Web browser is special software, which is used to execute web pages.
It can do following functions:
1. Connect to an appropriate server.
2. Query the server for the information to be read.
3. 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.
Why java is known as an Internet Language? Discuss.
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.
Explain Java Applets and Applications.
Java can be used to create two types of programs: applications and applets.
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. There is no need to
include main method.
Applications: An application is a program that is executed by the operating system
of your system. It must have main method.
Explain the important features of java.
Features of java
 Simple
 Object-oriented
 Robust
 Multithreading
 Architecture-neutral
 Interpreted
 Dynamic
 Distributed
SUBJECT: CORE JAVA
7/54
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. Its syntax is similar to the C language.
Object oriented: Java is a true object oriented language.
Robust: Java is a strictly typed language, it checks your code at compile time and it
also checks your code at run time. Java does garbage collection by itself.
Multithreaded: It supports multithreaded programming, which allows you to write
programs that do many things simultaneously.
Architecture-Neutral: The main goal was “write once; run anywhere, any time.
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.
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.
Ans.
Q6.
Ans.
Q7.
Ans.
What is operator ‘+’: Concatenation or Addition?
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
What are the command line arguments? How they are used?
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 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
List a few areas of application of oops technology.
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 using 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.
SUBJECT: CORE JAVA
Q8.
Ans.
Q9.
Ans.
8/54
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
Write the characteristics of object oriented Programming.
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 description of these
properties are given as follows:
Abstraction: It is used to specify new abstract data types (ADT). It is used to hide
unnecessary details from the user. Abstraction refers to the act of representing
essential features without including the background details or explanations.
Encapsulation : It is the process of wrapping up the data and methods inside a
class. The data is not accessible to the outside world and only those methods, which
are wrapped inside the class, can access it. This insulation of the data from direct
access by the program is called data hiding.
Inheritance : It is the process of inheriting the characteristics of one class by
another. It is the process in which the objects of one class acquire the properties of
objects of another class. Inheritance supports the concept of hierarchical
classification. The class that is inherited is known as the base class and the class
that inherits the base class is the child class. The concept of inheritance provides the
idea of reusability.
Polymorphism : It is the process in which one interface is used by multiple methods.
Polymorphism means the ability to take more than one form. It allows objects having
different internal structures to share the same external interface.
Explain the structure of Java Program.
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 what is the purpose of classes and
objects. 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 need 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 classes 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
are the primary and essential elements of a java program. These classes are used to
SUBJECT: CORE JAVA
Q10.
Ans.
9/54
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 class is 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.
Write a note on Java tokens.
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:1. Reserved keywords
2. Identifiers
3. Literals
4. Operators
5. 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 , 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 operators 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 .
SUBJECT: CORE JAVA
Q11.
Ans.
Q12.
Ans.
Q13.
Ans.
10/54
Explain the scope of variables declared in Java.
Java variables are actually classified into three kinds:
Instance variable
Class variable
Local variable.
Instance and class variables are declared inside a class.
Instance variables: These are created when the objects are instantiated and
therefore they are associated with the objects. They take different values for each
other.
Class variables: These are global to a class and belong to entire set of objects that
class creates. Only one memory location is created for class variable.
Local Variables : Variables declared inside methods are called local variables. They
are not available for use outside the method definition.
Explain the Bitwise logical and shift operators.
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
0
0
1
1
0
1
0
1
0
0
0
1
0
1
1
1
0
1
1
0
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
Explain various tools that are used to create and run a program.
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.
SUBJECT: CORE JAVA
11/54
 JavaMaker, a Window 95/ Windows NT product.
Q14.
Ans.
Q15.
Ans.
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.
What do you mean by “java is Architecture Neutral”?
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. It can run on any platform provided that
the JVM is installed on that platform.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.
Explain literals in java.
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
Boolean Literals
The only valid literals of Boolean type are true and false. For example,
1. boolean isBig=true;
2. 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,
SUBJECT: CORE JAVA
12/54
Char c1=’\u4567’;
Java supports a few escape for denoting special characters:
 ‘\n’ for new line
 ‘\r’ for return
 ‘\t’ for tab
 ‘\b’ for backspace
 ‘\f’ for formfeed
 ‘\’ ‘ for single quote
 ‘\ ” ’ for double quote
 ‘\\’ for backslash
Integral Literals: Integral literals may be expressed in decimal, octal, or hexadecimal.
The default is decimal. To indicate octal, prefix the literal with 0x or 0X; the hex
digits may be upper- or lower. The value twenty-eight may thus be expressed in six
ways:
 28
 034
 0x1c
 0x1C
 0X1c
 oX1c
 oX1C
Floating point Literals: A floating point literal express a floating-point number. In
order to be interpreted as a floating- point literal, a numerical expression must contain
one of the following:
 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
String Literal : A string literal is a sequence of characters enclosed in double quotes.
For example String s= ”character in a strings are 16-bit Unicode.”;
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
Does java supports pointer justify your answer?
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
SUBJECT: CORE JAVA
13/54
typed language, it checks your code at compile time, it also checks your code at run
time.
Q17.
Ans.
Q18.
Ans.
Explain history of java.
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 platform 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
that they had added 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
Explain Mathematical Functions used in java.
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.
Functions
Actions
Sin(x)
Cos(x)
Returns the sine of the angle x in radians.
Returns the cosine of the angle x in
radians.
Returns the tangent of the angle x in
radians.
Returns the angle whose sine is y.
Returns the angle whose cosine is y.
Returns the angle whose tangent is y.
Returns the angle whose tangent is x/y.
Returns x raised to y (Xy).
Returns e raised to x (ex).
Returns the natural logarithm of x.
Returns the square root of x.
Returns the smallest whole number greater
than or equal to x.
Returns the largest whole number less than
or equal to x.
Returns the absolute value of a.
Returns the maximum of a and b.
Returns the minimum of a and b.
Tan(x)
asin(y)
Acos(y)
atan(y)
atan2(x,y)
pow(x,y)
Exp(x)
Log(x)
sqrt(x)
Ceil(x)
floor(x)
Abs(a)
max(a,b)
Min(a,b)
Q19.
Ans.
`
What do you mean by Internet? Explain the various services provided by
Internet.
Internet: - A global network 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.
SUBJECT: CORE JAVA
14/54
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 the 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.
Q20.
Ans.
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 that 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
thus refine the search process.
Explain short circuit logical operator in java. Give an example of short circuit
logical operator in java.
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.
SUBJECT: CORE JAVA
Section – B
[QUESTIONS 1 TO 32]
Q1.
Ans.
Q2.
Ans.
Q3.
Ans.
Q4.
Ans.
Q5.
Ans.
Q6.
Ans.
Q7.
Ans.
15/54
2 Marks Questions
[PAGE 14 TO 16]
What is an instance variable?
The data or variables, defined within a class are called instance variables. The code
is contained within methods. The instance variables are acted upon and accessed by
the methods defined for that class. Variables defined within a class are called
instance variables because each instance of the class contains its own copy of these
variables.
What is an object?
An object is a blue print of a class. 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.
What is the difference between Methods and Constructors?
Method and Constructors both defined under the class but there is some difference
between method and constructor
Method
Constructor
Defined with any name
Always having the same name as the
name of the class
Return type can be specified
No return type is specified
Can be declared as abstract
Never declared as abstract
Invoked by the reference of the object of Invoked when ever the memory is
a class
allocated to the object
Compare overloading and overriding methods.
Difference between overloading and overriding is:
Overloading
Overriding
Overloading is done when many Overriding is done when the function has
functions have the same name.
the same name in super and sub classes
Overloading happens with in the same Overriding happens with in super and
class
Sub class
In overloading methods having same In overriding methods having same name
name, can called by same object of the same parameters but can call by the
class but with different parameters
different objects of different class.
Differentiate between Java array and vector.
Difference between Java array and vector is:
Array
Vector
Arrays are static
Vectors are dynamic
No legal method to handle array
Provides different types of legal methods
to handle vector
Not related the collection
Related to the collection object
We can’t return any array value without
Vector’s element value can be returned
Array index
without index value
When do we declare a method or class final?
Methods are declared final when we want to prevent these methods to override.
Classes are declared final so that these are not inherited.
What is a Constructor? What are its special properties?
Constructors are the method defining by the same name as the name of the class.
These are used to initialize an object at the time of object creation. Special property
of a constructor is that it doesn’t have any return type.
SUBJECT: CORE JAVA
Q8.
Ans.
Q9.
16/54
What is a Constructor? What are its special properties?
Constructors are the method defining by the same name as the name of the class.
These are used to initialize an object at the time of object creation. Special property
of a constructor is that it doesn’t have any return type.
What is the difference between multiple inheritance and single inheritance?
Which does java support?
Ans.
Q10.
Ans.
Q11.
Ans.
Q12.
Ans.
Q13.
Ans.
Q14.
Ans.
Q15.
Ans.
Q16.
Ans.
Q17.
Ans.
Q18.
Ans.
Q19.
Ans.
Multiple Inheritance
Single inheritance
In multiple inheritance a sub class can In single inheritance a sub class can
have more than one super class
have only one super class.
Java supports only single inheritance, but it can implement the concept of multiple
inheritance using interfaces. By using interfaces, we can implement many classes in
a single class.
What restrictions are placed on method overloading?
Restrictions
 In methods overloading, overloaded methods must have same name.
 They must different parameters.
 They must define under the same class.
Name all the control statement used in java.
Decision control :If and switch
Loop control :While, do while, for
Label statements :Break, continue
What is the use of return statement?
The return statement is used to explicitly return from a method. It causes program
control to transfer back to the caller of the method. Return statement always return a
single value.
Define the syntax to declare an object.
classname xx=new classname();
E.g. Box xx=new my Box();
What is use of ‘this’ keyword?
This can be used inside any method to refer the current object of the class. This is
always a reference to the object on which the method was invoked. e.g
my(int i,int j,int k)
{ this.i=i, this.j=j, this.k=k; }
What do you mean by Garbage Collection?
Java provides a special feature in classes. The object of class is deallocated
automatically when it is not in use. This process is called garbage collection.
Define static in Java.
Static keyword is used with variables and methods. So that they can be called by the
reference of class name in which they are declared without creating the object of that
class.
What is the use of final keyword?
Final keyword is used with variables to make constant declaration , with classes to
prevent inheritance, and with methods to prevent overriding.
Differentiate String and StringBuffer class.
String and StringBuffer classes both creates String object. String represents fixedlength immutable character sequences. But StringBuffer represents growable and
writeable character sequences. StringBuffer also allow the alteration at the middle of
the string.
Name all the methods provided in the String class to manipulate Strings.
Length(),toString(),charAt(),getChars(),getBytes(),toCharArray(),equals(),startsWith(),
endsWith() ,indexOf(),lastIndexOf(),substring().
SUBJECT: CORE JAVA
Q20.
Ans.
Q21.
Ans.
Q22.
Ans.
Q23.
Ans.
Q24.
Ans.
Q25.
Ans.
Q26.
Ans.
Q27.
Ans.
Q28.
Ans.
Q29.
Ans.
Q30.
Ans.
Q31.
Ans.
17/54
What are Wrappers?
Data types are the not the part of the object hierarchy. Wrappers convert basic data
types to objects. They are passed by the reference. Java provides classes that
corresponds to each of the simple types. These classes encapsulate, or wrap the
simple type within a class and refer as Wrappers.
List all the wrapper classes.
Integer, Byte, Long, Short, Float, Double, Character, Boolean.
Define System Class.
The System class holds a collection of static methods and variables. The standard
input, output and error output of the java run time are stored in the in ,out and err
variables.
Name the super class of the java classes.
Object is the super class of all the java classes.
Define Class.
A class is a way to bind the data and its functions together. It allows the data to be
hidden if necessary from external use. When defining a class, we are making a new
abstract data type.
Name all the methods provided by Math class.
sin(), cos(), tan(), asin(), acos(), atan(), atan2(), exp(), log(), pow(). sqrt(), abs(),
floor(), max(), ceiling(), min(), round(), random(), toRadians(), toDegrees().
What are objects? How are they created?
An object in OOPs is an instance of class. Object is used to access the members of a
class. To create an object of class we use new keyword.
E.G. if ABC is a class and we want to declare an object obj for this class. The
ABC obj = new ABC ();
What do you understand by static?
If you want to define a class member that will be used independently of any object of
that class. To create such a member, precede its declaration with the keyword static.
When a member is declared static, it can be accessed before any objects of its class
are created, and without reference to any object. You can declare both methods and
variables to be static. The most common example of a static member is main (). Main
() is declared as static because it must be called before any object exists.
What are restrictions of static methods?
The can only call others static methods.
They must only access static data
They cannot refer to this or super in any way.
What is difference between interface and class?
Through the use of interface keyword, Java allows you to fully abstract the interface
from its implementation. That is, using interface you can specify what a class must do
but not how it does it. Interfaces are syntactically similar to classes, but they lack
instance variable, and their methods are declared without any body.
What are interfaces in java?
An interface is a class in the form of a collection of methods and constant
declarations. When a class implements an interface, it promises to implement all of
the methods declared in that interface. Interfaces are useful for capturing similarities
among unrelated classes without artificially forcing a class relationship, declaring
methods that one or more classes are expected to implement and revealing an
object's programming interface without revealing its class. Java uses ‘interface’ and
‘abstract Class’ to define interfaces.
What are methods in java?
When you create a class, you will specify the code and data that constitute that class.
Collectively these elements are called members of the class. Specifically, the data
defined by the class are referred to as member variables and the code that operates
on that data is called as a member method or simply method.
SUBJECT: CORE JAVA
Q32.
Ans.
How does String classes differ from StringBuffer class?
A Java string is an instantiated object of the string class. String Buffer is a peer class
of string. While string creates strings of fixed length, string Buffer creates strings of
flexible length that can be modified in terms of both length and content. We can insert
characters and sub-strings in the middle of string, or append another string to the
end. But in string classes, we cant modify the strings after declaring.
Section – B
[QUESTIONS 1 TO 32]
Q1.
Ans.
18/54
5 Marks Questions
[PAGE 17 TO 31]
List eight static methods of character class.
Character is a simple wrapper around a char.
Method
Description
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 Returns true if ch should be ignorned in
(char ch)
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.
Q2.
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("\n");
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(number[i]>number[j])
{
SUBJECT: CORE JAVA
Q3.
Ans.
Q4.
Ans.
19/54
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(" ");
}
}
Write any program in java using switch statement.
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");
} } }
Write a program to find whether the given number is a prime number or not.
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
SUBJECT: CORE JAVA
Q5.
Ans.
Q6.
Ans.
20/54
System.out.println("No is not prime"+i);
} }
Describe the various loop statements available in java.
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 while 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.
The Do Statement
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
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
}
Differentiate between constructors and destructors in java.
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()
SUBJECT: CORE JAVA
21/54
{
//finalization code here
Q7.
Ans.
Q8.
Ans.
}
Discuss the concept of parameters. What are parameters for? What is the
difference between formal parameters and actual parameters?
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
Write an application program to find the largest from the list of n elements.
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;
SUBJECT: CORE JAVA
Q9.
Ans.
Q10.
Ans.
Q11.
Ans.
22/54
System.out.println(i);
for(i=0;i<n;i++)
{
if(a[i]>m)
m=a[i];
}
System.out.println("greatest no is"+m);
}
}
What are string-handling features in java?
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 substring, 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()
Give two different reasons for using named constants (declared with the final
modifier).
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.
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.
class nav
{
public int small(int a,int b,int c)
{
SUBJECT: CORE JAVA
23/54
if(a<b)
{
if(a<c)
return (a);
else
return (c);
}
else
if(b<c)
return (b);
else
return (c);
}
}
Q12.
Ans.
Q13.
Ans.
class navjeet
{
public static void main(String aa[])
{
nav nn=new nav();
System.out.println(nn.small(34,5,7);
}
}
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.
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();
}}
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.
class ch1
{
int countchars(String name,char p)
{ int i=0,c=0;
for(i=0;i<name.length();i++)
SUBJECT: CORE JAVA
Q14.
24/54
{
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);
} }
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;
Q15.
Ans.
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]
}
}
}
Write a note on nested class.
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
SUBJECT: CORE JAVA
25/54
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 nonstatic 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.
Q16.
Ans.
Q17.
Ans.
What is use of super keyword?
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.
Discuss briefly the protected and private protected level of access protection
available level of access protection available in java.
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
SUBJECT: CORE JAVA
Q18.
Ans.
Q19.
Ans.
Q20.
Ans.
26/54
Same class
Yes
Yes
Yes
Yes
Same
No
Yes
Yes
Yes
package
subclass
Same
No
Yes
Yes
Yes
package nonsubclass
Different
No
No
Yes
Yes
package
subclass
Different
No
No
No
Yes
package nonsubclass
Write a Java program to create a Fibonacci series.
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;
}.
}
Write an application program to find the largest element from the given list.
class largest
{
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);
}
}
Write an application/applet to implement the binary search technique.
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])
{
SUBJECT: CORE JAVA
27/54
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;
}
Q21.
Ans.
Q22.
Ans.
if(f==1)
System.out.println(mid);
else
System.out.println("no match found");
}
}
Write an application program to print prime numbers 1 to 100.
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);
}
}
What is an Abstract Class?
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. Nonabstract methods implement the method statements.
SUBJECT: CORE JAVA
Q23.
Ans.
Q24.
28/54
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);
}
Write an application program to find the largest from the list of n elements.
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);
}
}
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[])
{
SUBJECT: CORE JAVA
29/54
ch1 cc=new ch1();
String s;
int i;
i=cc.countchars("navjeet",'e');
System.out.println("the value of i is"+i);
}
}
Q25.
Ans.
Q26.
Ans.
What is a Class?
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){
}
}
What is an Object?
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);
SUBJECT: CORE JAVA
30/54
Book book2 = new Book(“Core Java”,”Sun Press”, 11.20);
Book book3 = new Book(“Thinking in Java”,”Addison Wesley”, 12.20);
Q27.
Ans.
Q28.
Ans.
}
What is Inheritance?
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;
}
What is Polymorphism?
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(){
}
SUBJECT: CORE JAVA
Q29.
Ans.
Q30.
Ans.
31/54
}
Class ScrewDriver extends Tool{
void operateit(){
}
}
What are Constructor Methods?
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);
}
What Is Garbage Collection?
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.
SUBJECT: CORE JAVA
Q31.
Ans.
32/54
Although you can't tell Java to explicitly reclaim the memory of a specific dereferenced 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();
Explain Arrays.
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.
Q32.
Ans.
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"};
Briefly explain how subroutines can be a useful tool in the top-down design of
programs.
The major advantages of using subroutines or functions are as follows:
SUBJECT: CORE JAVA
33/54
1. 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.
2. 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.
3. 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.
4. Reusability of code
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.
SUBJECT: CORE JAVA
Section – C
[QUESTIONS 1 TO 21]
Q1.
Ans.
Q2.
Ans.
Q3.
Ans.
Q4.
Ans.
Q5.
Ans.
Q6.
Ans.
Q7.
Ans.
34/54
2 Marks Questions
[PAGE 32 TO 34]
What is HTML?
HTML is the synonym for Hyper Text Markup Language. HTML is used to create
static web pages. HTML uses tags to create web pages.
What is the relationship between the canvas class and the graphics class?
Canvas class and graphics class both are used for drawing purpose. Canvas
encapsulates a blank window upon which you can draw. This class contains methods
for drawing strings, lines, rectangles and other shapes defined in the graphics class,
which is a part of the java.awt package.
What is an Applet? Should applets have constructors?
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. Applet init() method is called exactly once in its life
cycle i.e. when it is loaded. Start() is called each time the browser visits he page.
Stop() is called when browser leaves the page. Destroy() is called when browser
unloads the applet.
No, Applet does not have constructors.
What is JAVA API?
The Java Application Programming Interface (API) is prewritten code, organized into
packages of similar topics. For instance, the Applet and AWT packages include
classes for creating fonts, menus, and buttons. Having Java API in your environment
is a pre-requisite of writing and compiling java program.
Sun Microsystems’s J2SE comes bundled with the compiler, a runtime environment,
and core API. Before you can develop an application written in the Java
programming language, you will need the Java 2 Platform Standard Edition (J2SE)
development kit. JESE 5.0 is the most current version of J2SE.
What is an Applet?
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. Applet init() method is called exactly once in its life
cycle i.e. when it is loaded. Start() is called each time the browser visits he page.
Stop() is called when browser leaves the page. Destroy() is called when browser
unloads the applet.
What advantages do Java’s layout provides over traditional windowing
system?
Advantages of java layout over windowing system
Java provides different types of layout to arrange and place the component in
windows applet/application.
It helps to manage component in window
It helps to hide or unhide components in window
It helps to use more than one container in same window
It helps to manage different container differently in same window
How does try statement determine which catch clause should be used to
handle an exception?
Try statement checks the type of error is generated by the try block and compare it
with all the provided catch block and determine which catch clause will executes.
SUBJECT: CORE JAVA
Q8.
Ans.
Q9.
Ans.
Q10.
Ans.
Q11.
Ans.
Q12.
Ans.
Q13.
Ans.
Q14.
Ans.
Q15.
Ans.
Q16.
Ans.
Q17.
Ans.
Q18.
Ans.
35/54
What is the use of getDocumentBase() and getCodeBase() methods?
Java provides the facility to applet to load data from the directory holding the HTML
file that started the applet and the directory from which the applet’s class file was
loaded. These directory are returned as URL objects by getDocumentBase() and
getCodeBase() method.
List all the events provided by awt.event package.
ActionEvent, ContainerEvent, FocusEvent, ComponentEvent, InputEvent, ItemEvent,
KeyEvent, MouseEvent, TextEvent, WindowEvent
What is a package?
The packages are containers for classes that are used to keep the class name spice
compartmentalized. Packages are stored in a hierarchical manner and are explicitly
imported into new class definitions. To create a package includes package command
as the first statement in Java source file. The package statement 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.
Why do applet classes needed to be declared as public?
The applet classes are declared as public because they are to be called outside the
package. And any class required outside package must be declared as public.
How do you compile and run applet?
To compile an applet the javac appletname command is used.
To run the applet appletviewer command is used.
Is it necessary to catch all type of exception?
Yes, it is necessary to catch all type of exception to get accurate result from the
program. Although there is an exception that we can’t handle is StackOverflow
exception in our program.
Identify correctly constructed package declarations, import statements, and
method declarations.
package packagename; is correct package declaration
import packagename.*; or import packagename.Classname ; is the correct import
statement.
public /private methodname([argumentlist]) is correct declaration for methods.
Explain the five rules for using across attributes.
1. Public data is defined by public keyword so that it can be used by any package.
2. To defined private data private keyword is used so that data can not be used
outside the class.
3. Default Access specification need not to be defined with any data type.
4. To define protected members so that these members of the class can be extended
by the subclasses of same and different packages.
What are exceptions in java?
Exceptions in java are used to handle errors. All the exceptions in java extends
Exception Class.
How an Image can be loaded on the Applet window?
To load the Image on the Applet window the getImage method is defined by the
applet class. It has the following forms.
Image getImage(URL url);
Image getImage(URL url, String imageName)
Differentiate between Component and Container.
Component is an abstract class that encapsulates all of the attributes of a visual
component- All user interface elements that are displayed on the screen and that
interact with user.
Container classes provide container to the components where we can place different
Components. All the Containers like window, panel, Frame, all are the sub classes of
container class.
SUBJECT: CORE JAVA
Q19.
Ans.
Q20
Ans.
Q21.
Ans.
What do you mean by panel class?
The panel class is a concrete subclass of container. It doesn’t add any new methods.
It simply implements container. Panel is the subclass of applet. When screen output
is directed to an applet, it is drawn on the surface of a panel object. Panel is a
window that does not contain a title bar, menu bar, or border.
What do you mean by repaint method?
The repaint method is defined by the AWT. It causes the AWT runtime system to
execute a call to your applet’s update() method. Which is, in default implementation,
calls paint().
What do you mean by applet viewer?
An applet viewer executes your applet in a window. This is generally the fastest
and easiest way to test your applet. Using an applet viewer, such as the standard
JDK tool, appletviewer.
Section – C
[QUESTIONS 1 TO 24]
Q1.
Ans.
Q2.
Ans.
36/54
5 Marks Questions
[PAGE 34 TO 43]
Why is java known as an Internet Language? Discuss.
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 Applets And Applications
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
Write an applet that accepts two texts and concatenates them.
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");
SUBJECT: CORE JAVA
Q3.
Ans.
Q4.
Ans.
37/54
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);
} }
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.
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”)’
}
}
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.
import java.awt. *;
import java. Awt.event. *;
import java. Applet. *;
public class largest extends Applet
Implements Actionlistener {
TextField first, second, third;
public void init ()
{
SUBJECT: CORE JAVA
Q5.
Ans.
Q6.
Ans.
38/54
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>
Write a note on API.
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.
Write a Program to draw lines.
import java.awt. *;
import java. Applet. *;
/*
SUBJECT: CORE JAVA
39/54
<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);
}}
Q7.
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);
}
Q8.
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);
}
}
Q9.
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 2. every application program need to
execute
define main() function in the program
3. no command line argument is We can pass commandline arguments
passed
in an application
4. a fast and small program Program those does not support web
executed on the internet
browsers
SUBJECT: CORE JAVA
Q10.
Ans.
Q11.
Ans.
40/54
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>
Write an applet that takes an integer and reverse that e.g. 756 to 657.
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);
}
}
Write an applet that takes the input and compute the factorial.
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;
SUBJECT: CORE JAVA
Q12.
Ans.
Q13.
Ans.
41/54
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);
}
}
Describe a package and its relationship with classes. What is the
recommended naming convention for creating your own package?
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;
What is Exception? Also define the types of Exception.
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.
SUBJECT: CORE JAVA
Q14.
Ans.
Q15.
Ans.
Q16.
Ans.
42/54
Define all the tools used to Handle Exception.
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.
Define life cycle of an applet.
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 ().
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?
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.
SUBJECT: CORE JAVA
Q17.
Ans.
Q18.
Ans.
43/54
Features
1. Structured exception handling.
2. Provide security from executing illegal instruction those prone to termination of
the program.
3. Use the concept of object oriented approach to handle exceptions.
4. User defined exception can also be handled.
Following are the major statements to handle exceptions
1. Try: - Program statements that you want to monitor for exceptions are contained
within a try block.
2. Catch: - If any exception occurs within the try block, it is thrown. These
exceptions are caught in catch block.
3. Finally: - Finally is the last block that will always execute although exception is
raised on not.
4. Throw: - Use to throw exception manually.
5. Throws: - To explicitly throws the exception.
Explain the methods used to create lines, circles, rectangles and ellipses.
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)
What do you mean by Layout Manager? What are the various types of Layout?
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.
SUBJECT: CORE JAVA
Q19.
Ans.
Q20.
Ans.
Q21.
Ans.
Q22.
Ans.
44/54
What do you mean by AWT? What components and containers are used by
AWT?
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
Write a program to draw parrellogram.
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);
}
}
What advantages do java’s Layout Managers provides over traditional
windowing system?
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.
Write a short note on VPN.
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.
SUBJECT: CORE JAVA
Q23.
Ans.
Q24.
Ans.
45/54
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:
1. Allows mobile professionals and telecommuter’s access their corporate network
over the Internet
2. it costs less than traditional remote access solutions3
3. Makes use of the telephone networks massive switching system
4. Accessing LAN is secure because the connection is encrypted.
Protocol used in VPN:
1. Pont to Point Tunneling Protocol
2. Layer 2 Tunneling Protocol
What is a stream class? How are the stream classes classified?
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 unidirectional; 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
What do you mean by system package?
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.
SUBJECT: CORE JAVA
46/54
OTHER IMPORTANT SHORT QUESTIONS
[QUESTIONS 1 TO 12]
Q1.
Ans.
Q2.
Ans.
Q3.
Ans.
Q4.
Ans.
Q5.
Ans.
Q6.
Ans.
Q7.
Ans.
Q8.
Ans.
Q9.
Ans.
[2 Marks]
[PAGE 44 TO 45]
What is a socket?
A socket can be used to connect java’s I/O system to other programs that may reside
either on the local machine or on any other machine on the Internet. TCP/IP sockets
are used to implement reliable, bi-directional, persistent, point-to-point, stream-based
connections between hosts on the Internet.
Name any four events.
Mouse Event
Keyboard Event
Component event
Focus event
Component Event
What is multithreading?
A thread is a line of execution. It is the smallest unit of code that is dispatched by the
scheduler. Thus a process can contain multiple threads to execute its different
sections. This is called multithreading.
When a program requires user input, multithreading enables creation of a separate
thread for this task alone.
When will you use buffered I/O streams?
Java programs perform I/O through streams. A stream is an abstraction that either
produces or consumes information. A stream is linked to a physical device by the
java I/O system. All streams behave in the same manner, even if the actual physical
devices to which they are linked differ. The same I/O classes and methods can be
applied to any type of device. An input stream can abstract many different kinds of
input: from a disk file, a keyboard, or a network socket. An output stream may refer to
the console, a disk file or a network connection.
What is RMI?
RMI allows a java object on one machine to invoke a method of a java object on a
different machine. An object may be supplied as an argument to that remote method.
The sending machine serializes the object and transmits it. The receiving machine
deserialization.
What is the purpose of HTTP tunneling?
Purpose of HTTP tunneling is to expose the attributes defined under the URL so that
the remote objects are recognized on the remote machines.
What are adapter classes?
Java provides a special feature called an adapter class that can simplify the creation
of event handlers. Adapter classes are useful when you want to receive only some of
the events that are handled by a particular event listener.
Differentiate between Component and Container.
Component is an abstract class that encapsulates all of the attributes of a visual
component. All user interface elements that are displayed on the screen and that
interact with user.
Container classes provides the container to the component where we can place
different Components all the Containers like
Window
Panel
Frame
All are the sub class of container class.
Define Canvas.
Canvas encapsulates a blank window upon which you can draw. Normally we
extends the Canvas class to design the applet for a bean component.
SUBJECT: CORE JAVA
Q10.
Ans.
Q11.
Ans.
Q12.
Ans.
47/54
Define Reflection?
Reflection is the ability of software to analyze itself. This is provided by the
java.lang.reflect package and elements in Class. Reflection is an important capability,
needed when using components called java Beans.
What is Secure Socket Layer (SSL)?
Secure Socket Layer is the layer which implements reliable, I-directional, persistent,
point-to-point, stream-based connections between hosts. Data transfer in
encapsulated form is called secure socket layer. TCP/IP is one of the protocols that
use secure socket layer.
How can I provide a directory listing, and allow the user to navigate directories
and select a file?
A directory is a file that contains a list of other files and directories. When you create
a file object and it is a directory, the isDirectory() method will return true. In this case,
you can call list() on that object to extract the list of other files and directories inside.
OTHER IMPORTANT LONG QUESTIONS
[QUESTIONS 1 TO 15]
Q1.
Ans.
Q2.
Ans.
[5 Marks]
[PAGE 45 TO 52]
What is a Servlet?
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.
What is JDBC?
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.
SUBJECT: CORE JAVA
Q3.
Ans.
Q4.
Ans.
Q5.
Ans.
48/54
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.
What is Swing?
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.
What is JAVABEANS?
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.
How does JSP differ from Servlets?
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
SUBJECT: CORE JAVA
Q6.
Ans.
Q7.
Ans.
49/54
<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>
What is Multithreading?
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();
}
}
What is Event Handling?
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.
SUBJECT: CORE JAVA
Q8.
Ans.
50/54
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 wouldbe "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.
Discuss RMI architecture.
RMI architecture consists of four layers: the application, stubs/skeletons, remote
references and the transport layer.
The following diagram shows the RMI layers:
Client Application
Server Application
Server Skeleton
Client Stub
Remote
Reference
Layer
Remote
Reference
Layer
Transport Layer
SUBJECT: CORE JAVA
Q9.
Ans.
Q10.
Ans.
Q11.
Ans.
51/54
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.
How I/O is accomplished using input stream outputstream, Reader and Writer
classes?
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.
How does multi threading improves the performance of java?
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.
How does multi threading improves the performance of Java? Why are they
used?
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.
SUBJECT: CORE JAVA
Q12.
Ans.
52/54
Differentiate between dynamic binding and message passing.
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.
Object
1
Object
Object
2
Object
3
Q13.
Ans.
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.
What is dynamic method dispatch? Explain with example.
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.
SUBJECT: CORE JAVA
53/54
Example: Dynamic method Dispatch
Q14.
Ans.
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
}
}
Write a short note of Collection Framework.
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.
SUBJECT: CORE JAVA
Q15.
Ans.
54/54
Java provides many I/O classes. Can you provide a summary to make things
easier?
The I/O classes defined by the java.io package are:
1. BufferedInputStream
2. BufferedOutputStream
3. BufferedReader
4. BufferedWriter
5. 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.
Download