SPPU TYBCA Syllabus
how to set class path?
old question paper
Slips java slip solution
Java
AWT Adapters are abstract classes from java.awt.event package introduced
with JDK 1.1. Adapter classes make event handling simple and easy. Adapters
usage replaces the listeners; adapters make event
handling easy to the programmer. Every listener that includes more than
one abstract method has got a corresponding adapter class.The advantage of
adapter is that we can override any one or two methods we like instead of all.
But incase of a listener, we must override all the abstract methods. For example,
to close the window, all the 7 abstract methods of WindowListener should be
overridden atleast with empty bodies. But is not the case with WindowAdapter. With WindowAdapter
only one method windowClosing() is enough to
override. Adapters can be used in inner classes also and is illustrated in
"Java Frame Closing – Anonymous inner class".how to set class path?
old question paper
Slips java slip solution
Unitwise Important Questions with Answer
Unit I
Q 1. Explain any three OOPS
(Polymorphism/Inheritance/Abstraction/Encapsulation) Concept.
Ans: Brief Introduction to OOP
Object Oriented Programming or
OOP is the technique to create programs based on the real world. Unlike
procedural programming, here in the OOP programming model programs are
organized around objects and data rather than actions and logic. Objects
represent some concepts or things and like any other objects in the real
Objects in programming language have certain behavior, properties, type, and
identity. In OOP based language the principal aim is to find out the objects to
manipulate and their relation between each other. OOP offers greater
flexibility and compatibility and is popular in developing larger application.
Another important work in OOP is to classify objects into different types
according to their properties and behavior. So OOP based software application
development includes the analysis of the problem, preparing a solution, coding
and finally its maintenance.
Java is a object oriented programming and
to understand the functionality of OOP in Java, we first need to understand
several fundamentals related to objects. These include class, method,
inheritance, encapsulation, abstraction, polymorphism etc.
Class - It is the
central point of OOP and that contains data and codes with behavior. In Java
everything happens within class and it describes a set of objects with common
behavior. The class definition describes all the properties, behavior, and
identity of objects present within that class. As far as types of classes are
concerned, there are predefined classes in languages like C++ and Pascal. But
in Java one can define his/her own types with data and code.
For example int a;
Here int is a type and a,b,c,d,e,f are the variable
of type int.in other word int is a class and a,b,c,d,e,f are the objects of
class int.
Object -
Objects are the basic unit of object orientation with behavior, identity. As we
mentioned above, these are part of a class but are not the same. An object is
expressed by the variable and methods within the objects. Again these variables
and methods are distinguished from each other as instant variables, instant
methods and class variable and class methods.
Methods -
We know that a class can define both attributes and behaviors. Again attributes
are defined by variables and behaviors are represented by methods. In other
words, methods define the abilities of an object.
Inheritance - This is the mechanism of organizing and structuring
software program. Though objects are distinguished from each other by some
additional features but there are objects that share certain things common. In
object oriented programming classes can inherit some common behavior and state
from others. Inheritance in OOP allows to define a general class and later to
organize some other classes simply adding some details with the old class definition.
This saves work as the special class inherits all the properties of the old
general class and as a programmer you only require the new features. This helps
in a better data analysis, accurate coding and reduces development time.
Abstraction - The process of abstraction in Java is used to hide
certain details and only show the essential features of the object. In other
words, it deals with the outside view of an object (interface).
Encapsulation - This is an important programming concept that assists
in separating an object's state from its behavior. This helps in hiding an
object's data describing its state from any further modification by external
component. In Java there are four different terms used for hiding data
constructs and these are public, private, protected and package. As we know an
object can associated with data with predefined classes and in any application
an object can know about the data it needs to know about. So any unnecessary
data are not required by an object can be hidden by this process. It can also
be termed as information hiding that prohibits outsiders in seeing the inside
of an object in which abstraction is implemented.
Polymorphism - It describes the ability of the object in belonging to
different types with specific behavior of each type. So by using this, one
object can be treated like another and in this way it can create and define
multiple level of interface. Here the programmers need not have to know the
exact type of object in advance and this is being implemented at runtime.
Q 2. Explain any 5 methods of “java.lang.String”
class.
Ans:
String Methods
Here is the list of methods supported by String class −
Sr.No.
|
Method &
Description
|
1
|
Returns the character at the specified index.
|
2
|
Compares this String to another Object.
|
3
|
Compares two strings lexicographically.
|
4
|
Compares two strings lexicographically, ignoring case
differences.
|
5
|
Concatenates the specified string to the end of this string.
|
6
|
Returns true if and only if this String represents the same
sequence of characters as the specified StringBuffer.
|
7
|
Returns a String that represents the character sequence in the
array specified.
|
8
|
Returns a String that represents the character sequence in the
array specified.
|
9
|
Tests if this string ends with the specified suffix.
|
10
|
Compares this string to the specified object.
|
11
|
Compares this String to another String, ignoring case
considerations.
|
12
|
Encodes this String into a sequence of bytes using the
platform's default charset, storing the result into a new byte array.
|
13
|
Encodes this String into a sequence of bytes using the named
charset, storing the result into a new byte array.
|
14
|
Copies characters from this string into the destination
character array.
|
15
|
Returns a hash code for this string.
|
16
|
Returns the index within this string of the first occurrence of
the specified character.
|
17
|
Returns the index within this string of the first occurrence of
the specified character, starting the search at the specified index.
|
18
|
Returns the index within this string of the first occurrence of
the specified substring.
|
19
|
Returns the index within this string of the first occurrence of
the specified substring, starting at the specified index.
|
20
|
Returns a canonical representation for the string object.
|
21
|
Returns the index within this string of the last occurrence of
the specified character.
|
22
|
Returns the index within this string of the last occurrence of
the specified character, searching backward starting at the specified index.
|
23
|
Returns the index within this string of the rightmost occurrence
of the specified substring.
|
24
|
Returns the index within this string of the last occurrence of
the specified substring, searching backward starting at the specified index.
|
25
|
Returns the length of this string.
|
26
|
Tells whether or not this string matches the given regular
expression.
|
27
|
Tests if two string regions are equal.
|
28
|
Tests if two string regions are equal.
|
29
|
Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.
|
30
|
Replaces each substring of this string that matches the given
regular expression with the given replacement.
|
31
|
Replaces the first substring of this string that matches the
given regular expression with the given replacement.
|
32
|
Splits this string around matches of the given regular
expression.
|
33
|
Splits this string around matches of the given regular
expression.
|
34
|
Tests if this string starts with the specified prefix.
|
35
|
Tests if this string starts with the specified prefix beginning
a specified index.
|
36
|
Returns a new character sequence that is a subsequence of this
sequence.
|
37
|
Returns a new string that is a substring of this string.
|
38
|
Returns a new string that is a substring of this string.
|
39
|
Converts this string to a new character array.
|
40
|
Converts all of the characters in this String to lower case
using the rules of the default locale.
|
41
|
Converts all of the characters in this String to lower case
using the rules of the given Locale.
|
42
|
This object (which is already a string!) is itself returned.
|
43
|
Converts all of the characters in this String to upper case
using the rules of the default locale.
|
44
|
Converts all of the characters in this String to upper case
using the rules of the given Locale.
|
45
|
Returns a copy of the string, with leading and trailing
whitespace omitted.
|
46
|
Returns the string representation of the passed data type
argument.
|
Q 3. Explain any 10 features of JAVA.
Ans:
These days Java programming language is being
used for programming web applications. It is also widely used for mobile
and electronic items.
Looks familiar to existing programmers: related
to C and C++:
Omits many rarely used, poorly understood,
confusing features of C++, like operator overloading, multiple inheritance,
automatic coercions, etc.
Contains no goto statement,
but break and continue
Has no header files and eliminated C
preprocessor
Eliminates much redundancy (e.g. no
structs, unions, or functions)
has no pointers
Added features to simplify:
Garbage collection, so the programmer won't have
to worry about storage management, which leads to fewer bugs.
A rich predefined class library
Java is an object-oriented
language, which means that you focus on the data in
your application and methods that manipulate that data, rather than
thinking strictly in terms of procedures.
In an object-oriented system, a class is
a collection of data and methods that operate on that data. Taken together, the
data and methods describe the state and behavior of an object.
Classes are arranged in a hierarchy, so that a subclass can inherit behavior
from its superclass.
Java comes with an extensive set of classes,
arranged in packages, that you can use in your programs.
It has a spring-like transparent RPC
system
Now uses mostly tcp-ip based protocols
like ftp & http
Java supports various levels of network
connectivity through classes in the java.net package (e.g. the URL class allows
a Java application to open and access remote objects on the internet).
The Java compiler
generates byte-codes, rather than native machine code. To actually
run a Java program, you use the Java interpreter to execute the compiled
byte-codes. Java byte-codes provide an architecture-neutral object file format.
The code is designed to transport programs efficiently to multiple platforms.
rapid turn-around development
Software author is protected, since binary byte
streams are downloaded and not the source code
Java has been designed for
writing highly reliable or robust software:
language restrictions (e.g. no pointer
arithmetic and real arrays) to make it impossible for applications to smash
memory (e.g overwriting memory and corrupting data)
Java does automatic garbage
collection, which prevents memory leaks
extensive compile-time checking so bugs
can be found early; this is repeated at runtime for flexibilty and to check
consistency
Security is an important
concern, since Java is meant to be used in networked environments. Without some
assurance of security, you certainly wouldn't want to download an applet from a
random site on the net and let it run on your computer. Java's memory
allocation model is one of its main defenses against malicious code (e.g can't
cast integers to pointers, so can't forge access). Furthermore:
access restrictions are enforced (public, private)
byte codes are verified, which copes with
the threat of a hostile compiler
compiler generates bytecodes, which have
nothing to do with a particular computer architecture
easy to interpret on any machine
Java goes further than just
being architecture-neutral:
no "implementation dependent"
notes in the spec (arithmetic and evaluation order)
standard libraries hide system differences
the Java environment itself is also
portable: the portability boundary is POSIX compliant
Java is an interpreted
language, so it will never be as fast as a compiled language as C or C++. In fact,
it is about 20 times as slow as C. However, this speed is more than enough to
run interactive, GUI and network-based applications, where the application is
often idle, waiting for the user to do something, or waiting for data from the
network.
Java allows multiple concurrent
threads of execution to be active at once. This means that you could be
listening to an audio clip while scrolling the page and in the background
downloading an image. Java contains sophisticated synchronization primitives
(monitors and condition variables), that are integrated into the language to
make them easy to use and robust. The java.lang package provides a Thread class
that supports methods to start, run, and stop a thread, and check on its
status.
Java was designed to adapt to
an evolving environment:
Even after binaries have been released,
they can adapt to a changing environment
Java loads in classes as they are needed, even
from across the network
It defers many decisions (like object layout) to
runtime, which solves many of the version problems that C++ has
Dynamic linking is the only kind there is
Q 4. Explain any 10 difference between JAVA and
C++.
Ans :Following are the difference between C++
and Java:
Although both are and was derived from but still
there is big difference between these two languages.
- Java does not support
operator overloading
- A class definition in Java has no closing
semicolon.
- In Java, Forward reference
declarations are not required.
- Scope resolution operator is
not required in Java.
- In C++ static data members
must be re-declared outside the class
- In C++ programming can be
done without making objects.
- Java has both compiler
and Interpreter for analyzing and execution of program.
- Java is platform
Independent whereas C++ is platform dependent.
- In C++ automatic garbage
collection mechanism is absent while java has it.
- C++ is less dynamic and more
optimizable than Java.
- C++ allows more control over
compile-time optimization, whereas Java depends on the
specific runtime optimization
- C++ uses pointers while java
doesn't have pointers
- Java compiles to byte
code whereas C++ compiles to machine language
- Java has built-in
Internet support while C++ does not have it.
- C++ works on Write
Once, Compile Anywhere while Java works on Write Once, Run Anywhere /
Write Once, Run Everywhere.
- C++ has multiple binary
compatibility standards while Java has a binary compatibility standard
- Java uses a package
system for splitting up code in multiple source files while C++ uses a header file
source code
Q 5. Explain different control structure in
JAVA.
Ans: Different
types of control statements: the decision making statements (if-then,
if-then-else and switch), looping statements (while, do-while and for) and
branching statements (break, continue and return).
Control Statements
The control statement are used to controll the
flow of execution of the program . This execution order depends on the supplied
data values and the conditional logic. Java contains the following types of
control statements:
1- Selection Statements
2- Repetition Statements
3- Branching Statements
Selection statements:
- If Statement:This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skips if block and rest code of program is executed .Syntax:if(conditional_expression){<statements>;...;...;}Example: If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates to 0 so if block is executed. Hence "This is even number" is printed on the screen.
int n = 10;
if(n%2
= = 0){
System.out.println("This is even number");
}
|
- If-else Statement:The "if-else" statement is an extension of if statement that provides another option when 'if' statement evaluates to "false" i.e. else block is executed if "if" statement is false.Syntax:if(conditional_expression){<statements>;...;...;}else{<statements>;....;....;}Example: If n%2 doesn't evaluate to 0 then else block is executed. Here n%2 evaluates to 1 that is not equal to 0 so else block is executed. So "This is not even number" is printed on the screen.
int n = 11;
if(n%2
= = 0){
System.out.println("This is even number");
}
else{
System.out.println("This is not even number");
}
|
- Switch Statement:This is an easier implementation to the if-else statements. The keyword "switch" is followed by an expression that should evaluates to byte, short, char or int primitive data types ,only. In a switch block there can be one or more labeled cases. The expression that creates labels for the case must be unique. The switch expression is matched with each case label. Only the matched case is executed ,if no case matches then the default statement (if present) is executed.Syntax:switch(control_expression){case expression 1:<statement>;case expression 2:<statement>;......case expression n:<statement>;default:<statement>;}//end switchExample: Here expression "day" in switch statement evaluates to 5 which matches with a case labeled "5" so code in case 5 is executed that results to output "Friday" on the screen.
int day = 5;
switch
(day) {
case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thrusday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default: System.out.println("Invalid entry"); break; } |
Repetition Statements:
- while loop statements:This is a looping or repeating statement. It executes a block of code or statements till the given condition is true. The expression must be evaluated to a boolean value. It continues testing the condition and executes the block of code. When the expression results to false control comes out of loop.Syntax:while(expression){<statement>;...;...;}Example: Here expression i<=10 is the condition which is checked before entering into the loop statements. When i is greater than value 10 control comes out of loop and next statement is executed. So here i contains value "1" which is less than number "10" so control goes inside of the loop and prints current value of i and increments value of i. Now again control comes back to the loop and condition is checked. This procedure continues until i becomes greater than value "10". So this loop prints values 1 to 10 on the screen.
int i = 1;
//print
1 to 10
while
(i <= 10){
System.out.println("Num " + i);
i++;
}
|
- do-while loop statements:This is another looping statement that tests the given condition past so you can say that the do-while looping statement is a past-test loop statement. First the do block statements are executed then the condition given in while statement is checked. So in this case, even the condition is false in the first attempt, do block of code is executed at least once.Syntax:do{<statement>;...;...;}while (expression);Example: Here first do block of code is executed and current value "1" is printed then the condition i<=10 is checked. Here "1" is less than number "10" so the control comes back to do block. This process continues till value of i becomes greater than 10.
int i = 1;
do{
System.out.println("Num: " + i);
i++;
}while(i
<= 10);
|
- for loop statements:This is also a loop statement that provides a compact way to iterate over a range of values. From a user point of view, this is reliable because it executes the statements within this block repeatedly till the specified conditions is true .Syntax:for (initialization; condition; increment or decrement){<statement>;...;...;}initialization: The loop is started with the value specified.condition: It evaluates to either 'true' or 'false'. If it is false then the loop is terminated.increment or decrement: After each iteration, value increments or decrements.Example: Here num is initialized to value "1", condition is checked whether num<=10. If it is so then control goes into the loop and current value of num is printed. Now num is incremented and checked again whether num<=10.If it is so then again it enters into the loop. This process continues till num>10. It prints values 1 to10 on the screen.
for (int num = 1; num <= 10; num++){
System.out.println("Num: " + num);
}
|
Branching Statements:
- Break statements:The break statement is a branching statement that contains two forms: labeled and unlabeled. The break statement is used for breaking the execution of a loop (while, do-while and for) . It also terminates the switch statements.Syntax:break; // breaks the innermost loop or switch statement.break label; // breaks the outermost loop in a series of nested loops.
- Continue statements:This is a branching statement that are used in the looping statements (while, do-while and for) to skip the current iteration of the loop and resume the next iteration .Syntax: continue;
- Return statements:It is a special branching statement that transfers the control to the caller of the method. This statement is used to return a value to the caller method and terminates execution of method. This has two forms: one that returns a value and the other that can not return. the returned value type must match the return type of method.Syntax:return;return values;return; //This returns nothing. So this can be used when method is declared with void return type.return expression; //It returns the value evaluated from the expression.Example: Here Welcome() function is called within println() function which returns a String value "Welcome to roseIndia.net". This is printed to the screen.
Unit II
Q 1. How to implement multiple inheritances in
java? Explain with the help of suitable example.
Ans : Inheritance
To know the concept of inheritance clearly you
must have the idea of class and its features like methods, data members, access
controls, constructors, keywords this, super etc.
As the name suggests, inheritance means to take
something that is already made. It is one of the most important feature of
Object Oriented Programming. It is the concept that is used for reusability
purpose. Inheritance is the mechanism through which we can derived classes from
other classes. The derived class is called as child class or the subclass
or we can say the extended class and the class from which we are deriving
the subclass is called the base class or the parent class. To derive a class in
java the keyword extends is used. To clearly understand the concept
of inheritance you must go through the following example.
The concept of inheritance is used to make the
things from general to more specific e.g. When we hear the word vehicle then we
got an image in our mind that it moves from one place to another place it is
used for traveling or carrying goods but the word vehicle does not specify
whether it is two or three or four wheeler because it is a general word. But
the word car makes a more specific image in mind than vehicle, that the car has
four wheels . It concludes from the example that car is a specific word and
vehicle is the general word. If we think technically to this example
then vehicle is the super class (or base class or parent class) and car is the
subclass or child class because every car has the features of it's parent (in
this case vehicle) class.
The following kinds of inheritance are there in
java.
- Simple
Inheritance
- Multilevel Inheritance
Simple Inheritance
When a subclass is derived simply from
it's parent class then this mechanism is known as simple inheritance. In case
of simple inheritance there is only a sub class and it's parent class. It is
also called single inheritance or one level
inheritance.
eg.
class A {
int x; int y; int get(int p, int q){ x=p; y=q; return(0); } void Show(){ System.out.println(x); } } class B extends A{ public static void main(String args[]){ A a = new A(); a.get(5,6); a.Show(); } void display(){ System.out.println("B"); } } |
Multilevel Inheritance
It is the enhancement of the concept of
inheritance. When a subclass is derived from a derived class then this
mechanism is known as the multilevel inheritance. The derived class is called
the subclass or child class for it's parent class and this parent class works
as the child class for it's just above ( parent ) class. Multilevel
inheritance can go up to any number of level.
e.g.
class A {
int x; int y; int get(int p, int q){ x=p; y=q; return(0); } void Show(){ System.out.println(x); } } class B extends A{ void Showb(){ System.out.println("B"); } } class C extends B{ void display(){ System.out.println("C"); } public static void main(String args[]){ A a = new A(); a.get(5,6); a.Show(); } } |
Java does not support multiple Inheritance
Multiple Inheritance
The mechanism of inheriting the features of more
than one base class into a single class is known as multiple inheritance. Java
does not support multiple inheritance but the multiple inheritance can be
achieved by using the interface.
In Java Multiple Inheritance can be achieved
through use of Interfaces by implementing more than one interfaces in a class.
super keyword
The super is java keyword. As the name suggest
super is used to access the members of the super class.It is used for two
purposes in java.
The first use of keyword
super is to access the hidden data variables of the super class hidden by the
sub class.
e.g. Suppose class A is the super class that has
two instance variables as int a and float b. class B is the subclass that
also contains its own data members named a and b. then we can access the super
class (class A) variables a and b inside the subclass class B just by calling
the following command.
super.member;
Here member can either be an instance
variable or a method. This form of super most useful to handle situations
where the local members of a subclass hides the members of a super class having
the same name. The following example clarify all the confusions.
class A{
int a; float b; void Show(){ System.out.println("b in super class: " + b); } } class B extends A{ int a; float b; B( int p, float q){ a = p; super.b = q; } void Show(){ super.Show(); System.out.println("b in super class: " + super.b); System.out.println("a in sub class: " + a); } public static void main(String[] args){ B subobj = new B(1, 5); subobj.Show(); } } |
Output:
C:\>java B
b in super class: 5.0 b in super class: 5.0 a in sub class: 1 |
Use of super to call super class
constructor: The second use of the
keyword super in java is to call super class constructor in the subclass. This
functionality can be achieved just by using the following command.
super(param-list);
Here parameter list is the list of the parameter
requires by the constructor in the super class. super must be the first
statement executed inside a super class constructor. If we want to call the
default constructor then we pass the empty parameter list. The following
program illustrates the use of the super keyword to call a super class
constructor.
class A{
int a; int b; int c; A(int p, int q, int r){ a=p; b=q; c=r; } } class B extends A{ int d; B(int l, int m, int n, int o){ super(l,m,n); d=o; } void Show(){ System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); } public static void main(String args[]){ B b = new B(4,3,8,7); b.Show(); } } |
Output:
C:\>java B
a = 4 b = 3 c = 8 d = 7 |
Q 2. What is the difference between interface
and abstract class in java?
Ans: Interface Vs Abstract Class
There are three main
differences between an interface and an abstract class:
- At the same time multiple
interfaces can be implemented, but only extend one class
- an abstract class may have some
method implementation (non-abstract methods, constructors, instance
initializers and instance variables) and non-public members
- abstract classes may or may not
be a little bit faster
Main reason for the existence of interfaces in
Java is: to support multiple inheritance. Languages supporting multiple
implementation inheritance, an interface is equivalent to a fully abstract
class (a class with only public abstract members).
The above differentiation suggests when to use
an abstract class and when to use an interface:
- If you want to provide common
implementation to subclasses then an abstract class is used,
- If you want to declare
non-public members, the use abstract method
- In case of abstract class, you
are free to add new public methods in the future,
- If you're confirm regarding the
stablity of the API for the long run then use an interface
- If you want to provide the
implementing classes the opportunity to inherit from other sources at the
same time then use an interface.
In general, prefer interfaces if you don't need
to use an abstract class, because they provide more design flexibility.
Q 3. What do you mean by Polymorphism? Write a
java program to explain Overriding.
Answer : Polymorphism means the
ability to take more than one form. Polymorphism means 'any forms.' In OOP, it
refers to the capability of objects to react differently for the same method.
In OOP methodoverloading refers to the
capability of objects to react differently for the same method. Polymorphism
can be implemented in Java language in form of multiple methods having the same
method name. Java code uses a late-binding for supporting polymorphism, the
method which is invoked is decided at runtime.
1. Method Overloading
2. Method Overriding
1. Method Overloading :-
Overloaded methods are methods have the same
name, but different argument lists.
Overloaded methods have the same names but
different argument lists. The arguments may differ in type or number, or both.
However, the return types of overloaded methods can be the same or different.
class methodOverloading{
int add( int a,int b){
return(a+b);
}
float sub(float a,float b){
return(a-b);
}
double add( int a, double b,double c){
return(a+b+c);
}
int mul(int i, int j){
return(i*j);
}
}
public class mainClass extends
methodOverloading{
public static void main(String arr[]){
System.out.println("This progrsm display
the add massage.");
mainClass temp = new mainClass();
System.out.println("Addition value is:
" +temp.add(10,20));
System.out.println("Subtraction value is:
"+temp.sub(1.5f,2.3f));
System.out.println("Addion of double value
is: "+temp.add(10,20.4,25.6));
System.out.println("Multiple value is:
"+ temp.mul(10,10));
}
}
Method Overriding
Method overriding in java means
a subclass method overriding a super class method. Superclass method should be
non-static. Subclass uses extends keyword to extend the super class. In the
example class B is is the sub class and class A is the super class. In
overriding methods of both subclass and superclass possess same signatures.
Overriding is used in modifying the methods of the super class. In
overriding return types and constructor parameters of methods should
match .
Here is the code:
class A {
int i; A(int a, int b) { i = a+b; } void add() { System.out.println("Sum of a and b is: " + i); } } class B extends A { int j; B(int a, int b, int c) { super(a, b); j = a+b+c; } void add() { super.add(); System.out.println("Sum of a, b and c is: " + j); } } class MethodOverriding { public static void main(String args[]) { B b = new B(10, 20, 30); b.add(); } } |
Q 4. Write short notes on following.
a.) Wrapper class
Ans: Wrapper classes and all the methods that
manipulate data and allows to operate a certain work.
Wrapper class is a
wrapper around a primitive data type. It represents primitive data types
in their corresponding class instances e.g. a boolean data type can be
represented as a Boolean class instance. All of the primitive wrapper
classes in Java are immutable i.e. once assigned a value to a wrapper
class instance cannot be changed further.
Wrapper Classes
are used broadly with Collection classes in the java.util package
and with the classes in the java.lang.reflect reflection
package.
Following table lists the primitive types and the corresponding wrapper
classes:
Primitive
|
Wrapper
|
boolean
|
java.lang.Boolean
|
byte
|
java.lang.Byte
|
char
|
java.lang.Character
|
double
|
java.lang.Double
|
float
|
java.lang.Float
|
int
|
java.lang.Integer
|
long
|
java.lang.Long
|
short
|
java.lang.Short
|
void
|
java.lang.Void
|
In Java 5.0 version, additional wrapper classes
were introduced in the java.util.concurrent.atomic package.
They provide atomic operations for assignment, addition and increment. These
classes act like variables and cannot be used as a substitute for the
regular wrapper classes. Few of these new wrapper classes like AtomicInteger
and AtomicLong are the subclasses of the Number Classes.
Primitive
|
Wrapper
|
boolean
|
AtomicBoolean
|
int
|
AtomicInteger
|
long
|
AtomicLong
|
V
|
AtomicReference<V>
|
Features of the Wrapper Classes
Some of the sound features maintained by the
Wrapper Classes are as under :
- All the methods of the wrapper
classes are static.
- The Wrapper class does not
contain constructors.
- Once a value is assigned to a
wrapper class instance it can not be changed, anymore.
Wrapper Classes: Methods with examples
There are some of the methods of the Wrapper
class which are used to manipulate the data. Few of them are given below:
1. add(int,
Object): Learn to insert an element at the specified position.
2. add(Object): Learn
to insert an object at the end of a list.
3. addAll(ArrayList): Learn
to insert an array list of objects to another list.
4. get(): Learn
to retrieve the elements contained with in an ArrayList object.
5. Integer.toBinaryString(): Learn
to convert the Integer type object to a String object.
6. size(): Learn
to get the dynamic capacity of a list.
7. remove(): Learn
to remove an element from a particular position specified by a index
value.
8. set(int,
Object): Learn to replace an element at the position
specified by a index value.
b.) Java.lang.Math class
To manipulate the mathematical operation
in your program. The Mathclass is used to operate the calculations.
There is not necessary to import any package for the Math class
because this is already in java.lang package.
Any expressions can be operated through certain
method calls. There are some functions have been used in the given example. All
the functions have been explained below with example :
E
This is E field of the Math class which returns
you a default exponent value that is closer than any other to e, the base of
the natural logarithms.
PI
This is also a field of the Method class
which returns you a default pi value, the ratio of the circumference of a
circle to its diameter.
abs()
This is the abs() function which returns you the
absolute number.
ceil()
This is the ceil() function which returns you
the smallest value but greater than the argument.
exp()
This is the exp() function which returns you the
exponential value raised to the power of a double value.
floor()
This is the floor() function which returns you
the largest value but less than the argument.
IEEEremainder()
This is the IEEEremainder() which returns you
the remainder for the given dividend and divisor.
max()
This is the max() function which distinguishes
the maximum value from the two given value.
min()
This is the min() function which distinguishes
the minimum value from the two given value.
pow()
This is the pow() function which returns you the
number raised to the power of a first given value by the another one.
c.) random()
This is the random() function which returns you
the random number. It is absolutely system generated.
rint()
This is the rint() function which returns you a
value closest to the given value.
round()
This is the round() function which returns you a
value that is in the rounded form.
sqrt()
This is the sqrt() function which returns you
the square root of the specified value.
Code for the program :
public class mathclass{
public static void main(String[] args){ //E and round() System.out.println("e = " + Math.round(Math.E*100)/100f); //PI System.out.println("pi = " + Math.round(Math.PI*100)/100f); //abs() System.out.println("Absolute number = " + Math.abs(Math.PI)); //ceil() System.out.println("Smallest value but greater than
the argument = " + Math.ceil(Math.PI));
//exp() System.out.println("Exponent number powered by
the argument = " + Math.exp(0));
//floor() System.out.println("Largest value but less
than the argument = " + Math.floor(Math.E));
//IEEEremainder() System.out.println("Remainder = " +
Math.IEEEremainder(5.3f,2.2f));
//max() System.out.println("Maximum Number = " +
Math.max(10,10.3));
//min() System.out.println("Minimum Number = " +
Math.min(10,10.3));
//pow() System.out.println("Power = " + Math.pow(10,3)); //random() System.out.println("Random Number = " +
Math.random());
//rint() System.out.println("Closest to the Argument
= " + Math.rint(30));
//round() System.out.println("Round = " + Math.round(Math.E)); //sqrt() System.out.println("Square Root = " + Math.sqrt(400)); } } |
d.) Package in java
Ans : In Java, a package is
a group of related types classes and interfaces which
provides access protection and name space management to use those classes and
interfaces. Apart from these, Java also supports special kinds of classes
and interfaces known as Enumerations and Annotation,
respectively.
Packaging is used to organize classes that
belong to the same files or providing similar functionality. Apart from this,
it also helps the programmer to avoid class name collision when we use the
same class name as available in the another packages. For example,
the Date class of java.util package is
used to access the methods of the Date class. But, if we have a class name "Date" (user
defined) in our program, its name would crash with the Date class
of java.util package. To avoid this problem, we can use
Package through which the "Date"class can be put up into
another package like india.mycompany.Date without
collision with anyone.
Generally, classes in one package (or directory)
have different functionality from the another package. For
example, classes in java.io package manage the Input/Output streams
to read and write data from and to files, while classes in java.net package give
us the way to deal with the network operations.
Features of a Java package
- The protected members of the
classes can be accessed by each other in the same package.
- It resolves the naming
collision for the types it contains.
- A package may have the
following types.
- Interfaces
- Classes
- Enumerated types
- Annotations
Naming convention (Rules) for using the packages
- Package names are written in
all lowercase to avoid conflict with the names of classes or interfaces.
- The directory name must be same
as the name of package that is created using "package" keyword
in the source file.
- Before running a program, the
class path must be picked up till the main directory (or package) that is
used in the program.
- If we are not including any
package in our java source file then the source file automatically goes to
the default package.
- In general, we start a package
name begins with the order from top to bottom level.
- In case of the internet domain,
the name of the domain is treated in reverse (prefix) order.
Java Package Names and Directory Structure
Java Packages are usually
defined using a hierarchical naming pattern in which the Package name consists
of words separated by periods. The first part of the Package name represents
the main directory in which other subpackages or classes are put up. The
remaining part of the Package name reflect the sub contents of the
package. Just see the example of packages names:
Internet Domain
|
Package name
|
Subdirectory path
|
java.sun.com
|
com.sun.java.text
|
\com\sun\java\text
|
murach.com
|
com.murach.orders
|
\com\murach\orders
|
Lets see a general example to understand the
directory structure of the package importing the javax.swingpackage.
import javax.swing.*;
public class PackageDemo { public PackageDemo(){ JOptionPane.showMessageDialog(new JFrame(), " This is a Dialog Box component of swing ","My Message", JOptionPane.INFORMATION_MESSAGE); } public static void main(String[] args){ PackageDemo obj=new PackageDemo(); } } |
In the above example, a Java Package "javax.swing" is
a buid-in package imported from the JFC (Java Foundation
Classes). The first name of that package "javax" represents
the main package. The second part of the package name "swing" stands
for the contents of the package. All classes and interfaces reside
in the swing package can be accessed according to their functionality.
How to Set the Class Path:
The classpath is a user defined environment
variable that is used by Java to determine where predefined classes are
located. It tells the java tools and applications where to find user-defined
classes. The syntax to set the classpath is shown as:
C:> set CLASSPATH=%classpath%;classpath1;classpath2.....
|
You can set multiple path entries that are
separated by semi-colons.
To make this thing more understandable, let's
put the "HelloWorld" class along with its package "mypackage"under
the "C:\mainpackage" directory. Thus the directory
structure for this package is shown as:
Now we have changed the location of the package
from C:\mypackage\HelloWorld.java to C:\mainpackage\mypackage\HelloWorld.java.
Then the CLASSPATH needs to be changed to point the new location of
the package mypackage accordingly shown as:
set CLASSPATH =
.;C:\mainpackage;
Although in such condition, Java will look for
java classes from the current directory instead of the "C:\mainpackage" directory.
Access protection in packages:
Access protection
|
Discription
|
No modifier (default)
|
The classes and members specified in the same
package are accessible to
all the classes inside the same package. |
public
|
The classes, methods and member variables under this
specifier can be accessed from anywhere.
|
protected
|
The classes, methods and member variables under this
modifier are accessible by all subclasses,
and accessible by code in same package. |
private
|
The methods and member variables are accessible only
inside the class.
|
Access to fields in Java at a Glance:
Access By
|
public
|
protected
|
default
|
private
|
The class itself
|
Yes
|
Yes
|
Yes
|
Yes
|
A subclass in same package
|
Yes
|
Yes
|
Yes
|
No
|
Non sub-class in the same package
|
Yes
|
Yes
|
Yes
|
No
|
A subclass in other package
|
Yes
|
Yes
|
No
|
No
|
Non subclass in other package
|
Yes
|
No
|
No
|
No
|
e.) Nested Class
Ans
: Nested Classes
The Java programming language allows you to
define a class within another class. Such a class is called a nested
class and is illustrated here:
class OuterClass {
...
class NestedClass {
...
}
}
Terminology: Nested
classes are divided into two categories: static and non-static. Nested classes
that are declared static are called static nested classes.
Non-static nested classes are called inner classes.
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
A nested class is a member of its enclosing
class. Non-static nested classes (inner classes) have access to other members
of the enclosing class, even if they are declared private. Static nested
classes do not have access to other members of the enclosing class. As a member
of the OuterClass, a nested class can be declared private, public, protected,
or package private. (Recall that outer classes can only be
declared public or package private.)
Why Use Nested Classes?
Compelling reasons for using nested classes
include the following:
· It
is a way of logically grouping classes that are only used in one place: If
a class is useful to only one other class, then it is logical to embed it in
that class and keep the two together. Nesting such "helper classes"
makes their package more streamlined.
· It
increases encapsulation: Consider two top-level classes, A and B, where B
needs access to members of A that would otherwise be declared private. By
hiding class B within class A, A's members can be declared private and B can
access them. In addition, B itself can be hidden from the outside world.
· It
can lead to more readable and maintainable code: Nesting small classes
within top-level classes places the code closer to where it is used.
Static Nested Classes
As with class methods and variables, a static
nested class is associated with its outer class. And like static class methods,
a static nested class cannot refer directly to instance variables or methods
defined in its enclosing class: it can use them only through an object
reference.
Note: A static nested
class interacts with the instance members of its outer class (and other
classes) just like any other top-level class. In effect, a static nested class
is behaviorally a top-level class that has been nested in another top-level
class for packaging convenience.
Static nested classes are accessed using the
enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static
nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
f.) Inner Class
Ans :
Nested Class: Class
defined within another class is called nested class. Nested class is divided
into two parts-
1.Static
2.Non-static Static nested class is declared
static. Non-static nested class is also called inner class.
Example:
public class
NestedClass{
private String outer = "Outer Class"; //NestedClass instance variable
InnerClass innerClass = new InnerClass();
void
getOuterS(){
System.out.println(outer);
}
void
getInnerS(){
System.out.println(innerClass.inner);
}
class
InnerClass{
private String inner = "Inner Class"; //InnerClass instance variable,
uninitialized
void getInnerS(){
System.out.println(inner);
}
void getOuterS(){
System.out.println(NestedClass.this.outer);
}
}
public static void main(String[] args){
NestedClass nestedClass = new NestedClass();
NestedClass.InnerClass nestedInner = nestedClass.new InnerClass();//can also be
new NestedClass().new InnerClass ();
nestedClass.getOuterS();
nestedClass.getInnerS();
nestedInner.getInnerS();
nestedInner.getOuterS();
}
}
g.) Inner nested class
Ans : Non-static
nested classes are slightly different from static nested classes, a non-static
nested class is actually associated to an object rather than to the class in
which it is nested.
Any member of the inner nested class is not a
part of its outer class while its source code is in the class definition.
Non-static members of a class specify the requirements of objects created from
that class. Every object has a copy of the nested class that belongs to the
outer class. The same copy should access all the methods and instance variables
of that object.
Methods and variables of an inner class can be
access directly by the object of outer class.
Lets try to explain the concept of inner nested
class with the help of an example. There is an inner classcompany exists
within an outer class Info. The class Info is to be referred as
non-static nested class. The class Info invokes the method of the class Company with
the help of the object of the class Company.
Here is the code of the Example :
Info.java
import java.lang.*;
public class Info{ static String compName="Rose India"; public static class Company{ int time=10; void showinfo(){ System.out.println("Our Company Name : "+compName); System.out.println("The time of the company : "+time); } } public static void main(String[] args){ Info.Company object = new Info.Company(); object.showinfo(); } } |
Here is the output of the Example:
C:\roseindia>javac Info.java
C:\roseindia>java Info Our Company Name : Rose India The time of the company : 10 |
h.) Constructor
Ans: Every
class has at least one it's own constructort. Constructor creates a
instance for the class. Constructor initiates (initialize) something related to
the class's methods. Constructor is the method which name is same to the class.
But there are many difference between the method (function) and the
Constructor.
In this example we will see that how to to
implement the constructor feature in a class. This program is using two
classes. First class is another and second is the main class which
name is Construct. In the Construct class two objects
(a and b) are created by using the
overloaded another Constructor by passing different arguments and
calculated the are of the different rectangle by passing different values for
the another constructor.
Here is the code of the program :
class another{
int x,y; another(int a, int b){ x = a; y = b; } another(){ } int area(){ int ar = x*y; return(ar); } } public class Construct{ public static void main(String[] args) { another b = new another(); b.x = 2; b.y = 3; System.out.println("Area of rectangle : " + b.area()); System.out.println("Value of y in another class : " + b.y); another a = new another(1,1); System.out.println("Area of rectangle : " + a.area()); System.out.println("Value of x in another class : " + a.x); } } |
Output of the program :
C:\chandan>javac Construct.java
C:\chandan>java Construct Area of rectangle : 6 Value of x in another class : 3 Area of rectangle : 1 Value of x in another class : 1 |
i.) Super keyword
Ans : The super is
a keyword defined in the java programming language. Keywords are basically
reserved words which have specific meaning relevant to a compiler in java
programming language likewise the super keyword indicates the
following :
-- The super keyword in java programming language refers to the superclass of
the class where the super keyword is currently being used.
-- The super keyword as a standalone statement is used to call the
constructor of the superclass in the base class.
Example to use the super keyword to call the
constructor of the superclass in the base class:
public
class Class1{
public Class1(String
arg){
super(arg);
} |
-- The syntax super.<method_Name>() is used to give
a call to a method of the superclass in the base class.
-- This kind of use of the super keyword is only necessary when we need
to call a method that is overridden in this base class in order to specify that
the method should be called on the superclass.
Example to use the super keyword with a method:
public
class Class1{
public
String String_Method(){
return
super.overriden_String_Method();
} |
j.) This keyword
Ans : The keyword this is
useful when you need to refer to instance of the class from its method. The
keyword helps us to avoid name conflicts. As we can see in the program that we
have declare the name of instance variable and local variables same. Now to
avoid the confliction between them we use this keyword. Here,
this section provides you an example with the complete code of the program for
the illustration of how to what is this keyword and how to use
it.
In the example, this.length and this.breadth refers
to the instance variable length and breadth while length and breadth refers to
the arguments passed in the method. We have made a program over this.
After going through it you can better understand.
Here is the code of the program:
class Rectangle{
int length,breadth; void show(int length,int breadth){ this.length=length; this.breadth=breadth; } int calculate(){ return(length*breadth); } } public class UseOfThisOperator{ public static void main(String[] args){ Rectangle rectangle=new Rectangle(); rectangle.show(5,6); int area = rectangle.calculate(); System.out.println("The area of a Rectangle is : " + area); } } |
Output of the program is given below:
C:\java>java UseOfThisOperator
The area of a Rectangle is : 30 |
k.) Access specifier in java
Ans :
Access Modifiers : Access modifiers are used to specify the visibility and
accessibility of a class, member variables and methods. Java provides some
access modifiers like: public, private etc.. These can also be used with the
member variables and methods to specify their accessibility.
public keyword specifies that the public
class, the public fields and the public methods can be accessed from
anywhere.
private: This keyword provides the
accessibility only within a class i.e. private fields and methods can be
accessed only within the same class.
protected: This modifier makes a member of
the class available to all classes in the same package and all sub classes of
the class.
default : Its not a keyword. When we don't
write any access modifier then default is considered. It allows the class,
fields and methods accessible within the package only.
Q5. What do you mean by interface? Write a java
program to demonstrate interface.
Why use interface in java?
- We use it to achieve complete
abstraction.
- The interface, we can support
the functionality of the multiple inheritance.
- we can use it to achieve loose
coupling.
- We can implement all method
heading listed in interface.
- We can take the interface
check, that implements a empty method message().
How to create interface in java program: Following is the code of interface in java program. We have
created interface method in java using "interface" keyword.
Example:
interface Demo
{ void call(); }
interface
Demo1{ void run(); }
class CallTest
implements Demo{
public void call() {
System.out.println("Hello java");
}}
class RunTest implements Demo1{
public void run(){
System.out.println("Hello interface");
}
}
public class
interfaceDemo{
public static void main(String[] args) {
Demo demo = new CallTest();
Demo1 demo1 = new RunTest();
demo.call();
demo1.run();
} }
Unit III
Q 1. Write a java program to create user defined
exception.
Ans : In Java API all
exception classes have two type of constructor. First is called default
constructor that doesn't accept any arguments. Another constructor
accepts a string argument that provides the additional information about the
exception. So in that way the Custom exception behaves like the rest of
the exception classes in Java API.
There are two primary use cases for a custom
exception.
- your code can simply
throw the custom exception when something goes wrong.
- You can wrap an exception
that provides extra information by adding your own message.
The code of a Custom exception:
public class ExceptionClassName extends Exception
{
public ExceptionClassName(){ }
public ExceptionClassName(StringMessage)
{
super(message);
}
}
|
Lets see an example that
has the implementation of User Define Exception:
import java.io.*;
import java.util.*;
class
MyException extends Exception
{ private String nm=""; public String getMessage(String s) {
nm=s;
return ("you are not permitted to enter inside "+nm); } } public class ExcepDemo { public static void main(String args[])throws MyException,IOException {
String temp="";
try
{ String str="amit"; System.out.println("Enter the your name"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); temp=br.readLine();
if(!temp.equals(str))
throw new MyException(); else System.out.println("Welcome to Siddhant College Sudumbare Pune "); } catch(MyException e) { System.err.println(e.getMessage(temp)); } catch(Exception e){ System.err.println(e); } } } |
Output of the program:
C:\tybca\>javac ExcepDemo.java
C:\
tybca \>java ExcepDemo
Enter
the your name
Nisha
Sharma
you
are not permitted to enter inside nisha
C:\
tybca \>java ExcepDemo
Enter
the your name
Kanhaiya
Sharma
Welcome
to Siddhant College Sudumbare
|
In this example we have created own exception
class as MyException that throws an exception and a function
with argument as getMessage that shows an exception message,
if the user tries to enter the another name which doesn't match with a
particular predefined name. After throwing exception the control will be
transferred in the catch block to handle the exception where the function
is invoked to display the message included in that function.
Q 2. Explain different types of exception in
java.
Ans: There are two types of Exception
in java.
1. Language defined Exceptions
2. User defined Exceptions
Following are the language defined exceptions.
Here is the list of Java Exception handling
tutorials:
Exception is a run-time error which arises during the execution of
java program. The term exception in java stands for an exceptional
event. It can be defined as abnormal event that arises during the
execution and normal flow of program.
When an error occurs in a method, Java creates an object of the Exception
method. On making an object of exception method, java send it to the program by
throwing the object of exception method.
NumberFormatException is a subclass of the Runtime Exception class. A
Number Format Exception occurs in the java code when a programmer tries to
convert a String into a number.
Null pointer exceptions are the most common run time exception error
arises during execution of java program. All values in Java programs are
references to objects, and all the value in variable are default one.
Index Out of Bound Exception are the Unchecked Exception that occurs
at run-time errors. This arises because of invalid parameter passed to a
method in a code.
What is exception and exception handling in Java. This tutorial is going to
show you how to handle different types of exception in Java with the example
codes.
Here we are describing the example to show the use of Java class exception.
Go through the given example to find about such exceptions and the cause of
occurring it.
Here we are describing the use of using Argument exception in java
.Exceptions are the way in Java to indicate to a calling method that an
abnormal condition has occurred.
Here we are describing the way to compile the java file with the help of
the java program.
In this java program we are writing code for handling
Constructor exception. By Handling exception we generally mean handling
errors.
This tutorial describes how to handle Array list
exceptions appropriately in your programs and designs.
The example is talking about the exception that occurs during
the type casting in Java program. Here you will be able to see and handle the
java cast exception.
Clone means true copy of any thing whether it is a human being
or application program. In this tutorial we will show you how to create a clone
and handling the exception that occurs due to it in Java.
The tutorial is about the use of collection in Java and the
exception that occurs when some unexpected situation occurs in program like
deletion of files etc.. here you will learn to handle such type of collection
error in Java.
Exception in Java are classified on the basis of the
exception handled by the java compiler.
As we come across Built -in-exception, you create own customized
exception as per requirements of the application. On each application there is
a specific constraints.
As you know, Interface is just a reference type that do not contain method and
body in Java. It is just like any other class. In this tutorial we are going to
discuss about the Java Interface error and will show you how to handle
it.
In this section, you are learning about handling double exceptions in Java. In
Java double is used to store the decimal value, here we will learn why the
double exception occurs.
The tutorial is going to describe Java Enumeration and the type of exception
occurs while using it in your program.
Finally block is optional, if you want you can use it with try
and catch block. But if you want to do more then exception handling, use
finally. In this example we are going to show you finally exception in
java.
If you are developing the application, you can face any type of
exceptions. Integer exception could be one of them. This type of exception
occurs when user enters the wrong value. This tutorial describes how to
handle integer exceptions appropriately in your programs and
designs.
In this Java Exception tutorial, you have learned about various
types of exception in Java. But the given example is going to show you how to
create an object of an exception in Java. Creating objects in Java is very
simple and easy to learn an use.
Introduction to Java Array Exception and solutions to handle
it. This tutorial illustrate array exception in Java, it's cause of
occurring and steps to handle it.
In the given example, you will be introduced with array out of bound exception
in Java, and the way to handle such kind of exception.
Hash Map is used to provide key Value access to data. In this
example we are describing the way to handle HashMap exception appropriately in
your programs and designs.
In this section, we are describing, what is the hash table
and and when a hash-table exception occurs in Java.
This Example will show you, how and when Iterator exception
occurs in Java and what are the possible ways of handling these types of
exception. Go through the given Java Iterator example to see how to use an
Iterator in separate parts of your program.
As we come across Built -in-exception, you create own customized exception
as per requirements of the application. On each application there is a specific
constraints.
The java. lang package include several classes and
exceptional classes. This exceptional classes are the subclasses of run-time
exception, that is used further in exception handling.
Unhandled Exception are the exception that are thrown during
the execution of program. These exception are never caught during the execution
of program.
Assertion are simple check assumption made at the beginning of
the program to ensure the program is true throughout provided by
the Java language.
Serialization is the process of writing an class object that is
transmitted through the network in the encoded stream of byte form. This
Encoded form can be reconstructed from the network by reading from byte of
stream.
Static method in parseInt is derived from package java.lang.integer.public
static method int parseInt(String s) gives you
NumberFormatException.
Exception in Java are classified on the basis of the exception
handled by the java compiler.
Thread is the independent path of execution run inside the program.
Many Thread run concurrently in the program. Multithread are those group of
more than one thread that runs concurrently in a
program.
Simple Date Format Exception inherits from a package name
java.text.SimpleDateFormat and implements
interfaceCloneable,Serializable.SimpleDateFormat is a concrete class.
Q 3. Write a java program to read bytes from
given File.
Ans : This program reads the bytes from file and display it to the
user.
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Output of the Program:
C:\Tybca>javac FileRead.java
C:\ Tybca >java
FileRead
this is a file C:\ Tybca > |
Q 4. Write a java program to Java count characters from file.
Ans: Description of code:
Firstly, we have used FileReader and
BufferedReader class to read the file 'data.txt' and stored the data into
string. Then we have removed all the spaces between the string using
replaceAll() method and convert the string to lowercase. This string is then
converted into character array in order to count the occurrence of each
character of the array.
Here is the data.txt:
Hello
All glitters are not gold |
Here is the code:
import java.io.*;
import java.util.*;
class CountCharactersFromFile {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new
FileReader("C:/data.txt"));
String strLine = "";
String str = "";
while ((strLine = br.readLine()) != null) {
str += strLine;
}
String st = str.replaceAll(" ", "").toLowerCase();
char[] third = st.toCharArray();
System.out.println("Character Total");
for (int counter = 0; counter < third.length; counter++) {
char ch = third[counter];
int count = 0;
for (int i = 0; i < third.length; i++) {
if (ch == third[i])
count++;
}
boolean flag = false;
for (int j = counter - 1; j >= 0; j--) {
if (ch == third[j])
flag = true;
}
if (!flag) {
System.out.println(ch +
"
" + count);
}
}
}
}
Through the above code, you can read the file
and count the occurrence of each character of the content of the file.
Output:
Character Total
h 1 e 3 l 6 o 3 a 2 g 2 i 1 t 3 r 2 s 1 n 1 d 1 |
Q 5. Write a java program to copy contains of
one file to other file.
Ans :Introduction
This example illustrates how to copy
contents from one file to another file. This topic is related to the I/O
(input/output) of java.iopackage.
In this example we are using File class of java.io package.
The File class is an abstract representation of file and directory pathnames.
This class is an abstract, system-independent view of hierarchical pathnames.
Anabstract pathname has two components:
An optional system-dependent prefix string,
such as a disk-drive specifier, "/" for the UNIX root
directory, or "\\" for a Win32 UNC pathname, and
A sequence of zero or more string names.
Explanation
This program copies one file to another file. We
will be declaring a function called copyfile which copies the
contents from one specified file to another specified file.
copyfile(String srFile,
String dtFile)
The function copyfile(String srFile, String
dtFile) takes both file name as parameter. The function creates a new File
instance for the file name passed as parameter
File f1 = new File(srFile);
File f2 = new File(dtFile);
and creates another InputStream instance for the
input object and OutputStream instance for the output object passed as
parameter
InputStream in = new
FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
and then create a byte type buffer for buffering
the contents of one file and write to another specified file from the first one
specified file.
byte[] buf = new byte[1024];
// For creating a byte type buffer
out.write(buf, 0, len); // For writing to another specified file from buffer buf
Code of the Program :
import java.io.*;
public class CopyFile{ private static void copyfile(String srFile, String dtFile){ try{ File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1);
//For Append the file.
// OutputStream out = new FileOutputStream(f2,true); //For Overwrite the file. OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0){ out.write(buf, 0, len); } in.close(); out.close(); System.out.println("File copied."); } catch(FileNotFoundException ex){ System.out.println(ex.getMessage() + " in the specified directory."); System.exit(0); } catch(IOException e){ System.out.println(e.getMessage()); } } public static void main(String[] args){ switch(args.length){ case 0: System.out.println("File has not mentioned."); System.exit(0); case 1: System.out.println("Destination file has not mentioned."); System.exit(0); case 2: copyfile(args[0],args[1]); System.exit(0); default : System.out.println("Multiple files are not allow."); System.exit(0); } } } |
Output of program:
Here the data of "Hello.java" file
is copied to the Filterfile.txt file.
C:\Tybca>javac CopyFile.java
C:\ Tybca >java CopyFile a.java Filterfile.txt File copied. C:\ Tybca > |
You can even use this program for copying files
from one hard drive to another hard drive.
Q6. Write short note on following.
a.) Stream
b.) ByteStream Classes
c.) CharacterStream Classes
Stream
Ans: The sequence of data can be defined as a
stream. Java defines two types of streams which are given below :
1. Byte
2. Characters
Byte Stream
For dealing input and output of bytes, byte stream is
employed. For reading and writing binary data it is incorporated. Binary Stream
uses two abstract classes for input and output. These are InputStream class and
OutputStream class respectively. To read data from the source InputStream is
used and to write data to a destination OutputStream is used.
The byte stream classes are given below :
Byte Stream Classes
|
Detail
|
InputStream
|
The InputStream is an abstract super class .All the
classes representing an input
stream of bytes is the subclass of this super class. |
OutputStream
|
The OutputStream is an abstract super class .All the
classes representing an output
stream of bytes is the subclass of this super class. |
FileInputStream
|
In a file system, it gets input bytes from a file.
|
FileOutputStream
|
Using it you can write data to a File or to a
FileDescriptor.
|
ByteArrayInputStream
|
A ByteArrayInputStream has an internal buffer. This buffer
can retain bytes read from the stream
|
ByteArrayOutputStream
|
Data can be written into a byte array using the output
stream of ByteArrayOutputStream.
|
SequenceInputStream
|
The input streams can be logically concatenated using
SequenceInputStream.
|
StringBufferInputStream
|
The string's content supplies bytes read to an input
stream which is created by an application.
The StringBufferInputStream class allows an application to do this. |
FilterInputStream
|
It has some additional input stream used as basic data
source, These input streams can provide
transformation of data and extra functionality. |
FilterOutputStream
|
All the classes that filter output streams is the
subclasses of the FilterOutputStream superclass.
|
DataInputStream
|
It allows an application to read java's data type using an
input stream which is independent of machine.
|
DataOutputStream
|
It allows an application to write java's data
type(primitive) to an output stream.
|
BufferedInputStream
|
It provides additional functionality to the input stream
such as capability to buffer. It also supports reset and mark methods.
|
BufferedOutputStream
|
The buffered output stream is applied by this class.
|
PrintStream
|
It provide ability to the other output stream to print
several data values' representation.
|
PipedInputStream
|
The data byte written on piped output stream is provided
by PipedInputStream. But before that it must connect to the piped output
stream.
|
PipedOutputStream
|
For creating communication pipe, piped output stream
should be connected to piped output stream.
|
PushbackInputStream
|
To sum up the ability to "push back" or
"unread" one byte to other input stream, a PushbackInputStream is
used.
|
RandomAccessFile
|
For accessing a file randomly (for reading or writing)
this class is incorporated.
|
Methods defined by InputStream
After creating InputStream object, you can
perform additional operations on the stream using given below methods :
Methods
|
Description
|
public void close() throws IOException{}
|
The output stream of a file is closed using this function.
Before that it releases any resource. This function throws IOException.
|
protected void finalize()throws IOException {}
|
This function clears the connection to the file. It throws
an IOException.
|
public int read(int r)throws IOException{}
|
This function reads the data from the InputStream and
return int which is next byte of data. It also returns
-1 if end of file is reached. |
public int read(byte[] r) throws IOException{}
|
This method reads data equal to length of r from the input
stream using array. The total number of bytes read is returned after
finishing reading. When end of file reached it returns -1.
|
public int available() throws IOException{}
|
This function returns the number of bytes available for
reading from file input stream. The return type is int.
|
Method defined by OutputStream
Once you have OutputStream object
in hand then there is a list of helper methods which can be used to write to
stream or to do other operations on the stream.
Methods
|
Description
|
public void close() throws IOException{}
|
This function closes the output stream of the file and
throws IOException.
|
protected void finalize()throws IOException{}
|
This function closes the connection to the file and throws
IOException.
|
public void write(int w)throws IOException{}
|
Using this function, you can write specified bytes to the
output stream.
|
public void write(byte[] w)
|
This function is used to write bytes of length equal to w
to the output stream from the the mentioned byte array.
|
Character Stream
For handling the input and output of characters
Character Stream is incorporated, which streamlines internationalization.
The hierarchical distribution of Character
stream is different from Byte Stream. The hierarchical tree of
Character Stream is topped by the Reader and Writer abstract classes. Reader
abstract class is used for input while Writer abstract class is used for
output.
The method defined by Reader abstract class is
given below :
Function / Method
|
Description
|
abstract void close( ) throws IOException
|
The input source is closed using this function.
|
void mark(int numChars) throws IOException
|
This function set a mark in the input stream at the
current point. This Point will remain valid till numChars characters are
read.
|
boolean markSupported( )
|
If the stream support mark( )/reset( ) , this function
returns true.
|
int read( ) throws IOException
|
The input streams' next available character is return by
this function as an integer representation.
|
int read(char buffer[ ]) throws IOException
|
This function reads the characters from buffer equal to the
length of buffer.length and it returns the number of successful characters
read.
|
abstract int read(char buffer[ ],int offset, int numChars)
throws IOException
|
This function returns the count of the characters
successfully read from buffer starting from buffer[offset] up to numChars.
|
boolean ready( ) throws IOException
|
If the input is pending, it returns true otherwise false.
|
void reset( ) throws IOException
|
This function resets the input pointer to the previously
set mark.
|
long skip(long numChars) throws IOException
|
This function skips the number of input characters equal
to numChars. It returns the count of actually skipped characters.
|
The method defined by Writer abstract class is
given below :
Function / Method
|
Description
|
Writer append(char ch) throws IOException
|
This function adds ch at the end of the output stream
which invoked it. It also returns reference to the stream.
|
Writer append(CharSequence chars) throws IOException
|
This function adds the chars to the end of the
output stream which invoked it. It also returns a reference to the stream.
|
Writer append(CharSequence chars, int begin, int end)
throws IOException
|
This function adds a sub range of chars to the end of the
output stream. It returns a reference to the stream.
|
abstract void close( ) throws IOException
|
The output stream is closed by this function.
|
abstract void flush( ) throws IOException
|
This function flushes the buffer of output.
|
void write(int ch) throws IOException
|
This function writes the character to the output stream.
The characters are in the low-order 16 bits of ch .
|
void write(char buffer[ ]) throws IOException
|
Using this function you can write to the output stream -a
complete array of characters .
|
abstract void write(char buffer[ ],int offset, int
numChars) throws IOException
|
This function is used to writes a sub range of numChars
characters from the array buffer to the output stream beginning at
buffer[offset].
|
void write(String str) throws IOException
|
Using this function you can writes str to the output
stream.
|
void write(String str, int offset, int numChars)
|
Using this function, from the string str ,you can write a
sub range of numChars characters.
|
The File Class
In spite of classes available to support file
I/O, Java has a class named as File, which contains
information about a file. For manipulating a file or the
computer's file system, this class is very effective and efficient. This class
is used for creation of files and directories, file searching, file deletion
etc.
Once you have File object in
hand then there is a list of helper methods which can be used manipulate the
files, which are given below :
Methods
|
Description
|
public String getName()
|
This function returns the file or directory's name
specified by the pathname.
|
public String getParent()
|
This function returns the parent directory pathname
string. The pathname of the directory is passed to know it's parent pathname
string. If the pathname doesn't have parent directory, it returns null.
|
public File getParent File()
|
This function returns the parent directory abstract
pathname and it returns null if it doesn't have parent directory.
|
public String getPath()
|
To convert the abstract pathname into a pathname string,
we use this function.
|
public boolean isAbsolute()
|
This function return true if this abstract pathname is
absolute otherwise returns false.
|
public String getAbsolutePath()
|
To find the absolute pathname string of the provided
abstract pathname, we incorporate this method.
|
public boolean canRead()
|
This function is used to check if the application can read
the file provided by this abstract
pathname. This function returns true if the file name provided by the abstract pathname exists otherwise return false. |
public boolean canWrite()
|
This function is used to check if the application can
modify to the file provided through this abstract
pathname. This function returns true if the file name provided by the abstract pathname exists and allowed to write, otherwise return false. |
public boolean exists()
|
This function returns true if the file name provided by
the abstract pathname exists otherwise return false.
|
public boolean isDirectory()
|
This function returns true if the file represented by the
abstract pathname is a directory otherwise returns false.
|
public boolean isFile()
|
This function is used to test whether the file represented
by the abstract pathname exist and also checks whether it is a normal file.
If it is , it will return true otherwise return false.
|
public long lastModified()
|
This function is used to return the last modification time
of the file represented by the abstract pathname.
|
public long length()
|
This function finds the length of the file of the file
represented by the abstract pathname and return it. It returns unspecified if
the pathname represented is a directory.
|
public boolean createNewFile()
throws IOException |
This function is used to create a new file which has the
name provided by its abstract pathname. It will return true if the file
created successfully otherwise returns false.
|
public boolean delete()
|
This function is used to delete the file/directory
represented by the abstract pathname.
|
public void deleteOnExit()
|
This function is used to delete the file represented by
the abstract pathname when the virtual machine terminates.
|
public String[] list()
|
This function returns an array of strings naming the files
and directories in the directory specified by its abstract
pathname.
|
public String[] list(FilenameFilter filter)
|
This function returns an array of strings naming the files
and directories in the directory specified by its abstract pathname that
satisfy the specified filter.
|
public File[] listFiles()
|
This functions returns an array of abstract pathnames
represented by the files in the directory.
|
public File[] listFiles(FileFilter filter)
|
This function returns an array of abstract pathnames
represented by the files and directories
in the directory represented by this abstract pathname that satisfy the specified filter. |
public boolean mkdir()
|
This function creates the directory named by this abstract
pathname. this function returns true if the file created successfully
otherwise false.
|
public boolean mkdirs()
|
This method creates the directory named by this abstract
pathname, including any
necessary but nonexistent parent directories. Returns true if and only ifbr> the directory was created, along with all necessary parent directories; false otherwise |
public boolean renameTo(File dest)
|
This function renames the file represented by this
abstract pathname.
|
public boolean setLastModified(long time)
|
This function is used to set the last modification time of
the file/ directory specified by the abstract
pathname. |
public boolean setReadOnly()
|
This function sets the file provided through abstract
pathname to read-only mode. If it succeeded, it returns true otherwise
returns false.
|
public String toString()
|
This function is used to return the pathname string of the
abstract pathname provided.
|
FileReader Class
FileReader class inherits from the InputStreamReader class.
For reading streams of characters, this class is used.
Once you have FileReader object
in hand then there is a list of helper methods which can be used manipulate the
files :
Method / Function
|
Description
|
public int read() throws IOException
|
This function reads a single character at a time and
returns the count of number of character read.
|
public int read(char [] c, int offset, int len)
|
This function is used to read characters. An array is used
to read characters.
|
FileWriter Class
FileWriter Class inherits from the OutputStreamWriter class.
For writing streams of characters, this class is incorporated.
Methods / Function
|
Description
|
public void write(int c) throws IOException
|
Using this function, you can write a single character.
|
public void write(char [] c, int offset, int len)
|
Using this function, you can write a part of an array
specified by offset(starting) up to the length from offset.
|
public void write(String s, int offset, int len)
|
Using this function, you can write a part of an String
specified by offset(starting) up to the length(specified by len) from offset.
|
d.) ByteStream Classes
Ans : refer above solution
e.) CharacterStream Classes
Ans : refer above solution
Unit V
Q 1.What are the advantages and disadvantages of
using applet? Explain life cycle of applet.
Q2. Write procedure of creating, compiling and
executing applets in java.
Q 3. Write a java program to draw human face in
applet.
Q 4. Write a java program to draw national Flag
in applet.
Q 5. Write a java program to draw pi chart in
applet.
Q 6. Explain different types of Layout Managers
Q7. Write short note on flowing.
Event delegation model
Adapter Class
Swing Component
Color Class in Applet
Graphics Class in Applet
Ans : Introduction
Applet is java program that can be embedded into HTML pages. Java applets runs
on the java enables web browsers such as mozila and internet explorer. Applet
is designed to run remotely on the client browser, so there are some
restrictions on it. Applet can't access system resources on the local computer.
Applets are used to make the web site more dynamic and entertaining.
Advantages of Applet:
- Applets are cross platform and
can run on Windows, Mac OS and Linux platform
- Applets can work all the
version of Java Plugin
- Applets runs in a sandbox, so
the user does not need to trust the code, so it can work without security
approval
- Applets are supported by most
web browsers
- Applets are cached in most web
browsers, so will be quick to load when returning to a web page
- User can also have full access
to the machine if user allows
Disadvantages of Java Applet:
- Java plug-in is required to run
applet
- Java applet requires JVM so
first time it takes significant startup time
- If applet is not already cached
in the machine, it will be downloaded from internet and will take time
- Its difficult to desing and
build good user interface in applets compared to HTML technology
lifecycle of an applet and different
methods of an applet. Applet runs in the browser and its lifecycle method are
called by JVM when it is loaded and destroyed. Here are the lifecycle methods
of an Applet:
init(): This method is called to initialized an applet
start(): This method is called after the initialization of the applet.
stop(): This method can be called multiple times
in the life cycle of an Applet.
destroy(): This method is called only once in
the life cycle of the applet when applet is destroyed.
init () method: The life cycle of an applet is begin on that time when
the applet is first loaded into the browser and called the init() method. The
init() method is called only one time in the life cycle on an applet. The
init() method is basically called to read the PARAM tag in the html file. The
init () method retrieve the passed parameter through the PARAM tag of html file
using get Parameter() method All the initialization such as initialization of
variables and the objects like image, sound file are loaded in the init ()
method .After the initialization of the init() method user can
interact with the Applet and mostly applet contains the init()
method.
Start () method: The start method of an applet is called after the
initialization method init(). This method may be called multiples time when the
Applet needs to be started or restarted. For Example if the user wants to
return to the Applet, in this situation the start Method() of an Applet will be
called by the web browser and the user will be back on the applet. In the start
method user can interact within the applet.
Stop () method: The stop() method can be called multiple times in the life
cycle of applet like the start () method. Or should be called at least one
time. There is only miner difference between the start() method and stop ()
method. For example the stop() method is called by the web browser on that time
When the user leaves one applet to go another applet and the start() method is
called on that time when the user wants to go back into the first program or
Applet.
destroy() method: The destroy() method is called only one
time in the life cycle of Applet like init() method. This method is called only
on that time when the browser needs to Shut down.
Q2. Write procedure of creating, compiling and
executing applets in java.
Ans :Creating
First Applet Example:
First of all we will know about
the applet. An applet is a program written in java programming language and
embedded within HTML page. It runs on the java enabled web browser such as
Netscape navigator or Internet Explorer.
In this example you will see, how to write an
applet program. Java source of applet is then compiled into java class file and
we specify the name of class in the applet tag of html page. The java enabled
browser loads class file of applet and run in its sandbox.
Here is the java code of program :
import java.applet.*;
import java.awt.*; public class FirstApplet extends Applet{ public void paint(Graphics g){ g.drawString("Welcome in Java Applet.",40,20); } } |
Here is the HTML code of the program:
<HTML>
<HEAD> </HEAD> <BODY> <APPLET ALIGN="CENTER"CODE="FirstApplet.class" WIDTH="800"HEIGHT="500"></APPLET> </BODY> </HTML> |
Passing Parameter in Java Applet: Java applet has the feature of retrieving the parameter
values passed from the html page. So, you can pass the parameters from your
html page to the applet embedded in your page. Theparam tag(<parma
name="" value=""></param>) is used to pass the
parameters to an applet. For the illustration about the concept of applet and
passing parameter in applet, a example is given below.
In this example, we will see what has to be done
in the applet code to retrieve the value from parameters. Value of a parameter
passed to an applet can be retrieved using getParameter() function.
E.g. code:
String strParameter = this.getParameter("Message");
Printing the value:
Then in the function paint (Graphics
g), we prints the parameter value to test the value passed from html page.
Applet will display "Hello! Java Applet" if no parameter is
passed to the applet else it will display the value passed as parameter. In our
case applet should display "Welcome in Passing parameter in java applet
example." message.
Here is the code for the Java Program :
import java.applet.*;
import java.awt.*; public class appletParameter extends Applet { private String strDefault = "Hello! Java Applet."; public void paint(Graphics g) { String strParameter = this.getParameter("Message"); if (strParameter == null) strParameter = strDefault; g.drawString(strParameter, 50, 25); } } |
Here is the code for the html program :
<HTML>
<HEAD> <TITLE>Passing Parameter in Java Applet</TITLE> </HEAD> <BODY> This is the applet:<P> <APPLET code="appletParameter.class" width="800" height="100"> <PARAM name="message" value="Welcome in Passing parameter in java applet example."> </APPLET> </BODY> </HTML> |
There is the advantage that if need to change
the output then you will have to change only the value of the param tag in html
file not in java code.
Compile the program :
javac appletParameter.java
Output after running the program :
To run the program using appletviewer, go to
command prompt and type appletviewer appletParameter.htmlAppletviewer
will run the applet for you and and it should show output like Welcome
in Passing parameter in java applet example. Alternatively you can
also run this example from your favorite java enabled browser.
Q 3. Write a java program to draw human face in
applet.
Ans :
import java.awt.*;
import java.applet.*;
public class Smiley extends Applet{
public void paint(Graphics g){
Font f = new Font("Helvetica", Font.BOLD,20);
g.setFont(f);
g.drawString("Keep Smiling!!!", 50, 30);
g.drawOval(60, 60, 200, 200);
g.fillOval(90, 120, 50, 20);
g.fillOval(190, 120, 50, 20);
g.drawLine(165, 125, 165, 175);
g.drawArc(110, 130, 95, 95, 0, -180);
}
}
Q 4. Write a java program to draw national Flag
in applet.
Ans :
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
class Ball
{
int x,y,radius,dx,dy;
Color BallColor;
public Ball(int x,int y,int radius,int
dx,int dy,Color bColor)
{
this.x=x;
this.y=y;
this.radius=radius;
this.dx=dx;
this.dy=dy;
BallColor=bColor;
}
}
public class BouncingbALL extends Applet
implements Runnable{
Ball redBall,blackBall,greenBall;
public void init()
{
redBall=new
Ball(80,80,20,2,4,Color.red);
greenBall=new
Ball(80,80,20,2,4,Color.green);
blackBall=new
Ball(40,70,20,4,2,Color.black);
Thread t=new Thread(this);
t.start();
}
public void paint(Graphics g)
{
g.setColor(redBall.BallColor);
g.fillOval(redBall.x,
redBall.y, redBall.radius, redBall.radius);
g.setColor(greenBall.BallColor);
g.fillOval(greenBall.x,
greenBall.y, greenBall.radius, greenBall.radius);
g.setColor(blackBall.BallColor);
g.fillOval(blackBall.x,
blackBall.y, blackBall.radius, blackBall.radius);
}
public void run()
{
while(true)
{
try
{
displacementOperation(redBall);
displacementOperation(blackBall);
displacementOperation(greenBall);
Thread.sleep(20);
repaint();
}
catch(Exception e){}
}
}
//This method checks the boundary condition of
ball movement
public void displacementOperation(Ball ball)
{
if(ball.y >= 200 || ball.y <= 0)
{
ball.dy=-ball.dy;
}
if(ball.x >= 200 || ball.x <= 0)
{
ball.dx=-ball.dx;
}
ball.y=ball.y-ball.dy;
ball.x=ball.x-ball.dx;
}
}
Q 5. Write a java program to draw pi chart in
applet.
Ans :import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
class Slice {
double value;
Color color;
public Slice(double value, Color
color) {
this.value = value;
this.color = color;
}
}
class MyComponent extends JComponent {
Slice[] slices = { new Slice(5,
Color.black),
new Slice(33, Color.green),
new Slice(20, Color.yellow), new
Slice(15, Color.red) };
MyComponent() {}
public void paint(Graphics g) {
drawPie((Graphics2D) g,
getBounds(), slices);
}
void drawPie(Graphics2D g,
Rectangle area, Slice[] slices) {
double total = 0.0D;
for (int i = 0; i <
slices.length; i++) {
total +=
slices[i].value;
}
double curValue = 0.0D;
int startAngle = 0;
for (int i = 0; i <
slices.length; i++) {
startAngle =
(int) (curValue * 360 / total);
int arcAngle =
(int) (slices[i].value * 360 / total);
g.setColor(slices[i].color);
g.fillArc(area.x, area.y, area.width, area.height,
startAngle,
arcAngle);
curValue +=
slices[i].value;
}
}
}
public class Main {
public static void main(String[]
argv) {
JFrame frame = new
JFrame();
frame.getContentPane().add(new MyComponent());
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Q 6. Explain different types of Layout Managers.
Ans :
LayoutManagers:
The LayoutManagers are
used to arrange components in a particular manner. LayoutManager is an
interface that is implemented by all the classes of layout managers. There are
following classes that represents the layout managers:
- java.awt.BorderLayout
- java.awt.FlowLayout
- java.awt.GridLayout
- java.awt.CardLayout
- java.awt.GridBagLayout
- javax.swing.BoxLayout
- javax.swing.GroupLayout
- javax.swing.ScrollPaneLayout
- javax.swing.SpringLayout etc.
here we will discuss
some of them
BorderLayout:
The BorderLayout is used
to arrange the components in five regions: north, south, east, west and center.
Each region (area) may contain one component only. It is the default layout of
frame or window. The BorderLayout provides five constants for each region:
- public static final int NORTH
- public static final int SOUTH
- public static final int EAST
- public static final int WEST
- public static final int CENTER
Constructors of BorderLayout class:
- BorderLayout(): creates
a border layout but with no gaps between the components.
- JBorderLayout(int hgap, int
vgap): creates a border layout
with the given horizontal and vertical gaps between the components.
GridLayout
Constructors of GridLayout class:
FlowLayout
Fields of FlowLayout
class:
Constructors of
FlowLayout class:
BoxLayout class:
Note: BoxLayout
class is found in javax.swing package.
Fields of BoxLayout
class:
Constructor of
BoxLayout class:
CardLayout class
Constructors of
CardLayout class:
Commonly used
methods of CardLayout class:
|
Q7. Write short
note on flowing.
a.) Event
delegation model
b.) Adapter Class
c.) Color Class in
Awt
e
Delegation
Event model
The
modern approach to handling events is based on the delegation event model. In
this model, an event is sent to component form which it originated. The
component registers a listener object with the program. The listener processes
the event and then returns.
Every
event has a corresponding listener interface that specifies the methods that
are required to handle the event. Event object are sent to registered
listeners. To enable a component to handle events, you must register an
appropriate listener for it.
Adapter Class in JAVA
Introduction
The Color class states colors in the
default sRGB color space or colors in arbitrary color spaces identified by a
ColorSpace.
Class declaration
Following is the declaration for java.awt.Color class:
public class Color
extends
Object
implements Paint, Serializable
Field
Following are the fields for java.awt.geom.Arc2D class:
·
static
Color black --
The color black.
·
static
Color BLACK --
The color black.
·
static
Color blue --
The color blue.
·
static
Color BLUE --
The color blue.
·
static
Color cyan --
The color cyan.
·
static
Color CYAN --
The color cyan.
·
static
Color DARK_GRAY --
The color dark gray.
·
static
Color darkGray --
The color dark gray.
·
static
Color gray --
The color gray.
·
static
Color GRAY --
The color gray.
·
static
Color green --
The color green.
·
static
Color GREEN --
The color green.
·
static
Color LIGHT_GRAY --
The color light gray.
·
static
Color lightGray --
The color light gray.
·
static
Color magenta --
The color magenta.
·
static
Color MAGENTA --
The color magenta.
·
static
Color orange --
The color orange.
·
static
Color ORANGE --
The color orange.
·
static
Color pink --
The color pink.
·
static
Color PINK --
The color pink.
·
static
Color red --
The color red.
·
static
Color RED --
The color red.
·
static
Color white --
The color white.
·
static
Color WHITE --
The color white.
·
static
Color yellow --
The color yellow.
·
static
Color YELLOW --
The color yellow.
Class constructors
S.N.
|
Constructor & Description
|
1
|
Color(ColorSpace cspace, float[] components, float alpha)
Creates a color in the specified ColorSpace with the color
components specified in the float array and the specified alpha.
|
2
|
Color(float r, float g, float b)
Creates an opaque sRGB color with the specified red, green, and
blue values in the range (0.0 - 1.0).
|
3
|
Color(float r, float g, float b, float a)
Creates an sRGB color with the specified red, green, blue, and
alpha values in the range (0.0 - 1.0).
|
4
|
Color(int rgb)
Creates an opaque sRGB color with the specified combined RGB
value consisting of the red component in bits 16-23, the green component in
bits 8-15, and the blue component in bits 0-7.
|
5
|
Color(int rgba, boolean hasalpha)
Creates an sRGB color with the specified combined RGBA value
consisting of the alpha component in bits 24-31, the red component in bits
16-23, the green component in bits 8-15, and the blue component in bits 0-7.
|
6
|
Color(int r, int g, int b)
Creates an opaque sRGB color with the specified red, green, and
blue values in the range (0 - 255).
|
7
|
Color(int r, int g, int b, int a)
Creates an sRGB color with the specified red, green, blue, and
alpha values in the range (0 - 255).
|
Class methods
S.N.
|
Method & Description
|
1
|
Color brighter()
Creates a new Color that is a brighter version of this Color.
|
2
|
PaintContext createContext(ColorModel cm, Rectangle r,
Rectangle2D r2d, AffineTransform xform, RenderingHints hints)
Creates and returns a PaintContext used to generate a solid
color pattern.
|
3
|
Color darker()
Creates a new Color that is a darker version of this Color.
|
4
|
static Color decode(String nm)
Converts a String to an integer and returns the specified opaque
Color.
|
5
|
boolean equals(Object obj)
Determines whether another object is equal to this Color.
|
6
|
int getAlpha()
Returns the alpha component in the range 0-255.
|
7
|
int getBlue()
Returns the blue component in the range 0-255 in the default
sRGB space.
|
8
|
static Color getColor(String nm)
Finds a color in the system properties.
|
9
|
static Color getColor(String nm, Color v)
Finds a color in the system properties.
|
10
|
static Color getColor(String nm, int v)
Finds a color in the system properties.
|
11
|
float[] getColorComponents(ColorSpace cspace, float[] compArray)
Returns a float array containing only the color components of
the Color in the ColorSpace specified by the cspace parameter.
|
12
|
float[] getColorComponents(float[] compArray)
Returns a float array containing only the color components of
the Color, in the ColorSpace of the Color.
|
13
|
ColorSpace getColorSpace()
Returns the ColorSpace of this Color.
|
14
|
float[] getComponents(ColorSpace cspace, float[] compArray)
Returns a float array containing the color and alpha components
of the Color, in the ColorSpace specified by the cspace parameter.
|
15
|
float[] getComponents(float[] compArray)
Returns a float array containing the color and alpha components
of the Color, in the ColorSpace of the Color.
|
16
|
int getGreen()
Returns the green component in the range 0-255 in the default
sRGB space.
|
17
|
static Color getHSBColor(float h, float s, float b)
Creates a Color object based on the specified values for the HSB
color model.
|
18
|
int getRed()
Returns the red component in the range 0-255 in the default sRGB
space.
|
19
|
int getRGB()
Returns the RGB value representing the color in the default sRGB
ColorModel.
|
20
|
float[] getRGBColorComponents(float[] compArray)
Returns a float array containing only the color components of
the Color, in the default sRGB color space.
|
21
|
float[] getRGBComponents(float[] compArray)
Returns a float array containing the color and alpha components
of the Color, as represented in the default sRGB color space.
|
22
|
int getTransparency()
Returns the transparency mode for this Color.
|
23
|
int hashCode()
Computes the hash code for this Color.
|
24
|
static int HSBtoRGB(float hue, float saturation, float
brightness)
Converts the components of a color, as specified by the HSB
model, to an equivalent set of values for the default RGB model.
|
25
|
static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals)
Converts the components of a color, as specified by the default
RGB model, to an equivalent set of values for hue, saturation, and brightness
that are the three components of the HSB model.
|
26
|
String toString()
Returns a string representation of this Color.
|
Methods inherited
This class inherits methods from the
following classes:
·
java.lang.Object
Color Example
Create the following java program using
any editor of your choice in say D:/ > AWT > com >
tutorialspoint > gui >
AWTGraphicsDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class AWTGraphicsDemo extends Frame {
public
AWTGraphicsDemo(){
super("Java AWT Examples");
prepareGUI();
}
public
static void main(String[] args){
AWTGraphicsDemo
awtGraphicsDemo = new AWTGraphicsDemo();
awtGraphicsDemo.setVisible(true);
}
private
void prepareGUI(){
setSize(400,400);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
@Override
public
void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Font plainFont = new Font("Serif", Font.PLAIN, 24);
g2.setFont(plainFont);
g2.setColor(Color.red);
g2.drawString("Welcome to TutorialsPoint", 50, 70);
g2.setColor(Color.GRAY);
g2.drawString("Welcome to TutorialsPoint", 50, 120);
}
}
Compile the program using command prompt.
Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java
If no error comes that means compilation
is successful. Run the program using following command.
Q 1. what do you meany by java collection?
what is the benifit of using java collection framework?
Q 2. Explain LinkedList
class in java collection.
Q 3. What do you mean by
collection class in java? explain in brief
Q 4.
Q 5. write short note on
following.
a) itrator
b) Collector
c) Vector
d) hashtable
e) Treemap
Ans 1:
Collections in Java
A collection —
sometimes called a container — is simply an object that groups multiple
elements into a single unit. Collections are used to store, retrieve,
manipulate, and communicate aggregate data. Typically, they represent data
items that form a natural group, such as a poker hand (a collection of cards),
a mail folder (a collection of letters), or a telephone directory (a mapping of
names to phone numbers). If you have used the Java programming language — or
just about any other programming language — you are already familiar with
collections.
What Is a Collections Framework?
A collections
framework is a unified architecture for representing and manipulating
collections. All collections frameworks contain the following:
Interfaces: These are abstract data types that
represent collections. Interfaces allow collections to be manipulated
independently of the details of their representation. In object-oriented
languages, interfaces generally form a hierarchy.
Implementations: These are the concrete
implementations of the collection interfaces. In essence, they are reusable
data structures.
Algorithms: These are the methods that perform
useful computations, such as searching and sorting, on objects that implement
collection interfaces. The algorithms are said to be polymorphic:
that is, the same method can be used on many different implementations of the
appropriate collection interface. In essence, algorithms are reusable
functionality.
Apart
from the Java Collections Framework, the best-known examples of collections
frameworks are the C++ Standard Template Library (STL) and Smalltalk's
collection hierarchy. Historically, collections frameworks have been quite
complex, which gave them a reputation for having a steep learning curve. We
believe that the Java Collections Framework breaks with this tradition, as you
will learn for yourself in this chapter.
Benefits of the Java Collections
Framework
The
Java Collections Framework provides the following benefits:
- Reduces
programming effort: By
providing useful data structures and algorithms, the Collections Framework
frees you to concentrate on the important parts of your program rather
than on the low-level "plumbing" required to make it work. By
facilitating interoperability among unrelated APIs, the Java Collections
Framework frees you from writing adapter objects or conversion code to
connect APIs.
- Increases
program speed and quality: This Collections Framework provides
high-performance, high-quality implementations of useful data structures
and algorithms. The various implementations of each interface are
interchangeable, so programs can be easily tuned by switching collection
implementations. Because you're freed from the drudgery of writing your
own data structures, you'll have more time to devote to improving
programs' quality and performance.
- Allows
interoperability among unrelated APIs: The collection interfaces are the vernacular by
which APIs pass collections back and forth. If my network administration
API furnishes a collection of node names and if your GUI toolkit expects a
collection of column headings, our APIs will interoperate seamlessly, even
though they were written independently.
- Reduces
effort to learn and to use new APIs: Many APIs naturally take collections on input and
furnish them as output. In the past, each such API had a small sub-API
devoted to manipulating its collections. There was little consistency
among these ad hoc collections sub-APIs, so you had to learn each one from
scratch, and it was easy to make mistakes when using them. With the advent
of standard collection interfaces, the problem went away.
- Reduces
effort to design new APIs: This is the flip side of the previous advantage.
Designers and implementers don't have to reinvent the wheel each time they
create an API that relies on collections; instead, they can use standard
collection interfaces.
- Fosters
software reuse: New
data structures that conform to the standard collection interfaces are by
nature reusable. The same goes for new algorithms that operate on objects
that implement these interfaces.
The Collection
Interfaces
The
collections framework defines several interfaces. This section provides an
overview of each interface −
Sr.No.
|
Interface &
Description
|
1
|
This enables you to work with groups of objects; it is at the
top of the collections hierarchy.
|
2
|
This extends Collection and an instance of List
stores an ordered collection of elements.
|
3
|
This extends Collection to handle sets, which must contain
unique elements.
|
4
|
This extends Set to handle sorted sets.
|
5
|
This maps unique keys to values.
|
6
|
This describes an element (a key/value pair) in a map. This is
an inner class of Map.
|
7
|
This extends Map so that the keys are maintained in an ascending
order.
|
8
|
This is legacy interface defines the methods by which you can
enumerate (obtain one at a time) the elements in a collection of objects.
This legacy interface has been superceded by Iterator.
|
Answer
2:Java - The
LinkedList Class
The LinkedList class extends
AbstractSequentialList and implements the List interface. It provides a
linked-list data structure.
Following are the constructors supported
by the LinkedList class.
Sr.No.
|
Constructor &
Description
|
1
|
LinkedList( )
This constructor builds an empty linked list.
|
2
|
LnkedList(Collection c)
This constructor builds a linked list that is initialized with
the elements of the collection c.
|
Apart from the methods inherited from its
parent classes, LinkedList defines following methods −
Sr.No.
|
Method &
Description
|
1
|
void add(int index, Object element)
Inserts the specified element at the specified position index in
this list. Throws IndexOutOfBoundsException if the specified index is out of
range (index < 0 || index > size()).
|
2
|
boolean add(Object o)
Appends the specified element to the end of this list.
|
3
|
boolean addAll(Collection c)
Appends all of the elements in the specified collection to the
end of this list, in the order that they are returned by the specified
collection's iterator. Throws NullPointerException if the specified
collection is null.
|
4
|
boolean addAll(int index, Collection c)
Inserts all of the elements in the specified collection into
this list, starting at the specified position. Throws NullPointerException if
the specified collection is null.
|
5
|
void addFirst(Object o)
Inserts the given element at the beginning of this list.
|
6
|
void addLast(Object o)
Appends the given element to the end of this list.
|
7
|
void clear()
Removes all of the elements from this list.
|
8
|
Object clone()
Returns a shallow copy of this LinkedList.
|
9
|
boolean contains(Object o)
Returns true if this list contains the specified element. More
formally, returns true if and only if this list contains at least one element
e such that (o==null ? e==null : o.equals(e)).
|
10
|
Object get(int index)
Returns the element at the specified position in this list.
Throws IndexOutOfBoundsException if the specified index is out of range
(index < 0 || index >= size()).
|
11
|
Object getFirst()
Returns the first element in this list. Throws
NoSuchElementException if this list is empty.
|
12
|
Object getLast()
Returns the last element in this list. Throws
NoSuchElementException if this list is empty.
|
13
|
int indexOf(Object o)
Returns the index in this list of the first occurrence of the
specified element, or -1 if the list does not contain this element.
|
14
|
int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the
specified element, or -1 if the list does not contain this element.
|
15
|
ListIterator listIterator(int index)
Returns a list-iterator of the elements in this list (in proper
sequence), starting at the specified position in the list. Throws IndexOutOfBoundsException
if the specified index is out of range (index < 0 || index >= size()).
|
16
|
Object remove(int index)
Removes the element at the specified position in this list.
Throws NoSuchElementException if this list is empty.
|
17
|
boolean remove(Object o)
Removes the first occurrence of the specified element in this
list. Throws NoSuchElementException if this list is empty. Throws
IndexOutOfBoundsException if the specified index is out of range (index <
0 || index >= size()).
|
18
|
Object removeFirst()
Removes and returns the first element from this list. Throws
NoSuchElementException if this list is empty.
|
19
|
Object removeLast()
Removes and returns the last element from this list. Throws
NoSuchElementException if this list is empty.
|
20
|
Object set(int index, Object element)
Replaces the element at the specified position in this list with
the specified element. Throws IndexOutOfBoundsException if the specified
index is out of range (index < 0 || index >= size()).
|
21
|
int size()
Returns the number of elements in this list.
|
22
|
Object[] toArray()
Returns an array containing all of the elements in this list in
the correct order. Throws NullPointerException if the specified array is
null.
|
23
|
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in
the correct order; the runtime type of the returned array is that of the
specified array.
|
Example
The following program illustrates several
of the methods supported by LinkedList −
import java.util.*;
public class LinkedListDemo {
public
static void main(String args[]) {
// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// remove elements from the linked list
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion:
"
+ ll);
// remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last:
"
+ ll);
// get and set a value
Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}
This will produce the following result −
Output
Original
contents of ll: [A, A2, F, B, D, E, C, Z]
Contents
of ll after deletion: [A, A2, D, E, C, Z]
ll
after deleting first and last: [A2, D, E, C]
ll
after change: [A2, D, E Changed, C]
Answer 3:
The Collection Classes
Java provides a set of standard collection
classes that implement Collection interfaces. Some of the classes provide full
implementations that can be used as-is and others are abstract class, providing
skeletal implementations that are used as starting points for creating concrete
collections.
The standard collection classes are summarized
in the following table −
Sr.No.
|
Class &
Description
|
1
|
AbstractCollection
Implements most of the Collection interface.
|
2
|
AbstractList
Extends AbstractCollection and implements most of the List
interface.
|
3
|
AbstractSequentialList
Extends AbstractList for use by a collection that uses
sequential rather than random access of its elements.
|
4
|
Implements a linked list by extending AbstractSequentialList.
|
5
|
Implements a dynamic array by extending AbstractList.
|
6
|
AbstractSet
Extends AbstractCollection and implements most of the Set
interface.
|
7
|
Extends AbstractSet for use with a hash table.
|
8
|
Extends HashSet to allow insertion-order iterations.
|
9
|
Implements a set stored in a tree. Extends AbstractSet.
|
10
|
AbstractMap
Implements most of the Map interface.
|
11
|
Extends AbstractMap to use a hash table.
|
12
|
Extends AbstractMap to use a tree.
|
13
|
Extends AbstractMap to use a hash table with weak keys.
|
14
|
Extends HashMap to allow insertion-order iterations.
|
15
|
Extends AbstractMap and uses reference equality when comparing
documents.
|
The AbstractCollection,
AbstractSet, AbstractList, AbstractSequentialList andAbstractMap classes
provide skeletal implementations of the core collection interfaces, to minimize
the effort required to implement them.
The following legacy classes defined by
java.util have been discussed in the previous chapter −
Sr.No.
|
Class &
Description
|
1
|
This implements a dynamic array. It is similar to ArrayList, but
with some differences.
|
2
|
Stack is a subclass of Vector that implements a standard
last-in, first-out stack.
|
3
|
Dictionary is an abstract class that represents a key/value
storage repository and operates much like Map.
|
4
|
Hashtable was part of the original java.util and is a concrete
implementation of a Dictionary.
|
5
|
Properties is a subclass of Hashtable. It is used to maintain
lists of values in which the key is a String and the value is also a String.
|
6
|
A BitSet class creates a special type of array that holds bit
values. This array can increase in size as needed.
|
Important questions for
internal examination
Total no of questions
5]
Seat no
|
04102016-501
BCA.(Semester V)
Examination ,2016
JAVA Programming
(2013 Pattern)
Time: 3 hour Maximum marks: 80
N.B. (i) All questions are
compulsory.
(ii) All questions carry equal marks.
Q1. Attempt the following ( any eight). [8*2=16]
(a)
State the purpose of Wrapper class.
(b)
Can we use super () and this () with in the same constructor
justify your answer.
(c)
What types of variable can we define in interface?
(d)
Can a finally block be executed without catch block?
Justify your answer.
(e)
List any 3 advantages of using applet.
(f)
List any 8 controls of awt.
(g)
List any 5 methods of collection interface.
(h)
“A try block must have a catch block “ state true or false justify your answer.
(i)
List the access specifiers supported by package.
(j)
What is the default layout of frame and panel?
(k)
List any 5 methos of vector class
(l)
List 3 constructor of HashTable class.
(m)
List any 5 methods of Collection interface.
(n)
How to print welcome message before main () is
executed?
Q2. Attempt the following (any four) [4*4=16]
(a)
Write steps of creating user defined package in
java.
(b)
Define
collection define any two classes used with collection.
(c)
Why we will use garbage collection in java? Justify your
answer.
(d)
How to
implement multiple inheritance in java?
(e)
Write a java program to demonstrate method
overloading.
(f)
Write a java program to create user defined
exception.
(g)
Write a java program to design a Login form using
swings.
(h)
Write a java program to demonstrate mouse events.
Or
(i)
Write a java program to demonstrate keyboard events.
Q3. Attempt the following (any four) [4*4=16]
(a)
Write a java program to accept n students name from
the user. Insert into ArrayLisy and display the contents of same ArrayList ,
also remove first and last element from the ArryList and display the result.
(b)
Explain any 5 methods of File class.
(c)
Explain any 5 methods of BufferedReader class.
(d)
Write 5 differences between interface and abstract
class.
(e)
What do you mean by Adapter class?
(f)
What is the different dialog available in java? Explain
any two in detail.
(g)
What are the Layout available in java? Explain Grid
Layout in detail.
(h)
Explain GroupBox class with example.
(i)
What is the difference between Array and ArrayList
in java?
Q4. Attempt the following (any four) [4*4=16]
(a)
Write a java program to copy contents of one file
say source.txt to destination.txt.
(b)
Write a java program to design Indian flag using
applet.
(c)
Write a java program to design human smily face in
java using applet.
(d)
Write a java program to design student registration
form using applet.
(e)
Explain life cycle of applet.
(f)
What do you mean by event delegation model in java?
(g)
Write a program to define an abstract “RoundShap” with one data member-radius and constant PI. Declare
abstract methods findArea() and findVolume. Define a sub class Sphere , and
calculate area & volume of Sphere.
Q5. Attempt the following (any four) [4*4=16]
(a)
Explain Inner and Outer Class with suitable example.
(b)
Explain any 6 components used in Swings.
(c)
Write short note on following
(1)
HashTable class
(2)
Vector class
(3)
LinkedList Class
(4)
ArryList Class
(5)
CharacterStream Class
(6)
ByteStream Class
(7)
Exception Types in java
(8)
OOPS Properties
(9)
Overriding in Java
(10)Container
Class
(11)StringBuffer
class
(12)Iterator
interface
(13)Collection
Interface
(14)ListIterator
interface
(15)Map
interface.
d).State the difference between exception and error.
(E) can an abstract class declared as final? Justify
your answer.