Download Java UNIT-1-2

Document related concepts
no text concepts found
Transcript
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Q1: What is Java? Explain Java features in detail.
Q1: Any two features of Java.
Q1: Explain Java Buzzwords or Features.
Q1: Why Java is so popular?
Ans: Java is a programming language that is exclusively Object Oriented created by a team of
programmers at sun Microsystems in 1991.Their original goal was to develop a language that could be
used to write software for different consumer electronic devices such as TVs, VCRs and such electronics
machines.
It has full GUI support, full network support and it is platform independent.
It is case sensitive language.
This language was initially called “Oak” by James Gosling but renamed “Java” at 1995.
In java any program writes in notepad this is called source code. And the program run on the dos prompt
this is called object code.
In java programming the class name and program name is same. In java the first character of class name is
capital.
For example: class name is “Pgi” then file name will be “Pgi.java”
This program compiles & run.
Compile= javac Pgi.java
Run = java Pgi
Feature of java
1.
2.
3.
4.
5.
6.
7.
8.
9.
Java is object oriented programming language.
Java is platform independent.
Java has byte code.
Java has interpreter.
multithreading
distributed networking
Security provides.
Portable
High performance
Object Oriented
to be an Object Oriented language, any language must follow at least the four characteristics.
 Inheritance : It is the process of creating the new classes and using the behavior of the existing
classes by extending them just to reuse the existing code and adding the additional features as
needed.
 Encapsulation: It is the mechanism of combining the information and providing the abstraction.
 Polymorphism: As the name suggest one name multiple form, Polymorphism is the way of
providing the different functionality by the
functions having the same name based on the signatures of the methods.
 Dynamic binding: Sometimes we don't have the knowledge of objects about their specific types
while writing our code. It is the way of providing the maximum functionality to a program about
the specific type at runtime.
Developed By: - Prof. Adnan Ahmad
Page 1
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important
key feature of java language that makes java as the most powerful language. Not even a single language is
Idle to this feature but java is closer to this feature. The programs written on one platform can run on any
platform provided the platform must have the JVM.
Byte Code
The byte code is the instruction that is not for any specific cpu. This byte code is design to be interpreted
by JVM (java virtual machine) and this byte code makes java platform independent.
Interpreted
we all know that Java is an interpreted language as well. With an interpreted language such as Java,
programs run directly from the source code.
The interpreter program reads the source code and translates it on the fly into computations. Thus, Java
as an interpreted language depends on an interpreter program.
Multithreaded
As we all know several features of Java like Secure, Robust, Portable, dynamic etc; you will be more
delighted to know another feature of Java which is Multithreaded.
Java is also a multithreaded programming language. Multithreading means a single program having
different threads executing independently at the same time. Multiple threads execute instructions
according to the program code in a process or a program. Multithreading works the similar way as
multiple processes run on one computer.
Distributed
The widely used protocols like HTTP and FTP are developed in java. Internet programmers can call
functions on these protocols and can get access the files from any remote machine on the internet rather
than writing codes on their local system.
Secure
Java does not use memory pointers explicitly. All the programs in java are run under an area known as the
sand box. Security manager determines the accessibility options of a class like reading and writing a file to
the local disk. Java uses the public key encryption system to allow the java applications to transmit over
the internet in the secure encrypted form. The byte code Verifier checks the classes after loading.
Portable
the feature Write-once-run-anywhere makes the java language portable provided that the system must
have interpreter for the JVM. Java also has the standard data size irrespective of operating system or the
processor. These features make the java as a portable language.
Performance
Java uses native code usage, and lightweight process called threads. In the beginning interpretation of
byte code resulted the performance slow but the advance version of JVM uses the adaptive and just in
time compilation technique that improves the performance.
Developed By: - Prof. Adnan Ahmad
Page 2
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Q2: Explain Byte Code and java virtual Machine.
Q2: What is Byte Code? Explain How Java is Platform Independent.
Q2: Why Java is Platform Independent. Explain work of JVM.
Ans:
In java
Compile
Interpreted
Source code --------------> byte code ----------------> object code
(Designed by jvm)
C/C++
Compile
Source code --------------> byte code
Byte code/JVM
As you know all programming language has two form source code and object code.
The source code is the textual version that is written using text editor like notepad,
Edit.
Object code is the executable form that is executed by computer.
Like any language java also start from source code. But different is that when
Java source code is compiled then instead of object code the java compiler produced an
object file that contains byte code.
The byte code is the instructions that are not for any specific cpu. These byte codes are design
to be interpreted by JVM (java virtual machine) and this byte code makes java platform
independent.
JVM(Java virtual machine):it is the runtime environment for java programs and it contains the
following :
1)class loader
2)byte code verifier
3)JIT (Just In time) compiler and interpreter
java is a platform independent language which means it can be operated in
any operating system.
JVM is an abstract computing machine like any other real computing machine which interprets the byte
code (.class file which contains virtual machine instructions) to a machine dependent native code. The
output of JVM i.e. the native code contains low level instructions which are easily understandable by the
micro processors which process the native code to give the desire output.
Compiler converts all program whole at same time. While interpreter convert program line by line.
Developed By: - Prof. Adnan Ahmad
Page 3
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Q3: How many different types of programs create in Java? Explain with example.
Q3: What is difference between application and applet.
Q3: What is basic structure of Java?
Q3: Why Java main () method is public and static?
Q3: Why Java main () method has one argument?
Ans: Application and Applets=there are two types of program that can built in java.
1. Application
2. Applet
Application can be directly executed by JVM. Applet require web browser for execution. The browse
includes a jvm and also provides an execution environment for the applet. It is also possible a tool known
as appletviewer to run an applet. This utility includes in JDK and is used to test applet.
Basic Structure:
class Test
{
public static void main(String args[])
{
System.out.println(“hello”);
}
}
The java main () method has public and static because in java main () method is accessed outside the class
so it is public. And the main () method is invoked direct by class not object so it is static.
The main () method has one argument know as array of String object args. It is used of command line.
means enter the value from dos prompt.
The println() method is static because it is invoked direct by class System for compile.
Q4: Any two primitive data types.
Q4: Explain the difference between the variable of primitive data types and reference data
type with java code.
Ans:
Primitive data types:
Type
1. character
2. Boolean
3. byte
4. short
5. integer
Description
16-bit character
true/false value
8-bit integer number
16-bit integer number
32-bit integer number
Developed By: - Prof. Adnan Ahmad
keyword
rang
char
boolean
byte
-128 to 127
short
-32768 to 32767
int -2147 483 648 To 2147 483 647
Page 4
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
6. long
7. float
8. double
Unit: - 1, 2, 3
64-bit integer number
long
Rang – (-9223 372 036 854 775 808 to 9223 372 036 854 775 807)
32-bit floating point
float 1.4e-045 to 3.4e+038
64-bit floating point
double 4.9e-324 to 1.8e+038
The primitive data types are predefined data types, which always hold the value of the same data
type, and the values of a primitive data type don't share the state with other primitive values. These data
types are named by a reserved keyword in Java programming language.
There are eight primitive data types supported by Java programming language:
For Example:
byte, short, int, long, float, double, boolean, char
Reference Data Type Means
In Java a reference data type is a variable that can contain the reference or an address of dynamically
created object. This type of data type is not predefined like primitive data type. The reference data types
are arrays, classes and interfaces that are made and handle according to a programmer in a java
program which can hold the three kinds of values as:
array type
// Points to an array instance
class type
// Points to an object or a class instance
interface type
// Points to an object and a method, which is implemented to
the corresponding interface
Developed By: - Prof. Adnan Ahmad
Page 5
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Class Type:
As you know that Java is an object-oriented programming language where an object is a variable,
associated with methods that is described by a class. The name of a class is treated as a type in a java
program, so that you can declare a variable of an object-type, and a method which can be called using that
object- type variable.
For example:
class Fruit {
fColor(){....}
fSize(){....}
};Fruit mango;
Fruit banana;
...
In the given example the Fruit is a class that has the reference variables as mango & banana through
which we can call
the behaviors associated with that class as mango.fColor(); within the main method of the super class.
Array Type:
An array is a special kind of object that contains values called elements. The java array enables the user to
store the values of the same type in contiguous memory allocations. The elements in an array are
identified by an integer index which initially starts from 0 and ends with one less than number of elements
available in the array. All elements of an array must contain the same type of value i.e. if an array is a type
of integer then all the elements must be of integer type. It is a reference data type because the class
named as Array implicitly extends java.lang.Object. The syntax of declaring the array is shown as:
DataType [] variable1, variable2,
.......variableN;
DataType [] variable = new DataType
[ArraySize];
DataType [] variable = {item 1, item
2,...item n};
For example:
int [] a = new int [10];
String [] b = {"reference","data",
"type"};
Interface Type:
Java provides an another kind of reference data type or a mechanism to support multiple inheritance
feature called an interface. The name of an interface can be used to specify the type of a reference. A
value is not allowed to be assign to a variable declared using an interface type until the object implements
the specified interface.
When a class declaration implements an interface, that class inherits all of the variables and methods
declared in that interface. So the implementations for all of the methods declared in the interface must be
provided by that class. For example:
Runnable r;
r = new Thread();
Developed By: - Prof. Adnan Ahmad
Page 6
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Q5: Explain JDK and Java class Library.
Ans:
JDK: java development kitt contains what you need to start building and executing java
application and applets.it can be downloaded for free from sun microsystem web site.
Follow the instruction to install the JDK on your machine.it contains a java virtual machine for
your platform and the java classs library.also include a set of tools including
compiler,interpreter and applet viewer.
Java class library: java define a rich set of class libraries.these provide a large number of
standard classes and method.that any java program can use.these library provide for
i/o,mathematical operation,networking,event handling and many other capabilities.
Some of the most commonly used class library and their function is known as package.a
package is the collection of classes.
Q6: Explain Polymorphism, Inheritance and Encapsulation with example.
Q6: Explain Inheritance with example.
Q6: What is three principle or rules of Object Oriented programming?
Ans:
Three principle of object oriented programming
1.Inheritnce
2.polymorphisam
3. Encapsulation
Inheritance:
“ The property of (data and method) super class is reused by sub class is knows as inheritance.”
Super class
The property of that class is reused by sub class is called super class. It is also known as father class /base
class.
Sub class
The property of super class is reused by that class is known as sub class. It is also known as son class /
derives class.
To create sub class from super class the keyword “extends” is used.
Syntax:
Class A
{
}
class B extends A
{
}
Developed By: - Prof. Adnan Ahmad
Page 7
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Here class A is super class and class B is sub class.
class Father
{
}
class son:public Father(c++)
class son extends Father(java)
extends is the keyword which is used when subclass is created. extends means all property (method,data)
of superclass is used by subclass.
class Father
{
}
class son extends Father
{
}
class Inherit
{
public static void main(String args[])
{
Father f=new Father();
Father f=new Son();
son s=new son();
// son s=new father(); generate error because son class can not reference to its super class mean object
of sub class can not allocate memory of its super class
}
}
Example:
class A
{
int i;
Integer j;
}
class B extends A
{
String s;
StringBuffer sb;
}
class Inherit
{
Developed By: - Prof. Adnan Ahmad
Page 8
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
public static void main(String args[])
{
B b=new B();
b.i=30;
b.j=new Integer(20);
b.s="c_dac";
b.sb=new StringBuffer("computer");
System.out.println("i="+b.i);
System.out.println("j="+b.j);
System.out.println("s="+b.s);
System.out.println("sb="+b.sb);
}
}
Types of Inheritance
1. Single inheritance
class A
{
}
class B extends A
{
}
2. Multilevel inheritance
class A
{
}
class B extends A
{
}
class C extends B
{
}
Developed By: - Prof. Adnan Ahmad
Page 9
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
3. Hierarchical inheritance
class A
{
}
class B extends A
{
}
class C extends A
{
}
4.Multiple Inheritance : Java does not support multiple inheritance but using interface it can do.
class A
{
}
class B
{
}
class C extends A,B
{
}
Polymorphisam:
Poly = many
morphisam= shape
“One interface and multiple implementation” means one function is used in different shape. For
example class Shape is used in different form.
Such as rectangle,circle,oval,square etc.
Example:
Class Father
{
void van(int ,int)
{}
}
class Son extends Father
{
void van(int,int,int,int)
{}
}
Developed By: - Prof. Adnan Ahmad
Page 10
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Encapsulation:
En=surrounded
capsule=cover
Encapsulation is the mechanism in which data is written with code. We may think what is code. The code
is providing a protective cover of data from which other software or other class cannot use this data.
Q-7: Explain Class Loader in Java.
Ans:
Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name
in a class that is already running in the JVM. So, how is the very first class loaded? The very first class is
especially loaded with the help of static main( ) method declared in your class. All the subsequently loaded
classes are loaded by the classes, which are already loaded and running. A class loader creates a
namespace. All JVMs include at least one class loader that is embedded within the JVM called the
primordial (or bootstrap) class loader.
Q8: What is Array? How to declare and initialize array?
Q8: Explain multi dimensional Array.
Q8: Explain any one reference data type with example.
Ans:
Array: array is the collection of variable of same data type.
in java to create and initialize array three step include
1. Declaration: to create new array is known as declaration.
Syntax:
datatype array_name[];
int a[];
Example for 2-D Array:
Int a[][];
2. Allocation: to allocate memory of array into disk is known as allocation for this purpose we used a
keyword "new". Which is allocate memory of array.
Syntax:
array_name=new datatype[size];
a=new int[4];
Example for 2-D Array:
a=new int[2][2];
3. Initialization: to assign or input value into array known as initialization.
a[0]=12;
a[1]=34;
...........
a[3]=45;
Example for 2-D Array:
a[0][0]=23;
a[0][1]=34;
Developed By: - Prof. Adnan Ahmad
Page 11
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
………..
a[1][1]=45;
Note1: declaration and allocation may be written in one step.
Syntax:
datatype array_name[]=new datatype[size];
int a[]=new int[4];
Example for 2-D Array:
Int a[][]=new int[2][2];
Note2: declaration allocation and initialization may be written in one step.
Syntax:
datatype array_name[]={list of value};
int a[]={3,5,6,7,8};
Example:
class Array
{
public static void main(String args[])
{
int a[]={12,34,56,78,96},i;
//declaration+allocation+initialization
System.out.println("length="+a.length);
for(i=0;i<5;i++)
{
System.out.println("a["+i+"]="+a[i]);
}
}
}
Example for 2-D Array:
Int a[][]={{list of value for first row},{list of value for second row}};
Example:
class Array2
{
public static void main(String args[])
{
int a[][]={{3,8,5},{1,2,3},{7,3,5}};
int r,c;
System.out.println("size of row="+a.length);
System.out.println("size of coloumn="+a[0].length);
for(r=0;r<3;r++)
{
for(c=0;c<3;c++)
{
System.out.print(" "+a[r][c]);
}
System.out.print("\n");
}
}}
Developed By: - Prof. Adnan Ahmad
Page 12
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Note3: to find the length of array we used following command
Syntax:
array_name.length;
a.length;
Note4: In 2-D array
Array_name.length; (return number of row)
Array_name[index].length; (return total element in given index)
Q9: What is command line? Explain with example.
Ans:
command line
class Array
{
public static void main(String args[])
{
System.out.println("length="+args.length);
System.out.println("args[0]="+args[0]);
System.out.println("args[1]="+args[1]);
}
}
As you know all java program has a main () method and this method has one argument known
as array of string object .this argument is used when user enter the value from command line
(means dos prompt) then this value is stored in this array. To find individually value from
command line we used ars[0],args[1],args[2]... etc.
And find the length we used args.length.
Q10: Explain class and object in Java.
Ans:
Class
Class is user define data type.
Class is collection of object.
Class is a blueprint.
A class is a template from which objects are created.
A class is declared by use of the class keyword. Classes may contain data and code both.
The general form of class definition:
Syntax:
Class cls_name
{
Type instance variable1;
Type instance variable2;
Developed By: - Prof. Adnan Ahmad
Page 13
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Type methodname1(parameter list)
{
Method body;
}
Type methodname2(parameter list)
{
Method body;
}
}
Example:
class Person
{
int age;
String name;
float height;
}
class General1
{
public static void main(String args[])
{
Person ram=new Person();
ram.age=25;
ram.name="Ramesh kumar";
ram.height=5.7f;
System.out.println("age="+ram.age);
System.out.println("name="+ram.name);
System.out.println("height="+ram.height);
}
}
Object
Object is real entity world. Object is variable/instance of class. Object is allocate memory of two items.
1. State
2. Behavior
State is indicate set of variable
Behavior is indicate set of function.
Syntax:
Class_name obj_name=new class_name();
Here “new” is a keyword which is used to allocate memory of object
Example:
Person ram=new ram();
Here “person” is the class and “ram” is the object of person class.
Developed By: - Prof. Adnan Ahmad
Page 14
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Q11: Explain Garbage collection and finalize method.
Ans: Objects are dynamically allocated by using the new operator. In some language like C++, dynamically
allocated object must be manually released by use of a delete operator.
Java handles deallocation for you automatically. The technique that accomplishes is called garbage
collection.
Finalize() method:
Sometimes an object will need to perform some action when it is destroyed. To handle such situation, Java
provides a mechanism called Finalization.
Finalize is a method which is work with garbage collation. This method is useful for indentified that
System.gc is worked in your program for free the memory which is not long reference.
Protected void finalize()
{
…………….
…………….
}
The java run time calls that method whenever it is about to recycle an object of that class.
Q12: Discuss “instanceof” operator in brief.
Q12: Explain “instanceof” keyword with example.
Ans:
instanceof is a keyword.
It checks if an object reference is an instance of a type, and returns a boolean value;
The <object-reference> instanceof Object will return true for all non-null object references, since all Java
objects are inherited from Object. instanceof will always return false if <object-reference> is null.
Syntax:
<object-reference> instanceof typeName
Example:
// Demonstrate instanceof operator.
class A {
int i, j;
}
class B {
int i, j;
}
class C extends A {
int k;
}
class D extends A {
int k;
}
class InstanceOf {
public static void main(String args[]) {
A a = new A();
Developed By: - Prof. Adnan Ahmad
Page 15
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
B b = new B();
C c = new C();
D d = new D();
if(a instanceof A)
System.out.println("a is instance of A");
if(b instanceof B)
System.out.println("b is instance of B");
if(c instanceof C)
System.out.println("c is instance of C");
if(c instanceof A)
System.out.println("c can be cast to A");
if(a instanceof C)
System.out.println("a can be cast to C");
System.out.println();
// compare types of derived types
A ob;
ob = d; // A reference to d
System.out.println("ob now refers to d");
if(ob instanceof D)
System.out.println("ob is instance of D");
System.out.println();
ob = c; // A reference to c
System.out.println("ob now refers to c");
if(ob instanceof D)
System.out.println("ob can be cast to D");
else
System.out.println("ob cannot be cast to D");
if(ob instanceof A)
System.out.println("ob can be cast to A");
- 230 System.out.println();
// all objects can be cast to Object
if(a instanceof Object)
System.out.println("a may be cast to Object");
if(b instanceof Object)
System.out.println("b may be cast to Object");
if(c instanceof Object)
System.out.println("c may be cast to Object");
if(d instanceof Object)
System.out.println("d may be cast to Object");
}
}
Developed By: - Prof. Adnan Ahmad
Page 16
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Q13: What is Wrapper class? Explain any one wrapper class with example.
Q13: Explain Integer class with example.
Ans:
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
float
int
java.lang.Double
java.lang.Float
java.lang.Integer
long
java.lang.Long
short
java.lang.Short
void
java.lang.Void
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.
Developed By: - Prof. Adnan Ahmad
Page 17
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
8. set(int, Object): Learn to replace an element at the position specified by a index value.
Example:
import java.util.*;
public class VecAdd{
public static void main(String argv[]){
Vector v = new Vector();
v.add(0,new Integer(10));
v.add(1,new Integer(20));
v.add(2,new Integer(30));
v.add(3,new Integer(40));
v.add(4,new Integer(50));
v.add(5,new Integer(60));
for(int i=0; i < v.size();i ++){
Integer iw =(Integer) v.get(i);
System.out.println(iw);
}
}
}
Integer class: Integer class is a wrapper class of int data type. Integer class encapsulate value of int
data type.
Integer class provide many types of method which are following.
Method
1. ValueOf(string)
2. intvalue()
3. Floatvalue()
4.doublevalue()
5. parseInt(String)
6. toBinaryString()
7. toHexString()
8. toOctString()
Description
To convert string value into integer
object.
To convert integer object to int variable.
To convert float object to float
variable.
To convert double object to double
variable.
To convert string to int variable.
To convert String to binary.
To convert String to hexanumber.
To convert String to octal Number.
Example:
class Integer1
{
public static void main(String args[])
{
String s="120";
Integer obj=Integer.valueOf(s); // int a=Integer.parseInt(s);
int a=obj.intValue();
Developed By: - Prof. Adnan Ahmad
Page 18
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
System.out.println("a="+a);
a=a+20;
System.out.println("a="+a);
}
}
Q14: Explain “java.lang” package.
Ans:
“java.lang” package has following classes
Boolean
The Boolean class wraps a value of the primitive type boolean in an object.
Byte
The Byte class wraps a value of primitive type byte in an object.
Class
Instances of the class Class represent classes and interfaces in a running Java application.
Compiler
The Compiler class is provided to support Java-to-native-code compilers and related
services.
Double
The Double class wraps a value of the primitive type double in an object.
Float
The Float class wraps a value of primitive type float in an object.
Integer
The Integer class wraps a value of the primitive type int in an object.
Long
The Long class wraps a value of the primitive type long in an object.
Math
The class Math contains methods for performing basic numeric operations such as the
elementary exponential, logarithm, square root, and trigonometric functions.
Object
Class Object is the root of the class hierarchy.
Package
Package objects contain version information about the implementation and specification of
a Java package.
Runtime
Every Java application has a single instance of class Runtime that allows the application to
interface with the environment in which the application is running.
String
The String class represents character strings.
StringBuffer A string buffer implements a mutable sequence of characters.
System
The System class contains several useful class fields and methods.
Thread
A thread is a thread of execution in a program.
Throwable
The Throwable class is the superclass of all errors and exceptions in the Java language.
“java.lang” package has following interfaces
CharSequence
A CharSequence is a readable sequence of characters.
Cloneable
A class implements the Cloneable interface to indicate to the Object.clone() method
Developed By: - Prof. Adnan Ahmad
Page 19
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
that it is legal for that method to make a field-for-field copy of instances of that class.
Comparable
This interface imposes a total ordering on the objects of each class that implements it.
Runnable
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread.
Q15: Difference between String and StringBuffer class.
Q15: Explain String, StringBuffer, StringBuilder? Also explain its method.
Q15: Explain how Strings are handled in Java.
Q15: Explain how StringBuffer is handled in Java
Q15: explain String Tokenizer class.
Ans:
String class:
It is an Object of constant with group of characters. It will not allow modifying as it is immutable. Every
modification creates a new String Object.
Creating string:
String s=null;
String s1=“Friend”;
String s2=new String(“Friend”);
String s3=s2;
String s4=new String(s2);
String s5=new String(char[ ], int, int);
String s6=new String(byte[ ], int, int);
• String1==String2
– compares references of two variables
• String1.equals(String2);
• String1.equalsIgnoreCase(String2);
– compares the values of two strings if equal returns true else returns false
•
•
•
•
•
•
•
•
•
•
•
methods:
String s1 = s.concat(String new)
int n = s.indexOf(char)
char c = s.charAt(int)
int n = s.length()
String s1 = s.replace(char old, char new)
String s1 = s.substring(int start, int end)
String s1 = s.trim()
byte[ ] b = s.getBytes()
char[ ] c = s.toCharArray()
String[ ] s1 = s.split(String delimiter)
StringBuffer class:
As you know the String class is the collection of character. When the value of string object is assign then
there is no way to change or modify these value.
Developed By: - Prof. Adnan Ahmad
Page 20
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
The StringBuffer class also a collection of character but it has some types method to modify the value.
Such as append() method, insert() method.
Stringbuffer class has three type of constructor.
1. StringBuffer()
2. StringBuffer(int n)
3. StringBuffer(String s)
The first type of constructor has no argument. Its buffer size is 16 character.
The second type of constructor has one int type argumenrt. In this constructor the size defined by user.
The third type of constructor has one argument Strig type And it also reserve 16 character.
The Total size = String.length+16 character.
The String Buffer class has following types of method.
1. append() -- To add String in right size.
2. insert(int p, String s) -- To add string into p position.
3. reverse() --- To print string into reverse order.
4. capacity() --- To return size of stringbuffer constructor.
5. length() ---- To return total no of character.
Example:
class Buffer1
{
public static void main(String args[])
{
StringBuffer sb3=new StringBuffer("cdac");
System.out.println("sb3="+sb3);
System.out.println("sb3.capacity="+sb3.capacity());
System.out.println("sb3.length="+sb3.length());
sb3.append(" computer");
System.out.println("sb3="+sb3);
System.out.println("sb3.capacity="+sb3.capacity());
System.out.println("sb3.length="+sb3.length());
}
}
Note – In append or insert method cannot greater than 16 characters add in buffer
constructor because this character is store in buffer constructor reserve capacity value and the buffer
constructor capacity is 16.
Difference between String,StringBuffer and StringBuilder:
The most important difference between String and StringBuffer/StringBuilder in java is that String object
is immutable whereas StringBuffer/StringBuilder objects are mutable.
String is immutable, its mean that the value stored in the String object cannot be changed.
StringBuffer/StringBuilder objects are mutable; we can make changes to the value stored in the object.
Developed By: - Prof. Adnan Ahmad
Page 21
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Finally, whats the difference between StringBuffer and StringBuilder?
StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization.
StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement
threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).
StringTokenizer class:
• An Object created on String to break a String into tokens.
Constructors
StringTokenizer(String str)
StringTokenizer(String str, String delim)
StringTokenizer(String str, String delim, boolean returnDelims)
while (st.hasMoreTokens())
{
println(st.nextToken());
}
Example: StringTokenizer st=new StringTokenizer("this is a test");
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
output:
this
is
a
test
Q16: Difference between static and instance variable with example.
Q16: Explain initialize block or static block and class initialize block with example.
Q16: Difference between static and local variable.
Q16: What is variable? How to declare and initialize variable in java?
Ans:
In java three type of variable
1. Instance variable (to call object through)
2. Static variable
3. Local variable ( Internal)
Instance variable:the data or variable of class are called instance variable.
Instance variable invoked by object(instance) of class.
“A variable is name of data type which is stored value of data type”. Variable is the basic unit of storage in
a java program.
A variable is defined by the combination of identifiers, a type and an optional initialize.
All variable have a scope, which defines their visibility and a life time.
All variable must be declared before they can be used. The basic form variable declaration and
initialization are following.
Declaration: when we create new variable then it is known as declaration.
Syntax: type identifier1, identifier2;
Developed By: - Prof. Adnan Ahmad
Page 22
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Int a,b; // here we declare two variable a and b.
Initialization: when we input or assign value into variable then it is known as initialization.
Syntax: identifier=value;
A=12; b=30;
//initialization
Example:
Class Box
{
Double width;
Double height;
Double depth;
}
Class BoxDemo
{
Public static void main(String args[][)
{
Box b=new Box();
Double vol;
b.width=10;
b.height=20;
b.depth=30;
vol=b.width*b.height*b.depth;
//here variable vol initialize as a dynamic.
System.out.println(“volume is:-“+vol);
}
}
Static variable:
Static variable is shared all object of its class. To created static variable the keyword static is used before
variable name.
Syntax:- Static data type var_name;
For example :- static int a;
The static variable has by default zero value when its class loads into memory. (Object create
to its class)
The static variable is direct related to class. A static variable is exit within class.
Example:
class Item
{
static int count;
String name;
Item(String name)
{
this.name=name;
count++;
Developed By: - Prof. Adnan Ahmad
Page 23
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
}
}
class Svar
Unit: - 1, 2, 3
{
public static void main(String args[])
{
Item i1=new Item("Apple");
System.out.println(i1.name+" "+i1.count);
Item i2=new Item("Mango");
System.out.println(i2.name+" "+i2.count);
Item i3=new Item("Graps");
System.out.println(i3.name+" "+i3.count);
}
}
Initializer block / static block:
You may define static block of statement to be executed when a class is loaded into memory.
This known as static initialization block.
Syntax:
Class cls_name
{
static
{
statement block;
}
}
1. Initialize block defined using the keyword static.
2. Executed once when the class loaded.
3. Can initialize only static data member of the class.
Example:
class X
{
static int array[];
static
{
array=new int[6];
for(int i=0;i<6;i++)
array[i]=i;
}
}
class Staticblock
Developed By: - Prof. Adnan Ahmad
Page 24
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
{
public static void main(String args[])
{
for(int i=0;i<6;i++)
System.out.println(X.array[i]);
}
}
we also create method as static to put the keyword static.
For example:
Static ret_type method()
{ // body of method;
}
Local variable:
The Local variable is declared inside the method. When method is invoked then local variable is
executed. The Local has no default value.
The name of local variable is same as static and instance variable but in that case the local variable
hides the static and instance variable.
The scope is the region (place) where the local variable is executed.
Example:
class A
{
int i;
//instance variable
static int j;
//static variable
void f()
{
int i=20;
//local variable
int j=30;
System.out.println("i="+i);
System.out.println("j="+j);
}
}
class Lvar
{
public static void main(String args[])
{
A a=new A();
a.i=23;
a.j=45;
System.out.println("i="+a.i);
System.out.println("j="+a.j);
a.f();
}}
Developed By: - Prof. Adnan Ahmad
Page 25
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Q17: what is type conversion and casting?
Q17: Explain widening conversion and narrowing conversion.
Q17: explain compatible type conversion and non-compatible type conversion.
Ans: Type Conversion and Casting:
It is common to assign a value of one type to a variable of another type.
There are two basic types of conversion. A widening conversion occurs when a value of one type is
converted to a wider type--one that has larger range of legal values. A widening conversion is also known
as compatible conversion.
Java performs widening conversion automatically.
If the two types are compatible then java will perform the conversion implicitly/automatically.
Example: you assign int to a double variable or char to int variable.
Narrowing conversion is another matter, however. A narrowing conversion occurs when a value is
converted to a type that is not wider than it. Narrowing conversion is not always safe.
Narrowing conversion is also known as incompatible conversion.
example: if you want to assign an int value to a byte variable then this conversion will not performed
automatically because byte has smaller size(-128 to 127) than int.
syntax: (target-type)value;
int i=13;
byte b=i; //compiler does not allow this
To create conversion between two incompatible types, you must use a cast. A cast is an explicitly type
conversion.
Syntax:
int i=13;
byte b=(byte)i; //force the int to be converted to a byte.
i=(int)13.456; //force this double to the int 13.
Example:
Class Conversion
{
Public static void main(String args[])
{
byte b; int i=257,double d=323.142;
System.out.println(“conversion int to byte:-“);
b=(byte)i;
System.out.println(“i and b:”+i+” “+b);
System.out.println(“conversion double to int:-“);
i=(int)d;
System.out.println(“d and i:”+d+” “+i);
System.out.println(“conversion double to byte:-“);
b=(byte)d;
System.out.println(“d and b:”+d+” “+b);
} }
Developed By: - Prof. Adnan Ahmad
Page 26
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Q18: Explain Constructor with Constructor Overloading and Method Overloading with Example.
Q18: Explain Constructor and method overloading.
Ans:
Constructor:
Constructor is a type of method .the class name and constructor name must be same. Constructor
has no return value. Constructor has any argument. Constructor has any argument. Constructor helps to
create object of particular class. When object is created then constructor called itself.
Each class has constructor.
Syntax:
Class cls_name
{
Constructor_name()
{
//body of constructor
}
}
Example:
class Point
{
double a;
double b;
Point(double x,double y)
{
a=x;
b=y;
}
}
class Construct
{
public static void main(String args[])
{
Point p=new Point(33,44);
System.out.println("a="+p.a);
System.out.println("b="+p.b);
}}
Costructor overloading:
When a class has more than one constructor and each constructor has same class name then it is known
as constructor overloading.
In constructor overloading each constructor has different argument. If argument is same then compiler
generates ambiguity.
Eaxmple:
class Point
{
double a;
double b;
Developed By: - Prof. Adnan Ahmad
Page 27
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
double c;
Point(double a)
{
this(a,0,0);
}
Point(double a,double b)
{
this(a,b,0);
}
Point(double a,double b,double c)
{
this.a=a;
this.b=b;
this.c=c;
}
}
class Construct1
{
public static void main(String args[])
{
Point p=new Point(12);
System.out.println("a="+p.a);
System.out.println("b="+p.b);
System.out.println("c="+p.c);
Point p1=new Point(10,20,30);
System.out.println("a="+p1.a);
System.out.println("b="+p1.b);
System.out.println("c="+p1.c);
}
}
Method overloading:
When a class has more than one method and each method has same name then it is known as method
overloading.
In method overloading each method has different argument. If argument is same then compiler generates
ambiguity.
Example:
class Point3d
{
int a;
int b;
int c;
Point3d(int a)
{
this(a,0,0);
Developed By: - Prof. Adnan Ahmad
Page 28
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
}
Point3d(int a,int b,int c)
{
this.a=a;
this.b=b;
this.c=c;
}
void f(int a)
{
this.a=a;
}
void f(int a,int b)
{
this.a=a;
this.b=b;
}
void f(int a,int b,int c)
{
this.a=a;
this.b=b;
this.c=c;
}
}
class Methodover
{
public static void main(String args[])
{
Point3d p=new Point3d(10,34,56);
p.f(12);
System.out.println("a="+p.a);
System.out.println("b="+p.b);
System.out.println("c="+p.c);
p.f(10,20,30);
System.out.println("a="+p.a);
System.out.println("b="+p.b);
System.out.println("c="+p.c);
}
}
Developed By: - Prof. Adnan Ahmad
Page 29
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Q19: Discuss use of super keyword.
Q19: Explain the uses of keyword "this" and "super" with code.
Q19: What is different between “this” and “super” keyword?
Q19: Explain the importance of super and this keyword with example.
Ans:
This keyword:
This keyword refered that object or variable which is currently executed.
Syntax : This.var_name;
The This keyword also invoked argument of one constructor to another constructor.
Syntax : This (args);
Example:
class Point
{
double a;
double b;
Point(double a,double b)
{
this.a=a;
this.b=b;
}
}
class Construct
{
public static void main(String args[])
{
Point p=new Point(33,44);
System.out.println("a="+p.a);
System.out.println("b="+p.b);
}}
Super keyword:
The super keyword is used when argument of super constructor or method is passed into
argument of sub constructor or method.
Syntax : super (args);
If user does not used super or this keyword then compiler automatically called super keyword.
The super keyword must be declare before this keyword if both keyword is used simultaneously.
Developed By: - Prof. Adnan Ahmad
Page 30
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Example:
class S
{
int s;
S(int s)
{
this.s=s;
}
}
class T extends S
{
int t;
T(int s,int t)
{
super(s);
this.t=t;
}
}
class U extends T
{
int u;
U(int s,int t,int u)
{
super(s,t);
this.u=u;
}
}
class Super1
{
public static void main(String args[])
{
U u1=new U(12,34,56);
System.out.println("s="+u1.s);
System.out.println("t="+u1.t);
System.out.println("u="+u1.u);
}
}
Q20: What is method overriding? Explain with example.
Q20: What is difference between method overloading and method overriding? Explain with
example.
Ans: Method Overriding
Method of super class is reused into sub class. Then it is known as method overriding.
In method overriding the argument of each method must be same. The method overriding occurs
in inheritance. The method overriding obeys the concept of polymorphism.
In method overriding the object of sub class hides the method of super class.
Developed By: - Prof. Adnan Ahmad
Page 31
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Example:
class A
{
void hello()
{
System.out.println("Hello A");
}
}
class B extends A
{
void hello()
{
System.out.println("hello B");
}
}
class C extends B
{
void hello()
{
System.out.println("hello C");
}
}
class Over
{
public static void main(String args[])
{
C c=new C();
c.hello();
}
}
Method Overloading:
Refer question no. 18
Q21: What is the need of declaring abstract class? Explain with code.
Q21: Explain different access modifier/specifier used in java.
Q21: If we are declaring variable, method, class as final. What will happen?
Q21: Explain abstract, final and public class modifier.
Q21: Explain final, native and synchronized method modifier.
Q21: Explain following modifiers: final , private and protected.
Ans:
Class Modifier:
Class has three modifiers
1. Abstract class = cannot be instantiated
Abstract class cannot create instance (object). The method of abstract class has empty
body. The method implemented into sub class of abstract class.
Developed By: - Prof. Adnan Ahmad
Page 32
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
The sub class of abstract class is known as concrete class.
Syntax:
Abstract class class_name
{
Type method_name()
{
//empty body
}
}
Example:
abstract class A
{
void set()
{
}
}
class B extends A
{
void set()
{
System.out.println("Hello B");
}
}
class Clmodifier
{
public static void main(String args[])
{
B b=new B();
b.set();
}
}
2. final class = cannot be extended. The final class cannot created sub class.
Syntax:
Final class class_name
{
//class member declaration
}
Note: final and abstract keyword cannot used simultaneously for same class. Because
abstract class needs subclass for implements of method while final class cannot create
subclass so abstract and final both keyword cannot used simultaneously.
3. public class = can be used any other class or program.
Syntax:
Public class class_name
{ // class member declaration }
Developed By: - Prof. Adnan Ahmad
Page 33
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
.
Constructor Modifier:
Constructor has three modifier
1. public = can be access any other class.
2. private = can be access same class.
3. protected = can be used by sub class or same package.
Example:
class Person
{
int age;
String name;
public Person(int age,String name)
//public constructor
{
this.age=age;
this.name=name;
}
private Person()
// private constructor
{
}
}
class Cmodifier
{
public static void main(String args[])
{
Person p=new Person(24,"Amit");
System.out.println("name="+p.name);
System.out.println("age="+p.age);
//Person p1=new Person();
//private constructor does not invoked outside the class
}
}
Variable Modifier:
Variable has five modifier
1. public = can be access any other class.
Syntax: public dataType varname;
2. private = can be access same class.
Syntax: private dataType varName;
3. protected = can be access sub class or same package.
Syntax: protected dataType varName;
4. static = it can be invoked class.
Syntax: static dataType varName;
Developed By: - Prof. Adnan Ahmad
Page 34
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
5. final = its value constant.
Syntax: final dataType varName=value;
Example:
class Person
{
final static int age=45;
}
class Vmodifier
{
public static void main(String args[])
{
System.out.println("age="+Person.age);
}
}
Method Modifier:
Method has seven modifier
1.
2.
3.
4.
public = can be accessed any other class.
private = can be accessed same class.
protected = can be accessed sub class or same package.
static = it can be invoked class.
Syntax:
Static type methodName()
{
// body of method
}
Example:
class Linear
{
static double solve(double a,double b)
{
return -b/a;
}
}
class Staticmethod
{
public static void main(String args[])
{
System.out.println(Linear.solve(2,2));
}
}
Developed By: - Prof. Adnan Ahmad
Page 35
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
5. final = final method cannot override
Syntax:
Final type methodName()
{
// body of method
}
6. Abstract = Abstract method has without body.
Syntax:
Abstract type methodName()
{
// body of method
}
Example:
// abstract class van
{
abstract int numwheel();
}
Class Truck extends van
{
int numwheel()
{
return 8;
}
}
Class car extends van
{
int numwheel()
{
return 4;
}
}
Class Modify
{
Car c= new Car();
System.out.println(c.numwheel());
Truck t=new Truck();
System.out.println(t.numwheel());
}
Note: In abstract method is use then the class must be abstract but the class is abstract then
the method does not abstract.
Developed By: - Prof. Adnan Ahmad
Page 36
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
7. native=the method is implemented in the machine code by the host cpu. It does not using
java bytecode.
Q22: Explain each of the following terms: Multiple Inheritance and Interface.
Q22: What is an interface? How it is important in Java? Explain with example.
Ans:
Interface:
Interface is the group of constant and method which are declare in the form of class.
Syntax:Access-sp interface interface-name
{
return-type method-name(parameter-list);
type final_varname=value;
{
where access-sp is either public or not used.
The keyword interface is indicating that the name is interface. Each interface variable is implicitly
public, static, and final. So variable modifier are not used.
Each interface method is implicitly public and abstract. So method modifier is not use.
A class can implement one or more interfaces when a class is created by interface then keyword
implements are used.
Syntax for implementing interface:
access class class_name [extends superclass][implements interface]
{
//class body
}
If a class implements an interface then it must implement all of the methods declared by that
interface otherwise the compiler issue error message.
When a sub class is created by more than one super class (two super classes) then it is known as multiple
inheritance. Java does not support multiple inheritances, so in java we cannot create directly multiple
inheritances but using interface it can be possible.
Example:
interface K
{
int a= 5;
int k1();
}
interface J
{
Boolean J1();
}
Developed By: - Prof. Adnan Ahmad
Page 37
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
interface L extends K,J
{
double L1();
}
// multiple inheritance using interface
Class B implements L
{
Public int K1();
{
Return 4;
}
Public boolean j1();
{
Return true;
}
Public double L1()
{
Return 5,6;
}
}
Class modify
{
Public static void main(String args[])
{
B b=new B();
System.out.println( B.a );
System.out.println( b.K1() );
System.out.println( b.J1() );
System.out.println(b.L1() );
}
}
In an interface the variable is by default public, static and the method is by default abstract and
public.
Q23: Explain Abstract class. Give four differences: abstract class Vs. interface
Ans:
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract
classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation (without braces, and followed
by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, the class itself must be declared abstract, as in:
Syntax:
public abstract class GraphicObject {
Developed By: - Prof. Adnan Ahmad
Page 38
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
// declare fields
// declare non-abstract methods
abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract
methods in its parent class. However, if it does not, the subclass must also be declared abstract.
Abstract Classes versus Interfaces:
Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain
implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial
implementation, leaving it to subclasses to complete the implementation. If an abstract class
contains only abstract method declarations, it should be declared as an interface instead.
Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they
are related to one another in any way. for example.
By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A
single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of
the abstract class), but also have some differences (the abstract methods).
An Abstract Class Example:
In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves, and many
other graphic objects. These objects all have certain states (for example: position, orientation, line color,
fill color) and behaviors (for example: moveTo, rotate, resize, draw) in common. Some of these states and
behaviors are the same for all graphic objects—for example: position, fill color, and moveTo. Others
require different implementations—for example, resize or draw. All GraphicObjects must know how to
draw or resize themselves; they just differ in how they do it. This is a perfect situation for an abstract
superclass. You can take advantage of the similarities and declare all the graphic objects to inherit from
the same abstract parent object—for example, GraphicObject, as shown in the following figure.
Classes Rectangle, Line, Bezier, and Circle inherit from GraphicObject
First, you declare an abstract class, GraphicObject, to provide member variables and methods that are
wholly shared by all subclasses, such as the current position and themoveTo method. GraphicObject also
declares abstract methods for methods, such as draw or resize, that need to be implemented by all
subclasses but must be implemented in different ways. The GraphicObject class can look something like
this:
Syntax:
abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
Developed By: - Prof. Adnan Ahmad
Page 39
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Each non-abstract subclass of GraphicObject, such as Circle and Rectangle, must provide implementations
for the draw and resize methods:
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
When an Abstract Class Implements an Interface:
In the section on Interfaces , it was noted that a class that implements an interface must implement all of
the interface's methods. It is possible, however, to define a class that does not implement all of the
interface methods, provided that the class is declared to be abstract. For example,
abstract class X implements Y {
// implements all but one method of Y
}
class XX extends X {
// implements the remaining method in Y
}
In this case, class X must be abstract because it does not fully implement Y, but class XX does, in fact,
implement Y.
Q24: What is Package? How it is useful in Java with example?
Q24: Explain the uses of the keywords "package" and "import".
Q24: What is use of import statement?
Ans: Package:
Package is the collection of class and interfaces. Package is a one type of namespace. If we have multiple
class and we want to put under in common namespace (package) so we can use package.
You can assign the classes and interface in a source file to a particular package by using a package
statement with the following syntax:
Syntax:
Package packageName;
Package is the directory it is same as header file of c.
Developed By: - Prof. Adnan Ahmad
Page 40
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Example:
Package p;
Class A
{
void a1()
{
System.out.println(“class A”);
}
}
package p;
class B
{
void b1()
{
System.out.println(“class B”);
}
}
To create package, in the install of java folder. The name of package is the same name as folder. This
folder is created in the bin folder.
In package any class and interface is used to any other main class program. For example:
Package p;
Class Test
{
public static void main(String args[]);
{
A a=new A();
a.a1();
B b=new B();
b.b1();
}
}
package
for compile= javac packageName\*.java
for run=
java package Name. file name
import: import is the keyword. It is used when class of one package accessed into another
package.
packages are stored in a hierarchical manner and are explicitly "imported" into new definition.
In the program more than one package use in different method in different package then this
package are include the following method.
Developed By: - Prof. Adnan Ahmad
Page 41
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Package p;
import q.*;
import r.*;
class Test
{
public static void main(String args[]);
{
A a=new A();
a.a1();
B b=new B();
b.b1();
}
}
Here A is the class of package q and B is the class of package r.
and a1() is the method of class A and b1() is the method of class B.
we create package and we import that package in any other program and use all that method
then we use the class and method outside of the package or another program therefore its method and
class must have a public modifier.
Q25: What is an Exception? How many different types of exception available in Java?
Q25: What is an Exception? How it can handle? Explain with example.
Q25: What is an Exception handling? Explain its components briefly.
Q25: Explain the uses of keywords "throw", "throws", "try", "catch" and "finally
Q25: Differentiate throw and throws.
Q25: Give four differences: catch Vs. finally
Q25: Define checked and unchecked exception.
Q25: How to create your own exception? Explain with example.
Ans:
Exception class:
Exception is a run time error. Exception is an object which is encounter when program is executed.
Exception class has three type of block try, catch and finally and managed five components which are.
1. Try: the try statement contains a block of statement enclosed by brace.
this is the code you want to monitor for exception. if a problem occur
during its execution an exception is thrown.
2. Catch: your code can catch this exception using catch and handle it in
some rational manner.
Developed By: - Prof. Adnan Ahmad
Page 42
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
3. Finally: any code that absolutely must be executed before a method
returns is put in a finally block.
4. Throw: system-generated exception is automatically thrown by the java
run-time system. To manually throw an exception, use the keyword
throw.
5. Throws: any exception that is thrown out of a method must be specified
by throws clause.
The syntax is following:try
{
//try block
}
catch(Exception type1 param1)
{
//catch block
}
catch (Exceptiontype2 param2)
{
//catch block
}
…………
…………
catch(ExceptiontypeN paramN)
{
//catch block
}
finally
{
//finally block
}
The try statement contains a block of statement enclosed by brace.this is the code you want to monitor
for exception.if aproblem occur during its execution an exception is thrown.
The try block is a sequence of catch block each of these begin with the catch keyword.an argument is
passed to each catch block.the argument is the exception object that contain information about the
problem.
Any remaining statement in the try block are not executed.the search is begin at the first catch block.if the
type of exception object matches the type of the catch block parameter.those statement are
executed.other wise remaining catch block are examined.
The finally block is an optional block.
Example:
Class Exception1
{
public static void main(String args[])
{
try
{
int a=Integer.parseInt(args[0]);
Developed By: - Prof. Adnan Ahmad
Page 43
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
int b=Integer.parseInt(args[1]);
int c=a/b;
System.out.println(“C=”+c);
}
catch(ArithmeticException e)
{
System.out.println(“This is the mathematic error”);
}
catch(NumberFormateException e)
{
System.out.println(“This is datatype error”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array size error.”);
}
finally
{
System.out.println(“Error not found.”);
}
}
}
Exception and Error classes=the Throwable class is the super class of all exception and error clases.
This class provide two types of method.
String getMessage()=this method return the string.that was provided to the constructor.
String getLocalizedMessage()= returns a localized description of the exception.
Void printStackTrace()=display information about program at the time of problem occur.
void printStackTrace(PrintStream stream)=sends the stack trace to the specified stream.
void printStackTrace(PrintWriter stream)=sends the stack trace to the specified stream.
String toString()=returns a string object containing a description of the exception.
this method is called by println() when outputing a Throwable object.
The error class extends throwable class.it has more than one dozen subclasses.the error occurs during
compile time and it encounter by JVM.these include class format,stack,overflow,memory
exhaustion,internal error or illegal access.
The exception class extends Throwable.it has subclass which are following
Class
Description
ClassNotFoundException
a class cannot be found
Illegal accessException
an illegal access to a class was attempted
InturruptedException
a thread has been interrupted
NoSuchFieldException
a field could not be found
NoSuchMethodExeption
a method could not be found
RuntimeException
a run time exception occurred
Developed By: - Prof. Adnan Ahmad
Page 44
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
The RunTimeException class is one of the most important subclasses of Exception
It also divided many subclasses.
Class
ArrayIndexOutOfBoundsException
ArithmeticException
Description
an array index out of bounds
an mathematic exception occur
NegativeArraySizeException
NullPointerException
NumberFormatException
StringIndexOutOfBoundsException
a negative number was used for an array
a fiels or method has null object
a number is illegal format
a string index out of bounds
The throw statement=we already know an exception was generated by the jvm when certain run time
problem occurred.it is also possible for your program to explicity generate an exception.this can be done
with a throw statement. Its form is following
throw object.
Here object must be of type java.lang.Throwable.otherwise a compiler error occurs.
Syntax=
Catch(Exceptiontype param)
{
………
throw param;
………
}
customize /user define exception using
Throws clause:
Throw is used to throw an exception manually, where as throws is used in the case of checked exceptions,
to reintimate the compiler that we have handled the exception. So throws is to be used at the time of
defining a method and also at the time of calling that function, which rises an checked exception.
Example:
Prog. to explain diff. b/w throw and throw: Or example of customize/your own exception
class MyException extends Exception //to create our own exception
{
public String toString() //overriding the method toString() to print the desired msg.
{
return "Cannot divide a no. with one: "+"MyException";
}
public static void main(String args[]) throws MyException //use of throws
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
if(b==1)
throw new MyException(); // rises an MyException, if we try to divide a no. with 1
Developed By: - Prof. Adnan Ahmad
Page 45
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
else
System.out.println((float)a/b);
}
}
if we want to rise our own exception, we have to use either throws or to handle the exception by trycatch. If not, it gives the compile time error.
Exception Types:
Unchecked exceptions :

represent defects in the program (bugs) - often invalid arguments passed to a non-private
method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes :
"Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in
your program's logic and cannot be reasonably recovered from at run time."
 are subclasses of RuntimeException, and are usually implemented
using IllegalArgumentException, NullPointerException, orIllegalStateException
 a method is not obliged to establish a policy for the unchecked exceptions thrown by its
implementation (and they almost always do not do so)
Checked exceptions :
 represent invalid conditions in areas outside the immediate control of the program (invalid user
input, database problems, network outages, absent files)
 are subclasses of Exception
 a method is obliged to establish a policy for all checked exceptions thrown by its implementation
(either pass the checked exception further up the stack, or handle it somehow)
It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a subclass
of Exception (checked).
Q26: Discuss enum data type in brief.
Q26: Explain "Top level nested "class and "enum" type with java code.
Q26: Explain nested and inner class.
Ans: enum type:
An enum type is a type whose fields consist of a fixed set of constants. Common examples include
compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Because they are constants, the names of an enum type's fields are in uppercase letters.
In the Java programming language, you define an enum type by using the enum keyword. For example,
you would specify a days-of-the-week enum type as: syntax:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
You should use enum types any time you need to represent a fixed set of constants. That includes natural
enum types such as the planets in our solar system and data sets where you know all possible values at
compile time—for example, the choices on a menu, command line flags, and so on.
Example:
enum Day{MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY}
class EnumTest {
Day day;
Developed By: - Prof. Adnan Ahmad
Page 46
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY: System.out.println("Mondays are bad.");
break;
case FRIDAY: System.out.println("Fridays are better.");
break;
case SATURDAY:System.out.println("Weekends are good.");
break;
case SUNDAY: System.out.println("Weekends are best.");
break;
default: System.out.println("Midweek days are so-so.");
break;
}
}
}
class Enum1
{
public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
seventhDay.tellItLikeItIs();
}}
Nested Class
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: Syntax:
class OuterClass {
...
class NestedClass {
...
}
}
Developed By: - Prof. Adnan Ahmad
Page 47
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Terminology:
Nested classes are divided into two categories: static and non-static. Nested classes that are
declared static are simply called static nested classes. Non-static nested classes are called inner classes.
Syntax:
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?
There are several compelling reasons for using nested classes, among them:
 It is a way of logically grouping classes that are only used in one place.
 It increases encapsulation.
 Nested classes can lead to more readable and maintainable code.

Inner Classes:
As with instance methods and variables, an inner class is associated with an instance of its enclosing class
and has direct access to that object's methods and fields. Also, because an inner class is associated with an
instance, it cannot define any static members itself.
Objects that are instances of an inner class exist within an instance of the outer class. Consider the
following classes: syntax:
class OuterClass {
...
class InnerClass {
...
}
}
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the
methods and fields of its enclosing instance. The next figure illustrates this idea.
An Instance of InnerClass Exists Within an Instance of OuterClass
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within
the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Developed By: - Prof. Adnan Ahmad
Page 48
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Q27: What is the functionality of Simple Date class?
Q27:List out some of the basic utility classes in Java. And explain Date, Calendar and
Gregorian calendar classes.
Q27: Explain classes from “java.util” package.
Ans:
1.Date class=the date class encapsulated information about a specific date and time.it provide following
constructor.
Date()
Date(long msec)
The first type constructor return an object that represent the current date and time.
The secong type return an object that represent the date and time msec after the epoch.
The epoch is defined midnight on January 1,1970 GMT(grrenwich mean time)
Methods of Date class:
boolean equals(Object obj) = this method returns true if the invoking date object contains the same time
and date as the one specified by date. otherwise it returns false.
long getTime() = this method returns number of milliseconds that have elapsed since january 1, 1970.
void setTime(long time) = this method sets the time and date as specified by time.
String toString() = this method converts the invoking Date object into a string and returns the result.
Example:
import java.util.*;
class Date1
{
public static void main(String args[])
{
Date d=new Date();
Date epoch=new Date(0);
System.out.println("current date="+d);
System.out.println("epoch date="+epoch);
}
}
2.Calendar class=the calendar class is the abstract class which allow you to interpret date and time
information.this class define several int constant that are used to set and get component in calendar
class.these are following.
DAY_OF_WEEK,DATE,DAY_OF_MONTH,DAY_OF_YEAR,MONTH,PM,AM,WEEK_OF_YEAR,HOUR. Etc
The Calendar class not have constructor.instead it is used static getInstance() method to obtain a calendar
initializeto current date and time.
Syntax:
Calendar c=Calendar.getInstance()
Method of Calendar class:
int get(int field) = gets the value for a given time field.
Developed By: - Prof. Adnan Ahmad
Page 49
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
int getFirstDayOfWeek() = gets whet the first day of the week is;e.g., sunday in US, monday in
france.
static Calendar getInstance() = gets a calendar using the default time zone and locale.
Date getTime() = gets this calendar's current time.
long getTimeInMillis() = gets this calendar's current time as long.
void set(int year, int month, int date) = sets the value for the fields year, month, and date.
void set(int year, int month, int date, int hour,int minute,int second) = sets the value for
the fields year, month, date,hour, minute and seconds.
void setTime(Date date) = sets this calendar's current time with the given Date.
String toString() = return a string representation of this calendar.
Example:
import java.util.*;
class Calendar1
{
public static void main(String args[])
{
Calendar c=Calendar.getInstance();
System.out.println(c.get(Calendar.YEAR));
System.out.println(c.get(Calendar.MONTH));
System.out.println(c.get(Calendar.DAY_OF_WEEK));
System.out.println(c.get(Calendar.DAY_OF_MONTH));
System.out.println(c.get(Calendar.DATE));
}
}
GregorianCalendar class:
Gregorian Calendar is a concrete subclass of Calendar and provides the standard calendar
used by most of the world. the standard(Gregorian) calendar has 2 eras, BC and AD.
lets see the fields provide by this class
static int AD = value of the era fiels indicating the common era(Anno Domini), also known as
CE.
static int BC = value of the ERA fiels indicating the period before the common era(before
Christ), also known as BCE.
Methods:
void add(int field, int amount) = adds the specified amount of time to the given time field.
void setGregorianChange(Date date) = sets the gregorian calendar change date.
TimeZone class:
Another time related class is TimeZone. the TimeZone class allows you to work with time
zone offset from Greenwich Mean Time(GMT), also referred to as Coordinated Universal Time(
UTC). It also computes daylight saving time.
TimeZone only supplies the default constructor.
Developed By: - Prof. Adnan Ahmad
Page 50
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
“Java.util” package:
“Java.util” package defines the following classes and interfaces
Class(Date,Calendar,Scanner,ArrayList,LinkedList,Vector,Stack,StringTokenizer etc)
Interface(List,Set,Map,SortedMap,SortedSet,Collection,Enumeration,EventListener etc)
Note:For more detail about classes and interface of “java.util” package refer question no. 28 and 27.
Q28: Write note Collection Framework in Java.
Q28: Write a note: List, Set and Map Collection.
Q28: What is difference between Vector and ArrayList? How the Enumeration interface is
useful in Java explain with code?
Ans: Collection Framework:
Java provides the Collections Framework. In the Collection Framework, a collection represents the
group of the objects. And a collection framework is the unified architecture that represents and
manipulates collections.
The collection framework provides a standard common programming interface to many of the
most common abstraction without burdening the programmer with many procedures and
interfaces
Some interfaces and classes of the collection framework are as follows:
INTERFACES
CLASSES
Collection Interface
HashSet Class
Iterator Interface
TreeSet Class
Set Interface
ArrayList Class
List Interface
LinkedList Class
ListIterator Interface
HashMap Class
Map Interface
Hashtable Class
SortedSet Interface
Vector Class
SortedMap Interface
Stack Class
Developed By: - Prof. Adnan Ahmad
Page 51
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Array List class:( Set Interface)
The ArrayList class extends AbstractList and implements the Set interface. ArrayList supports dynamic
arrays that can grow as needed. In Java, standard arrays are of a fixed length. After arrays are created,
they cannot grow or shrink, which means that you must know in advance how many elements an array
will hold. But, sometimes, you may not know until run time precisely how large of an array you need. To
handle this situation, the collections framework defines ArrayList. In essence, an ArrayList is a variablelength array of object references. That is, an ArrayList can dynamically increase or decrease in size. Array
lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged.
When objects are removed, the array may be shrunk.
ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)
The first constructor builds an empty array list. The second constructor builds an array list that is
initialized with the elements of the collection c. The third constructor builds an array list that has the
specified initial capacity. The capacity is the size of the underlying array that is used to store the
elements. The capacity grows automatically as elements are added to an array list.
The methos of ArrayList are following.
•
•
•
•
•
•
•
•
•
•
•
al.add(Object o)
al.add(int index, Object element)
al.set(int index, Object element)
al.addAll(Collection c)
al.addAll(int index, Collection c)
al.clear()
Object o=al.get(int index)
al.remove(int index)
al.isEmpty()
int s=al.size()
Object[ ] o=al.toArray()
Where “al” is the object of ArrayList.
Example:
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " +
al.size());
// add elements to the array list
al.add("C");
al.add("A");
Developed By: - Prof. Adnan Ahmad
Page 52
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);
}
}
Unit: - 1, 2, 3
Obtaining an Array from an ArrayList:
When working with ArrayList, you will sometimes want to obtain an actual array that contains the
contents of the list. As explained earlier, you can do this by calling toArray( ). Several reasons exist
why you might want to convert a collection into an array such as:
• To obtain faster processing times for certain operations.
• To pass an array to a method that is not overloaded to accept a collection.
• To integrate your newer, collection-based code with legacy code that does not understand
collections.
Whatever the reason, converting an ArrayList to an array is a trivial matter, as the following program
shows:
// get array
Object ia[] = al.toArray();
int sum = 0;
// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();
System.out.println("Sum is: " + sum);
}
}
LinkedList class:( List Interface)
The LinkedList class extends AbstractSequentialList and implements the List interface. It provides a linkedlist data structure. It has the two constructors, shown here:
Developed By: - Prof. Adnan Ahmad
Page 53
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
LinkedList( )
LinkedList(Collection c)
The first constructor builds an empty linked list. The second constructor builds a linked list that is
initialized with the elements of the collection c.
In addition to the methods that it inherits, the LinkedList class defines some useful methods of its
own for manipulating and accessing lists. To add elements to the start of the list, use addFirst( ); to
add elements to the end, use addLast( ). Their signatures are shown here:
void addFirst(Object obj)
void addLast(Object obj)
Here, obj is the item being added.
To obtain the first element, call getFirst( ). To retrieve the last element, call getLast( ). Their
signatures are shown here:
Object getFirst( )
Object getLast( )
To remove the first element, use removeFirst( ); to remove the last element, call removeLast( ). They
are shown here:
Object removeFirst( )
Object removeLast( )
Example:
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
LinkedList ll = new LinkedList();
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);
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: " + ll);
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: " + ll);
Object val = ll.get(2);
System.out.println(val);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}
Developed By: - Prof. Adnan Ahmad
Page 54
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Vector class:( SortedSet Interface)
• Vector class is a growable array of objects
• Like an array, it contains components that can be accessed using an integer index
• Vector is synchronized
CONSTRUCTOR:
Vector v=new Vector()
Vector v=new Vector(Collection c)
PROPERTIES:
int n=v.elementCount
Object o=v.elementData
Methods:
• Object o=v.elementAt(int index)
• Enumeration e=v.elements()
• Object o=v.firstElement()
• Object o=v.lastElement()
• Object o=v.get(int index)
• int n=v.indexOf(Object elem)
• Int n=v.size()
• List l=v.subList(int fromIndex, int toIndex)
• Object[] o=v.toArray()
• String s=v.toString()
Enumeration Interface:
An object that implements the Enumeration interface generates a series of elements, one at a
time. Successive calls to the nextElement method return successive elements of the series.
To print all elements of a vector v:
Syntax:
Enumeration e = v.elements(); while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}
Example:
import java.util.*;
class Enumeration1
{
public static void main(String args[])
{
Vector v=new Vector();
v.addElement(new Integer(5));
v.addElement(new Float(5.45f));
v.addElement(new String("Hello"));
Developed By: - Prof. Adnan Ahmad
Page 55
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
v.addElement(new Double(5.3));
for(Enumeration e=v.elements();e.hasMoreElements();)
{
System.out.println(e.nextElement());
}
}
}
Difference B/W Vector & Array List:
java.util.Vector came along with the first version of java development kit (JDK). java.util.ArrayList was
introduced in java version1.2, as part of java collections framework. As per java API, in Java 2 platform
v1.2,vector has been retrofitted to implement List and vector also became a part of java collection
framework.
All the methods of Vector are synchronized. But, the methods of ArrayList are not synchronized. All the
new implementations of java collection framework is not synchronized.
Vector and ArrayList both uses Array internally as data structure. They are dynamically resizable.
Difference is in the way they are internally resized. By default, Vector doubles the size of its array when its
size is increased. But, ArrayList increases by half of its size when its size is increased.
Therefore as per Java API the only main difference is, Vector’s methods are synchronized and ArrayList’s
methods are not synchronized.
Stack class:(SortedMapInterface)
the stack class extends Vector and provide LIFO(last in first out)concept.this is excellent example of the
power of object oriented programming.the Vector class provides the functionality of a dynamic array.the
stack class provide push and pop method.
Methods:
Boolean empty()=return true if stack is empty otherwise false
Object pop()=return the object at top of the stack and remove it from stack
Object push(Object obj)=push object into the stack and also return obj
Int search(Object obj)=search the stack for object.if not found return -1,other wise return the index at
which object is located.the top of stack index is 1.
Example:
import java.util.*;
class Stack1
{
public static void main(String args[])
{
Stack <Integer>s=new Stack<Integer>();
for(int i=0;i<args.length;i++)
s.push(new Integer(args[i]));
while(!s.empty())
{
Object obj=s.pop();
Developed By: - Prof. Adnan Ahmad
Page 56
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
System.out.println(obj);
}
}
}
HashTable class(Map Interface):
•
•
•
•
A Hashtable is a collection of pairs of items (key, value)
When you put a value in the table, you associate the value with a key
To retrieve a value from the table, you provide a key, and the table looks up and returns the value
associated with the key
The Java API provides class Hashtable in package java.util
Java.util.Hashtable Constructors are following:
public Hashtable();
public Hashtable (int initialCapacity,float loadFactor);
public Hashtable (int initialCapacity);
Methods:
•
•
•
•
•
•
•
public Object put (Object key, Object value)
put() associates a value (any object) with a key (an object), and stores the value in the hash table
public Object get(Object key)
get() returns the value associated with the specified key, and leaves the value in the table
public boolean contains( Object value)
contains() returns true if the hash table contains the specified value
public Object remove(Object key)
Deletes a key/value association from the table
public void clear();
Clears table so it has no keys
public int size();
Returns the number of entries in the table
public boolean isEmpty();
Returns true if the table is empty
public boolean equals(Object o)
public String toString();
Example:
Class Hashclass
{
Public static void main(String args[])
{
Hashtable h1=new Hashtable();
System.out.println(“is table empty:”+h1.isEmpty());
H1.put(“the color of apple is”,”red”);
H1.put(“the color of banana is:”,”yellow”);
Developed By: - Prof. Adnan Ahmad
Page 57
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
System.out.println(“the data of Hashtable:”+h1);
System.out.println(“the value of red is:”+h1.get(“red”));
System.out.println(“is table empty:”+h1.isEmpty());
Unit: - 1, 2, 3
System.out.println(“remove from table is:”+h1.remove(“the color of apple is”));
System.out.println(“now the data of Hashtable:”+h1);
}
}
Q29: Explain Math class with example.
Ans:
Math class: Math class defined” java.lang” package.
The Math class contains all the floating point functions that are used for geometry and trigonometry, as
well as several general purpose methods. Math class defines two double constants: E(approximately 2.72)
and PI(approximately 3.14).
Methods:
Static double sin(double arg)= returns the sine of the angle specified by arg in radians.
Static double cos(double arg)=returns the cosine of the angle specified by arg in radians.
Static double tan(double arg)=returns the tangent of the angle specified by arg in radians.
Static double exp(double arg)=returns e to the arg.
Static double log(double arg)=returns the natural algorithm of arg.
Static double pow(double y, double x)=returns y raised to the x.
Static double sqrt(double arg)=returns square root to the arg.
Static int abs(double arg)=returns absolute value to the arg.
Static int max(int x,int y)=returns the maximum of x and y.
Static int min(int x,int y)=returns the minimum of x and y.
Static double ceil(double arg)=returns the smallest whole number greater than or equal to arg.
Static int round(float arg)=returns arg rounded up to the nearest int.
Examples:
class Math1
{
public static void main(String args[])
{
System.out.println(Math.sqrt(9));
System.out.println(Math.pow(2,4));
System.out.println(Math.max(2,4));
System.out.println(Math.ceil(2.4));
System.out.println(Math.round(4.5));
System.out.println(Math.floor(2,4));
}
}
Developed By: - Prof. Adnan Ahmad
Page 58
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Q30: Write a short note on the role of Pattern and Matcher class for handling
regular expression with example.
Ans: Regular Expression: it is a string of character that describes a character sequence. This general
description called Pattern, can then be used to find matches in other character sequence. Regular
expression can specify wildcard characters, sets of characters, and various quantifiers.
There are two classes that support regular expression processing: Pattern and Matcher.
Pattern class define regular expression. Matcher class match the pattern against another sequence.
•
Rules of Regular Expression
– The brackets [ ] represent choices
– The asterisk symbol * means zero or more occurrences.
– The plus symbol + means one or more occurrences.
– The hat symbol ^ means negation.
– The hyphen – means ranges.
– The parentheses ( ) and the vertical bar | mean a range of choices for multiple characters.
•
Example of Regular Expression:
Expression
Description
[013]
A single digit 0, 1, or 3.
[0-9][0-9]
Any two-digit number from 00 to 99.
[0-9&&[^4567]]
A single digit that is 0, 1, 2, 3, 8, or 9.
[a-z0-9]
A single character that is either a lowercase letter or a digit.
[a-zA-z][a-zA-Z0-9_$]*
A valid Java identifier consisting of alphanumeric characters,
underscores, and dollar signs, with the first character being
an alphabet.
[wb](ad|eed)
Matches wad, weed, bad, and beed.
(AZ|CA|CO)[0-9][0-9]
Matches AZxx,CAxx, and COxx, where x is a single digit.
Pattern class: The Pattern class is called regular expression.The pattern class define no constructors.
Instead, a Pattern is created by calling the compile() method.
Syntax: static Pattern compile(String pattern)
Here the pattern is the regular expression that you want to use.
Once you have created a Pattern object, you will use it to create a Matcher. This is done by calling the
Matcher() method defined by Pattern class.
Syntax: Matcher matcher(CharSequence str)
Here str is the character sequence that the pattern will be matched against.
Developed By: - Prof. Adnan Ahmad
Page 59
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Example:
Matcher class: The Matcher class has no constructor. Instead, you create a Matcher by calling the
matcher() method defined by Pattern class.
Once you you have created a Matcher, you will use its method to perform various pattern matching
operations.
Methods of Matcher class:
•
•
•
•
•
•
boolean matches(): it returns true if the sequence and the pattern match, otherwise return false.
boolean find(): it returns true if there is a matching subsequence, otherwise false.
String group(): the matching string returned. If no match exists, then an IllegalStateException is
thrown.
int start(): you can obtain the index within the input sequence of the current match.
int end(): the index one past the end of the current match is obtained.
String replaceAll(String newstr): you can replace all of matching sequence with another sequence.
Example:
import java.util.regex.*
class RegExSample
{
Public static void main(String args[])
{
Pattern p=Pattern.compile(“W+”);
Matcher m=p.matcher(“W WW WWW”);
While(m.find())
System.out.println(“Match:”+m.group());
}
}
Q31: Explain Varargs and Formatter class with example.
Ans:
Varargs class: The Varargs also kanown as variable arguments. This class allows a developer to declare
that a method can take a variable number of parameter for given argument. The Vararg must be the last
argument in the formal argument list.
Example:
Public void write(String…… records)
Developed By: - Prof. Adnan Ahmad
Page 60
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
Write(line1”);
Write(“line1”,”line2”,”line3”);
Public void printf(String format,Object….value)
Public void printf(“%d%d%d”,value1,value2,value3);
Example:
public static void printSomeStrings() {
String firstName = "John";
String lastName = "Doe";
int numPets = 7;
String petType = "dogs";
System.out.printf("%s %s has %s %s.%n",
firstName, lastName, numPets, petType);
System.out.println(firstName + " " + lastName +
" has " + numPets + " " +
petType + ".");
}
Result:
John Doe has 7 dogs.
John Doe has 7 dogs.
Note: in the above program Each %s entry in formatting string is replaced by next argument in
argument list. %n means newline.
Formatter class: printf() method that was added to the PrintStream class by J2SE 5.0. internally it uses
the java.util.Formatter class to format numerical values with specifiers similar to those used for the
printf() function in the C language. Constructor of the formatter class is following
Public Formatter(OutputStream os)
Methods of Formatter class:
Public Appendable out()
Public String toString()
Public void flush()
Public void close()
Public Formatter format(String format, Object…args)
Example:
Import java.io.*;
Import java.util.*;
Class Format1
{
Public static void main(String args[])
{
Formatter formatter=new Formatter((OutputStream)System.out);
formatter.format(“text output with formatter.%n”);
int a=11;
Developed By: - Prof. Adnan Ahmad
Page 61
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
float b=5.3f;
formatter.format(“int=%d%n”,a);
formatter.format(“float=%f%n”,b);
formatter.flush();
formatter.close();
}}
Q32: Explain Scanner Class.
Ans:
Scanner class:
The Scanner class is a class in java.util, which allows the user to read values of various types. There are far
more methods in class Scanner than you will need in this course. We only cover a small useful subset, ones
that allow us to read in numeric values from either the keyboard or file without having to convert them
from strings and determine if there are more values to be read.
Class Constructors:
There are two constructors that are particularly useful: one takes an InputStream object as a parameter
and the other takes a FileReader object as a parameter.
Syntax:
Scanner in = new Scanner(System.in); // System.in is an InputStream
Scanner inFile = new Scanner(new FileReader("myFile"));
If the file ≥myFile≤ is not found, a FileNotFoundException is thrown.
Numeric and String Methods
Method
int nextInt()
long nextLong()
float nextFloat()
double nextDouble()
String next()
String nextLine()
void close()
Returns
Returns the next token as an int. If the next token is
not an integer,InputMismatchException is thrown.
Returns the next token as a long. If the next token is
not an integer,InputMismatchException is thrown.
Returns the next token as a float. If the next token is
not
a
float
or
is
out
of
range, InputMismatchException is thrown.
Returns the next token as a long. If the next token is
not
a
float
or
is
out
of
range, InputMismatchException is thrown.
Finds and returns the next complete token from this
scanner and returns it as a string; a token is usually
ended by whitespace such as a blank or line break. If
not token exists,NoSuchElementException is thrown.
Returns the rest of the current line, excluding any
line separator at the end.
Closes the scanner.
Developed By: - Prof. Adnan Ahmad
Page 62
PATEL GROUP OF INSTITUTIONS
Subject: - JAVA
Unit: - 1, 2, 3
The Scanner looks for tokens in the input. A token is a series of characters that ends with what Java
calls whitespace. A whitespace character can be a blank, a tab character, a carriage return, or the end of
the file. Thus, if we read a line that has a series of numbers separated by blanks, the scanner will take each
number as a separate token
Example:
import java.util.Scanner;
import java.io.*;
// Access System.out
public class NumericInput
{
public static void main(String[] args)
{
// Declarations
Scanner in = new Scanner(System.in);
int integer;
long longInteger;
float realNumber;
double doubleReal;
String string1;
String string2;
// Prompts
System.out.println("Enter an integer, a long integer, "
+ "a floating-point ");
System.out.println("number, another floating-point number, "
+ "and a string.");
System.out.println("Separate each with a blank or return.");
// Read in values
integer = in.nextInt();
longInteger = in.nextLong();
realNumber = in.nextFloat();
doubleReal = in.nextDouble();
string1 = in.nextLine();
System.out.println("Now enter another value.");
string2 = in.next();
System.out.println("Here is what you entered: ");
System.out.println(integer + " " + longInteger + " " + realNumber +
" " + doubleReal + " " + string1 +
" and " + string2);
}
}
Developed By: - Prof. Adnan Ahmad
Page 63