Java Unit2
Java Unit2
Java Unit2
Creating Strings
1. Using String literal
Eg: String str1 = “Hello”;
2. Using another String object
Eg: String str2 = new String(str1);
3. Using new keyword
String str3 = new String(“Java”);
4. Using + operator (Concatenation)
Eg: String str4 = str1+str2;
char charAt(int index) returns char value for the particular index
static String format(Locale l, String format, returns formatted string with given locale
Object... args)
String substring(int beginIndex, int returns substring for given begin index and end
endIndex) index
String replace(char old, char new) replaces all occurrences of specified char value
String[] split(String regex, int limit) returns splitted string matching regex and limit
int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index
int indexOf(String substring, int fromIndex) returns specified substring index starting with given
index
static String valueOf(int value) converts given type into string. It is overloaded.
So StringBuffer class is used when we have to make lot of modifications to our string. It is also thread
safe i.e multiple threads cannot access it simultaneously. StringBuffer defines 4 constructors. They are,
StringBuffer ( )
StringBuffer ( int size )
StringBuffer ( String str )
StringBuffer ( charSequence [ ]ch )
StringBuffer() creates an empty string buffer and reserves room for 16 characters.
StringBuffer(int size) creates an empty string and takes an integer argument to set capacity of the buffer.
Eg:
class Test {
public static void main(String args[])
{
String str = "study";
str.concat("tonight");
System.out.println(str); // Output: study
String objects are immutable objects. Hence, if we concatenate on the same String object, it won't be
altered(Output: study). But StringBuffer creates mutable objects. Hence, it can be altered(Output:
studytonight).
public append(String s) is used to append the specified string with this string. The
synchronized append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float),
append(double) etc.
public insert(int offset, is used to insert the specified string with this string at the
synchronized String s) specified position. The insert() method is overloaded like
StringBuffer insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
public replace(int is used to replace the string from specified startIndex and
synchronized startIndex, int endIndex.
StringBuffer endIndex, String str)
public delete(int startIndex, is used to delete the string from specified startIndex and
synchronized int endIndex) endIndex.
StringBuffer
public void ensureCapacity(int is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number of
characters.
public String substring(int is used to return the substring from the specified
beginIndex) beginIndex.
public String substring(int is used to return the substring from the specified
beginIndex, int beginIndex and endIndex.
endIndex)
VECTOR
Vector implements a dynamic array. It is similar to ArrayList, but with two differences −
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
Constructors
Vector( ) : This constructor creates a default vector, which has an initial size of 10.
Vector(int size) : This constructor accepts an argument that equals to the required size, and creates
a vector whose initial capacity is specified by size.
Vector(int size, int incr) : This constructor creates a vector whose initial capacity is specified by
size and whose increment is specified by incr. The increment specifies the number of elements to
allocate each time that a vector is resized upward.
Vector(Collection c) : This constructor creates a vector that contains the elements of collection c.
Methods in Vector class
boolean add(Object o)
2
Appends the specified element to the end of this Vector.
boolean addAll(Collection c)
3 Appends all of the elements in the specified Collection to the end of this Vector, in the order
that they are returned by the specified Collection's Iterator.
int capacity()
6
Returns the current capacity of this vector.
void clear()
7
Removes all of the elements from this vector.
Object clone()
8
Returns a clone of this vector.
boolean containsAll(Collection c)
10
Returns true if this vector contains all of the elements in the specified Collection.
Enumeration elements()
13
Returns an enumeration of the components of this vector.
boolean equals(Object o)
15
Compares the specified Object with this vector for equality.
Object firstElement()
16
Returns the first component (the item at index 0) of this vector.
int hashCode()
18
Returns the hash code value for this vector.
boolean isEmpty()
22
Tests if this vector has no components.
Object lastElement()
23
Returns the last component of the vector.
boolean remove(Object o)
27 Removes the first occurrence of the specified element in this vector, If the vector does not
contain the element, it is unchanged.
boolean removeAll(Collection c)
28
Removes from this vector all of its elements that are contained in the specified Collection.
void removeAllElements()
29
Removes all components from this vector and sets its size to zero.
boolean retainAll(Collection c)
33
Retains only the elements in this vector that are contained in the specified Collection.
int size()
37
Returns the number of components in this vector.
Object[] toArray()
39
Returns an array containing all of the elements in this vector in the correct order.
Object[] toArray(Object[] a)
40 Returns an array containing all of the elements in this vector in the correct order; the runtime
type of the returned array is that of the specified array.
String toString()
41 Returns a string representation of this vector, containing the String representation of each
element.
void trimToSize()
42
Trims the capacity of this vector to be the vector's current size.
Eg:
import java.util.*;
public class VectorDemo {
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " + v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " + (Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
Output
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12
JAVA - METHODS
A Java method is a collection of statements that are grouped together to perform an operation.
Creating Method
Syntax
public static int methodName(int a, int b) {
// body
}
Here,
public static − modifier
int − return type
methodName − name of the method
a, b − formal parameters
int a, int b − list of parameters
Syntax
modifier returnType nameOfMethod (Parameter List) {
// method body
}
The syntax shown above includes
modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the method name
and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of parameters of a
method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the statements.
Example
return min;
}
Method Calling
For using a method, it should be called. There are two ways in which a method is called i.e., method
returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the program control gets
transferred to the called method. This called method then returns control to the caller in two conditions,
when −
the return statement is executed.
it reaches the method ending closing brace.
Example
public class ExampleMinNumber {
return min;
}
}
The void keyword allows us to create methods which do not return a value.
Method Overloading
When a class has two or more methods by the same name but different parameters, it is known as method
overloading. It is different from overriding. In overriding, a method has the same method name, type,
number of parameters, etc.
Example
public class ExampleOverloading {
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
// same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
The Constructors
A constructor initializes an object when it is created. It has the same name as its class and is syntactically
similar to a method. However, constructors have no explicit return type.
Example
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass() {
x = 10;
}
}
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
}
}
Parameterized Constructor
Example
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}
}
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
Object
Class
Data abstraction and encapsulation
Inheritance
Polymorphism
Dynamic binding
Message passing
Object
Objects are the basic run time entities in an object oriented system. They may represent a person, a place
or any data item. Objects contain data and code that manipulates that data.
Class
The entire set of data and code of an object that can be made a user defined data type with the help of a
class. A class is a collection of objects of type class.
Data Abstraction
The technique of creating new data types providing higher level view of the data that are well suited to an
application to be programmed is known as data abstraction.
Data Encapsulation
The wrapping up of data and functions into a single unit called class is known as data encapsulation.
Data Hiding
The insulation of the data from direct access by the program is called data hiding or information hiding.
Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of another class.
The concept of inheritance provides the idea of reusability. This means that we can add additional
features to an existing class without modifying it. Derivation involves the creation of new classes (derived
class) from the existing ones (base class).
Polymorphism
Polymorphism means the ability to take more than one form. There are two types of
polymorphism.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding also known as late binding means that the code associated with a given procedure call is
not known until the time of call at run time.
Message Passing
Process of invoking an operation on an object is known as message passing. Execution of actual method
is the response.
CLASSES
A class is a user defined data type. Once defined, this new type can be used to create objects of that type.
Thus, a class is a template for an object, and an object is an instance of a class. A class is declared by use
of the class keyword.
Syntax
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is contained within
methods. Collectively, the methods and variables defined within a class are called members of the class.
Java classes do not need to have a main( ) method.
Eg:
class Box {
double width;
double height;
double depth;
}
To actually create a Box object, we will use a statement like the following:
Box mybox = new Box(); // create a Box object called mybox
Every Box object will contain its own copies of the instance variables width, height, and depth. To access
these variables, you will use the dot (.) operator. The dot operator links the name of the object with the
name of an instance variable. For example, to assign the width variable of mybox the value 100, you
would use the following statement:
mybox.width = 100;
INNER CLASSES
It is possible to place a class definition within another class definition. This is called an inner class. The
inner class is a valuable feature because it allows you to group classes that logically belong together and
to control the visibility of one within the other.
Eg:
public class Parcel1 {
class Contents { // inner class
private int i = 11;
public int value() { return i; }
}
class Destination {// inner class
private String label;
Destination(String whereTo) {
label = whereTo;
}
String readLabel() { return label; }
}
public void ship(String dest) {
Contents c = new Contents();
Destination d = new Destination(dest);
System.out.println(d.readLabel());
}
public static void main(String[] args) {
Parcel1 p = new Parcel1();
p.ship("Tanzania");
}
}
ABSTRACT CLASS
A class that is declared with abstract keyword is known as abstract class in java. It can have abstract and
non-abstract methods (method with body). It needs to be extended and its method implemented. It cannot
be instantiated. A method that is declared as abstract and does not have implementation is known as
abstract method.
Example
In this example, Shape is the abstract class, its implementation is provided by the Rectangle and Circle
classes.
INHERITANCE IN JAVA
Inheritance can be defined as the process where one object acquires the properties of another existing
class. A class that is derived from another class is called subclass and inherits all fields and methods of
its superclass.
1) SINGLE INHERITANCE
When a class extends another one class only then it is called as single inheritance. The below flow
diagram shows that class B extends only one class which is A. Here A is a parent class of B and B would
be a child class of A.
Eg :
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
2) MULTIPLE INHERITANCE
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base
class. Mulitple inheritance is not supported directly in Java. The problem with “multiple inheritance” is
that the derived class will have to manage the dependency on two base classes. In Java multiple
inheritance is made possible through interfaces.
3) MULTILEVEL INHERITANCE
Multilevel inheritance refers to a mechanism where one can inherit from a derived class, thereby making
this derived class the base class for the new class.
Eg:
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
4) HIERARCHICAL INHERITANCE
In hierarchical inheritance one class is inherited by many sub classes. In below example class B,C and
D inherits the same class A. A is parent class (or base class) of B,C & D.
Eg:
Class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
Class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
Class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
Class MyClass
{
public void methodB()
{
System.out.println("method of Class B");
}
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
5) HYBRID INHERITANCE
Hybrid inheritance is a combination of Single and Multipleinheritance. A hybrid inheritance can be
achieved in the java in a same way as multiple inheritance that is using interfaces. By using interfaces we
can have multiple as well as hybrid inheritance in Java.
Eg:
interface A
{
public void methodA();
}
interface B extends A
{
public void methodB();
}
interface C extends A
{
public void methodC();
}
class D implements B, C
{
public void methodA()
{
System.out.println("MethodA");
}
public void methodB()
{
System.out.println("MethodB");
}
public void methodC()
{
System.out.println("MethodC");
}
public static void main(String args[])
{
D obj1= new D();
obj1.methodA();
obj1.methodB();
obj1.methodC();
}
}
Conclusion
Userdefined packages
Userdefined packages are created using package command
Syntax:
Package packagename;
Public class classname
{
..
}
Example:
Package mypkg;
Public class firstclass
{
System.out.println(“Welcome_packages”);
}
Importing Packages
Java includes the import statement to bring certain classes, or entire packages, into visibility.
In a Java source file, import statements occur immediately following the package statement
(if it exists) and before any class definitions. This is the general form of the import statement:
import pkg1[.pkg2].(classname|*);
The packages thus created are used in the required program using import statement
import pkg1.[.pkg2][pkg3].classname;
Eg: import mypkg.firstclass;
package pkg1;
public class class A
{
public void disA()
{
System.out.println(“class A”);
}
}
import pkg1. class A;
class pkgtest1
{
public static void main(String args[])
{
Class A obj A=new class A();
Obj A.dis A();
}
}
package pkg2;
public class B
{
protected int m=10;
public void dis B()
{
System.out.println(“class B”);
System.out.println(“m=” +m);
}
}
import pkg1.class A;
import pkg2.*;
class pkgtest2
{
public static void main(string args[])
{
Class A obj A =new class A();
Class B obj B=new class B();
Obj A.dis A();
Obj B.dis B();
}
}
Output :
Class A
Class B
m=10
INTERFACE
Java dose not support multiple inheritance. That is, classes in java cannot have more than one
superclass
An alternate approach to support the concept of multiple inheritance is the use of interfaces
Interfaces, like classes, contain methods and variables.
The difference between interface and class is that interface define only abstract methods and
final fields.
With interface, Java allows to utilize “one interface, multiple methods” aspect of polymorphism.
Defining an Interface
An interface is defined much like a class. This is the general form of an interface:
Eg:
interface area
{
final static float pi=3.142f;
float compute(float x, float y);
void show();
}
Extending interface
Interface can also be extended similar to classes
Format is
Interface intname2 extends intname1
{
//body of intname2
}
Eg:
interface item C
{
int code=100;
}
interface item extends item C
{
Void display();
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then create
the methods defined by the interface. The general form of a class that includes the implements clause
looks like this:
If a class implements more than one interface, the interfaces are separated with a comma. If a class
implements two interfaces that declare the same method, then the same method will be used by clients of
either interface. The methods that implement an interface must be declared public. Also, the type
signature of the implementing method must match exactly the type signature specified in the interface
definition.Here is a small example class that implements the Callback interface shown earlier.
ACCESS SPECIFIERS
Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes, fields and
methods in Java.These Specifiers determine whether a field or method in a class, can be used or invoked
by another method in another class or sub-class. Access Specifiers can be used to restrict access. Access
Specifiers are an integral part of object-oriented programming.
public specifiers :
Public Specifiers achieves the highest level of accessibility. Classes, methods, and fields declared as
public can be accessed from any class in the Java program, whether these classes are in the same package
or in another package.
private specifiers :
Private Specifiers achieves the lowest level of accessibility.private methods and fields can only be
accessed within the same class to which the methods and fields belong. private methods and fields are not
visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to
the public access specifier. Using Private Specifier we can achieve encapsulation and hide data from the
outside world.
protected specifiers :
Methods and fields declared as protected can only be accessed by the subclasses in other package or any
class within the package of the protected members' class. The protected access specifier cannot be applied
to class and interfaces.
default(no specifier):
When you don't set access specifier for the element, it will follow the default accessibility level. There is
no default specifier keyword. Classes, variables, and methods can be default accessed.Using default
specifier we can access class, method, or field which belongs to same package,but not from outside this
package.
Eg:
package pckage1;
class BaseClass {
public int x = 10;
private int y = 10;
protected int z = 10;
int a = 10; //Implicit Default Access Modifier
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
private int getY() {
return y;
}
private void setY(int y) {
this.y = y;
}
protected int getZ() {
return z;
}
protected void setZ(int z) {
this.z = z;
}
int getA() {
return a;
}
void setA(int a) {
this.a = a;
}
}
subClassObj.setY(20);
System.out.println("Value of y is : "+subClassObj.y);*/
//Access Modifiers - Protected
System.out.println("Value of z is : " + subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : " + subClassObj.z);
//Access Modifiers - Default
System.out.println("Value of x is : " + subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of x is : " + subClassObj.a);
}
}
Output
Value of x is : 10
Value of x is : 20
Value of z is : 10
Value of z is : 30
Value of x is : 10
Value of x is : 20