Java Basics: Constructors & Inheritance
Java Basics: Constructors & Inheritance
[Link]
[Link]
[Link] members
[Link] CLASS
[Link] keyword
7. String classes
1. Constructors
Constructor is a block of code that allows you to create an object of class. This can also be called
creating an instance. Constructor looks like a method but it’s not, for example methods can have
any return type or no return type (considered as void) but constructors don’t have any return type
not even void.
class TestOverloading
{
public static void main(String args[])
{
//This object creation would call the default constructor
StudentData myobj = new StudentData();
[Link]("Student Name is: "+[Link]());
[Link]("Student Age is: "+[Link]());
[Link]("Student ID is: "+[Link]());
[Link]
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of parent
class, and you can add new methods and fields also.
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
The class which is inherited is called parent or super class and the new class is called child or
subclass.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. [Link]("Programmer salary is:"+[Link]);
9. [Link]("Bonus of Programmer is:"+[Link]);
10. }
11. }
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000
In java programming, multiple and hybrid inheritance is supported through interface only. We
1) Single Inheritance
Single inheritance is damn easy to understand. When a class extends another one class only then
we call it a 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.
Class B extends A
{
public void methodB()
{
[Link]("Child class method");
}
public static void main(String args[])
{
B obj = new B();
[Link](); //calling super class method
[Link](); //calling local method
}
}
2) Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one
base class. The inheritance we learnt earlier had the concept of one base class or parent. The
problem with “multiple inheritance” is that the derived class will have to manage the dependency
on two base classes.
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If
A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.
3) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a
derived class, thereby making this derived class the base class for the new class. As you can see
in below flow diagram C is subclass or child class of B and B is a child class of A. For more
details and example refer – Multilevel inheritance in Java.
Class X
{
public void methodX()
{
[Link]("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
[Link]("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
[Link]("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
[Link](); //calling grand parent class method
[Link](); //calling parent class method
[Link](); //calling local method
}
}
4) Hierarchical Inheritance
In such kind of 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. Read More
at – Hierarchical Inheritance in java with example program.
Class A
{
public void methodA()
{
[Link]("method of Class A");
}
}
Class B extends A
{
public void methodB()
{
[Link]("method of Class B");
}
}
Class C extends A
{
public void methodC()
{
[Link]("method of Class C");
}
}
Class D extends A
{
public void methodD()
{
[Link]("method of Class D");
}
}
Class MyClass
{
public void methodB()
{
[Link]("method of Class B");
}
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
[Link]();
[Link]();
[Link]();
}
}
The above would run perfectly fine with no errors and the output would be –
method of Class A
method of Class A
method of Class A
5) Hybrid Inheritance
Read the full article here – hybrid inheritance in java with example program.
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes.
If A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.
In this tutorial we will discuss the use of static keyword in Java. It can be used along with
Class name, Variables, Methods and block.
1. static class
2. static block
3. static methods
4. static variables
Static Class
A Class can be made static only if it is a nested Class. The nested static class can be accessed
without having an object of outer class.
Example 1:
class Example1{
//Static class
static class X{
static String str="Inside Class X";
}
public static void main(String args[])
{
[Link]="Inside Class Example1";
[Link]("String stored in str is- "+ [Link]);
}
}
Output:
Static block is mostly used for changing the default values of static [Link] block gets
executed when the class is loaded in the memory.
A class can have multiple Static blocks, which will execute in the same sequence in which they
have been written into the program.
class Example3{
static int num;
static String mystr;
static{
num = 97;
mystr = "Static keyword in Java";
}
public static void main(String args[])
{
[Link]("Value of num="+num);
[Link]("Value of mystr="+mystr);
}
}
Output:
Value of num=97
Value of mystr=Static Keyword in Java
Static Methods
Static Methods can access class variables without using object of the class. It can access non-
static methods and non-static variables by using objects. Static methods can be accessed directly
in static and non-static methods.
Example: Static method display()
class Example6{
static int i;
static String s;
//Static method
static void display()
{
//Its a Static method
Example6 obj1=new Example6();
[Link]("i:"+obj1.i);
[Link]("i:"+obj1.i);
}
void funcn()
{
//Static method called in non-static method
display();
}
public static void main(String args[]) //Its a Static Method
{
//Static method called in another static method
display();
}
}
Output:
i:0
i:0
Static Variables
Data stored in static variables is common for all the objects( or instances ) of that Class.
Memory allocation for such variables only happens once when the class is loaded in the
memory.
These variables can be accessed in any other class using class name.
Unlike non-static variables, such variables can be accessed directly in static and non-
static methods.
class Example7{
static int var1;
static String var2;
//Its a Static Method
public static void main(String args[])
{
[Link]("Var1 is:"+Var1);
[Link]("Var2 is:"+Var2);
}
}
Output:
Var1 is:0
Var2 is:null
As you can see in the above example that both the variables are accessed in void main method
without any object(reference).
package [Link];
class Example8{
static int Var1=77; //Static integer variable
String Var2;//non-static string variable
ob1 integer:88
ob1 String:I'm Object1
ob2 integer:88
ob2 String:I'm Object2
In above example String variable is non-static and integer variable is Static. So you can see that
String variable value is different for both objects but integer variable value is common for both
the instances as all the objects share the same copy of a static variable.
Method Overloading is a feature that allows a class to have two or more methods having same
name, if their argument lists are different. In the last tutorial we discussed constructor
overloading that allows a class to have more than one constructors having different argument
lists.
Method overriding
Declaring a method in subclass which is already present in parent class is known as method
overriding.
Advantage of method overriding
The main advantage of method overriding is that the class can give its own specific
implementation to a inherited method without even modifying the parent class(base class).
class superclass
{
int x;
superclass(int x)
{
this.x=x;
}
void display() // base class method
{
[Link](x);
}
}
class subclass extends superclass
{
int y;
subclass(int x , int y)
{
super(x); // calls super class constructor
this.y=y;
}
void display() // derived class method
{
[Link](y);
}
}
class overriding
{
public static void main(String args[])
{
subclass s1=new subclass(100,200);
[Link](); // calls sub class method
}
}
Output
In java, base class reference can be assigned objects of sub class. When methods of sub class
object are called through base class’s reference, the mapping / binding or function calls to
respective function takes place after running the program, at least possible moment. This kind of
binding is known as “late binding” or “dynamic binding” or “runtime polymorphism”.
{
[Link](“area of rectangle”+a*b);
}
}
class triangle extends shape //sub class
{
triangle(int a1,int b1)
{
super(a1,b1);
}
}
}
class DispatchDemo
{
public static void main (String args[])
r=ob1; [Link]();
[Link] CLASS
Abstract class is a class that cannot be instantiated. (you are not allowed to
create object of Abstract class).
A class that is declared using “abstract” keyword is known as abstract class.
It may or may not include abstract methods which means in abstract class you can have
concrete methods (methods with body) as well along with abstract methods ( without an
implementation, without braces, and followed by a semicolon).
An abstract class has no use until unless it is extended by some other class.
If you declare an abstract method (discussed below) in a class then you must declare
the class abstract as well. you can’t have abstract method in a non-abstract class.
need for abstract classes:
can generalize the super class from which child classes can share its methods.
The subclass of an abstract class which can create an object is called as "concrete class".
abstract Method:
1. It is a method, which has no body (definition) in the base class. The body should be
implemented in the sub class only.
2. Any class with at least one abstract method should be declared as abstract.
3. If the sub class is not implementing an abstract method, its sub class has to implement it.
4. It must be overridden. An abstract class must be extended and in a same way abstract
method must be overriden. Abstract method must be in a abstract class.
{
[Link](“area of rectangle”+a*b);
}
}
class triangle extends shape //sub class
{
triangle(int a1,int b1)
{
a=a1;
b=b1;
}
{
[Link](“area of triangle”+0.5f *a*b);
}
}
class DispatchDemo
{
public static void main (String args[])
6..FINAL KEYWORD
This modifier can be applied to variables, methods and classes.
final Method:
1. It is a method whose definition is preceded by keyword “final”.
final returntype funname()
{
}
2. It can’t be redefined in the sub class. This means that, a sub class can’t override it.
final class:
1. It is a class whose definition is preceded by “final”.
2. The final class can’t be sub classed or derived. This means that we can’t create a sub
class from a final class.
/ no inheritance
final class A
{
}
class B extends A
{
}
The above code gives compile error. Because class A is a final class, which can’t be derived.
String is a group of characters. To manipulate strings java provides the flg. classes.
1. String 2. StingBuffer
String:
It is used to create String objects. String objects are “immutable”. This means that they can’t be
modified. Though String is a class. It can be used as a data type.
Eg.
String s = ”java”;
StringBuffer:
It is also used to create string objects. But these objects are mutable (changeable). This means
that they can be modified. It should be instantiated as follows.
Eg.
StringBuffer s = new StringBuffer(“java”);
String():
Creates a String object. Which is empty.
Eg.
String s = new String();
String(char[] ch):
Creates a string object with given character array.
Eg.
Char ch={‘v’,’i’,’s’,’i’,’o’,’n’};
String s= new String (ch);
Eg.
Char ch[]={‘v’,’i’,’s’,’i’,’o’,’n’};
String s= new String(ch,2,5);
charAt(int):
returns the character specified by the index.. Eg.
String s=”hello java”; Char ch=[Link](4);
concat(String str):
It concatenates the given string with invoking string object and the result is assigned to a new
string.
Eg.
String s1= “Hello”; String s2=”java”; String s3=[Link](s2);
copyValueOf(char ch[]):
copies the given character array into a string object.
Eg.
char ch[]= {‘j’,’a’,’v’,’a’};
String s=[Link](ch);
Eg.
char ch[]= {‘j’,’a’,’v’,’a’};
String s=[Link](ch,2,2);
endsWith(String str):
It returns true. If the invoking string object ends with given string.
Eg.
String s=”Welcome to java”; boolean b=[Link](“java”);
startsWith(String str):
It returns true. If the invoking string object starts with given string.
Eg.
String s=”Welcome to java”; boolean b=[Link](“java”);
equals(obj):
Returns true if the invoking string object and given object are equal.
Eg.
String s1= “java”; String s2=”j2se”; boolean b=[Link](s1);
equalsIgnoreCase(obj):
Returns true if the invoking string object and given object are equal. But it ignores case.
getBytes():
Returns the invoking string object as a byte array.
Eg.
String s=”java”;
byte b[]= [Link]();
Eg.
String s=”welcome to java”; Char ch[]=new char[20]; [Link](2,5,ch,0);
toLowerCase():
converts String object to lower case. Eg.
String s=new String (“hello java”); [Link]();
toUpperCase():
converts String object to upper case. Eg.
String s=new String (“hello java”);
[Link]();
trim():
It removes spaces in the invoking string object.
Eg.
String s = “ hai “; s.o.p(trim(s));
valueOf():
It is used to convert given parameter to a string. Eg.
String s= “ “; Int x=250;
S=[Link](x);
replace():
It is used to replace a character of invoking object with another character and result in assigned
to other string object.
Eg.
String s=”J2SE”;
String s2=[Link](“s”,”e”);
substring():
It returns a string within another string from specified index. Eg.
String s=”java is good”; String s1=[Link](5);
substring(int, int):
It returns a string from specified starting index to ending index of string object.
Eg.
String s=”java is good”; String s1=[Link](5,10);
indexOf():
It returns the index of specified string within the invoking string object. Eg.
String s=”java is good”; Int x =[Link](“is”);
lastIndexOf():
It returns the position / index of last occurrence of specified string in the invoking string object.
Eg.
String s=”java is good and is very nice”;
int x =[Link](“is”);
split():
It splits the invoking string object based on the criteria given as parameter and the result is
assigned to other string object.
Eg.
String s="hello, good, java"; String x[]=new String[5]; x=[Link](",");
for(int i=0;i<[Link];i++) [Link](x[i]);
replaceFirst():
Replaces the first occurance of the string (parameter1) other string (parameter2) and result is
assigned to another string object.
Eg.
String s=new String (“java is as good as any other language”); String s1=[Link](“as”,
“very”);
StringBuffer:
This class is also used to manipulate strings. It objects are mutable. This means that they can be
modified. This class belongs to [Link] package.
Constructors of StringBuffer
StringBuffer():
It creates an empty string buffer object.
Eg.
StringBuffer s= new StringBuffer();
StringBuffer(int):
It creates a string buffer object with initial capacity is 16. Eg.
StringBuffer s= new StringBuffer(16);
StringBuffer(String str):
It creates String Buffer object to given string. Eg.
StringBuffer s=new StringBuffer(“java”);
length():
It returns the length of string buffer object. Eg.
StringBuffer s=new StringBuffer(“Welcome to java”); int x = [Link]();
capacity():
It sreturns the capacity of string buffer object.
Eg.
StringBuffer(“Welcome”);
Int x=[Link]();
ensureCapacity(int):
It is used to set capacity of StringBuffer object.
Eg.
StringBuffer s=new StringBuffer(“helloworld”); [Link](20);
setLength(int):
to set length of StringBuffer object.
Eg.
StringBuffer s=new StringBuffer(“hello world”); [Link](20);
charAt(int):
returns a character at specified index.
Eg.
StringBuffer(“Vision computer education”); Char ch=[Link](3);
setCharAt(int, char):
Set given char. of specified index. Eg.
StringBuffer s=new StringBuffer(“hello world”); [Link](3,k);
getChars(int startindex, int endindex, char target[], int target-startindex):
It copies a substring of StringBuffer object from start index to end index into target array.
Eg.
Char ch[]=new char[20];
SB= new SB(“hello, very good java”); [Link](1,4,ch,0);
append(String str):
To append given string to the string buffer object.
Eg.
StringBuffer s=new StringBuffer(“Hello”); [Link](“java”);
deleteCharAt(int):
Deletes character at specified index. Eg.
SB s=new SB(“j2me”); [Link](2);
replace():
It is used to replace some text of string buffer object with given string.
Eg.
SB s=new SB(“Hello King java”); [Link](2,7,”vision”);
STRING TOKENIZER
The string tokenizer class allows an application to break a string into tokens. The tokenization
method is much simpler than the one used by the StreamTokenizer class.
The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted
strings, nor do they recognize and skip comments.
The set of delimiters (the characters that separate tokens) may be specified either at creation
time or on a per-token basis.
If the flag is false, delimiter characters serve to separate tokens. A token is a maximal
sequence of consecutive characters that are not delimiters.
If the flag is true, delimiter characters are themselves considered to be tokens. A token
is thus either one delimiter character, or a maximal sequence of consecutive characters
that are not delimiters.
import [Link];
public class App {
public static void main(String[] args) {
String str = "This is String , created by NANDHA";
StringTokenizer st = new StringTokenizer(str);
[Link]("---- Split by space ------");
while ([Link]()) {
[Link]([Link]());
}
[Link]("---- Split by comma ',' ------");
StringTokenizer st2 = new StringTokenizer(str, ",");
while ([Link]()) {
[Link]([Link]());
}
}
}
SAMPLE OUTPUT:
---- Split by space ------
This
is
String
,
created
by
NANDHA
---- Split by comma ',' ------
This is String
created by NANDHA
UNIT II
[Link]
[Link]
[Link] COLLECTION CLASSES AND INTERFACES
4. ASSERTION
5. JAVA I/O STREAMS
[Link]
[Link] Classes
[Link]
[Link]
In real life situation there may arise scenarios where we need to define files of the same
name. This may lead to “name-space collisions”. Packages are a way of avoiding “name-
space collisions”.
Types of package:
1) User defined package: The package we create is called user-defined package.
2) Built-in package: The already defined package like [Link].*, [Link].* etc are known as
built-in packages.
Defining a Package:
This statement should be used in the beginning of the program to include that program in that
particular package.
package <package name>;
User-Defined packages:
The users of the Java language can also create their own packages. They are called user-defined
packages. User-defined packages can also be imported into other classes and used exactly in the
same way as the Built-in packages.
Creating and Importing Packages:
package packagename; //to create a package
package [Link];//to create a sub package within a package.
e.g.: package pack;
The first statement in the program must be package statement while creating a package.
While creating a package except instance variables, declare all the members and the class
itself as public then only the public members are available outside the package to other
programs.
Program 1:
package college;
public class student
{
int regno;
String name;
public student(int r,String na)
{
regno=r;
name=na;
}
public void print()
{
[Link]("Regno: "+regno );
[Link]("Name: "+name );
}
}
package course;
public class engineering
{
int regno;
String branch;
String year;
public engineering(int r, String br, String yr)
{
regno=r;
branch=br;
year=yr;
}
public void print()
{
[Link]("Regno: "+regno);
[Link]("Branch: "+branch);
[Link]("Year: "+year);
}
}Compiling the above program:
The –d option tells the Java compiler to create a separate directory and place the .class file in
that directory (package). The (.) dot after –d indicates that the package should be created in the
current directory
Access Specifiers
[Link]
Def: It is a collection of final data members and abstract methods.
It is nothing but a pure abstract class. It has only abstract methods.
Interface looks like class but it is not a class.
An interface can have methods and variables just like the class but the methods declared
in interface are by default abstract (only method signature, no body). Also, the variables
declared in an interface are public, static & final by default.
2) Interface provides complete abstraction as none of its methods can have body. On the other
hand, abstract class provides partial abstraction as it can have abstract and concrete(methods
with body) methods both.
5) Class implementing any interface must implement all the methods, otherwise the class should
be declared as “abstract”.
interface Try
{
int a=10;
public int a=10;
public static final int a=10;
final int a=10;
static int a=0;
}
All of the above statements are identical.
9) Interface variables must be initialized at the time of declaration otherwise compiler will
through an error.
interface Try
{
int x;//Compile-time error
}
Above code will throw a compile time error as the value of the variable x is not initialized at the
time of declaration.
10) Inside any implementation class, you cannot change the variables declared in interface
because by default, they are public, static and final. Here we are implementing the interface
“Try” which has a variable x. When we tried to set the value for variable x we got compilation
error as the variable x is public static final by default and final variables can not be re-initialized.
13) If there are two or more same methods in two interfaces and a class implements both
interfaces, implementation of the method once is enough.
use of interfaces
As mentioned above they are used for abstraction. Since methods in interfaces do not have body,
they have to be implemented by the class before you can access them. The class that implements
interface must implement all the methods of that interface. Also, java programming language
does not support multiple inheritance, using interfaces we can achieve this as a class can
implement more than one interfaces, however it cannot extend more than one classes.
Syn:
interface Interfacename
{
data members ; // final data members methods() ; // abstract methods
}
data members ;
methods()
}
interface Area
{
float compute(float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return(x * y);
}
}
class Triangle implements Area
{
public float compute(float x,float y)
{
return(x * y/2);
}
}
class InterfaceArea
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Triangle tri = new Triangle();
Area area;
area = rect;
[Link]("Area Of Rectangle = "+
[Link](1,2)); area = tri;
[Link]("Area Of Triangle = "+
[Link](10,2)); }
}
SAMPLE OUTPUT:
Area Of Rectangle = 2.0
Area Of Triangle = 10.0
Interfaces
abstract Classes
4 A class can extend only one abstract class A class can implement any number of interfaces
abstract class can have protected , public Interface can have only public abstract methods i.e. by
6
and public abstract methods default
Collections in java is a framework that provides an architecture to store and manipulate the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed
by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue,
Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
Collection framework represents a unified architecture for storing and manipulating group of objects. It has:
There are many methods declared in the Collection interface. They are as follows:
7 public void clear() removes the total no of element from the collection.
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface.
Let's see an example where we are storing Student class object in array list.
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
[Link]=rollno;
[Link]=name;
[Link]=age;
}
. }
import [Link].*;
public class TestCollection3{
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s2=new Student(103,"Hanumat",25);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
. [Link](s1);//adding Student class object
. [Link](s2);
. [Link](s3);
. //Getting Iterator
. Iterator itr=[Link]();
. //traversing elements of ArrayList object
. while([Link]()){
. Student st=(Student)[Link]();
. [Link]([Link]+" "+[Link]+" "+[Link]);
. }
. }
. }
Test it Now
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data structure. It inherits the
AbstractList class and implements List and Deque interfaces.
ArrayList LinkedList
3) ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List
and Deque interfaces.
Output:
arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]
ListIterator Interface is used to traverse the element in backward and forward direction.
import [Link].*;
public class TestCollection8{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
[Link]("Amit");
[Link]("Vijay");
[Link]("Kumar");
[Link](1,"Sachin");
[Link]("element at 2nd position: "+[Link](2));
. ListIterator<String> itr=[Link]();
. [Link]("traversing elements in forward direction...");
while([Link]()){
. [Link]([Link]());
. }
. [Link]("traversing elements in backward direction...");
while([Link]()){
. [Link]([Link]());
. }
. }
. }
Test it Now
Output:
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and
implements Set interface.
List can contain duplicate elements whereas Set contains unique elements only.
Java LinkedHashSet class is a Hash table and Linked list implementation of the set interface. It inherits HashSet class and
implements Set interface.
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements
NavigableSet interface. The objects of TreeSet class are stored in ascending order.
The important points about Java TreeSet class are:
[Link]
An assertion is a statement in the JavaTM programming language that enables you to test your assumptions about your program.
For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than
the speed of light.
Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the
system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions
about the behavior of your program, increasing your confidence that the program is free of errors.
The assertion statement has two forms. The first, simpler form is:
assert Expression1 ;
where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it
is false throws an AssertionError with no detail message.
Use this version of the assert statement to provide a detail message for the AssertionError. The system passes the value
of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's
detail message.
The purpose of the detail message is to capture and communicate the details of the assertion failure. The message should
allow you to diagnose and ultimately fix the error that led the assertion to fail
To enable assertions at various granularities, use the -enableassertions, or -ea, switch. To disable assertions at various
granularities, use the -disableassertions, or -da, switch
class MarkAssertDemo
{
static float maximummarks=100;
static float changes(float mark)
{
maximummarks=maximummarks-mark;
[Link]("The maximummark is:" + maximummarks);
return maximummarks;
}
public static void main(String args[])
{
float g;
for(int i=0;i<5;i++)
{
g=changes(15);
assert maximummarks>=40.00:"marks is below 40.";
}
}
}
SAMPLE OUTPUT:
javac [Link]
java –ae MarkAssertDemo
The maximummark is:85.0
The maximummark is:70.0
The maximummark is:55.0
The maximummark is:40.0
The maximummark is:25.0
Exception in thread "main" [Link]: marks is below 40.
at [Link]([Link])
InputStream:
The InputStream class is used for reading the data such as a byte and array of bytes from an input source. An input source can
be a file, a string, or memory that may contain the data. It is an abstract class that defines the programming interface for all
input streams that are inherited from it.
InputStream
- ByteArrayInputStream
- FileInputStream
- ObjectInputStream
- FilterInputStream
- PipedInputStream
- StringBufferInputStream
- FilterInputStream
o BufferedInputStream
o DataInputStream
o LineNumberInputStream
o PushbackInputStream
OutputStream:
The OutputStream class is a sibling to InputStream that is used for writing byte and array of bytes to an output source. Similar
to input sources, an output source can be anything such as a file, a string, or memory containing the data.
OutputStream
- ByteArrayOutputStream
- FileOutputStream
- ObjectOutputStream
- FilterInputStream
- PipedOutputStream
- StringBufferInputStream
- FilterOutputStream
o BufferedOutputStream
o DataOutputStream
o PrintStream
OutputStream is also inherited from the Object class. Each class of the OutputStream provided by the [Link] package is
intended for a different purpose.
import [Link];
import [Link];
import [Link];
import [Link];
try{
File infile =new File("C:\\[Link]");
File outfile =new File("C:\\[Link]");
int length;
/*copying the contents from input stream to
* output stream using read and write methods
*/
while ((length = [Link](buffer)) > 0){
[Link](buffer, 0, length);
}
}catch(IOException ioe){
[Link]();
}
}
}
[Link]
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes
the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information
and bytes that represent the object and its data can be used to recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and
deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and
deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular
stands out −
SERIALIZING AN OBJECT
The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee
object and serializes it to a file.
When the program is done executing, a file named [Link] is created. The program does not generate any output, but
study the code and try to determine what the program is doing.
Note − When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.
Example
import [Link].*;
public class SerializeDemo {
try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/[Link]");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
[Link](e);
[Link]();
[Link]();
[Link]("Serialized data is saved in /tmp/[Link]");
}catch(IOException i) {
[Link]();
}
}
}
Deserializing an Object
The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the
program and try to determine its output −
Example
import [Link].*;
public class DeserializeDemo {
[Link]("Deserialized Employee...");
[Link]("Name: " + [Link]);
[Link]("Address: " + [Link]);
[Link]("SSN: " + [Link]);
[Link]("Number: " + [Link]);
}
}
Output
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
[Link] CLASS
Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper classes because they "wrap"
the primitive data type into an object of that class. The wrapper classes are part of the [Link] package, which is imported by
default into all Java programs.
The wrapper classes in java servers two primary purposes.
To provide a mechanism to ‘wrap’ primitive values in an object so that primitives can do activities reserved for the
objects like being added to ArrayList, Hashset, HashMap etc. collection.
To provide an assortment of utility functions for primitives like converting primitive types to and from string objects,
converting to various bases like binary, octal or hexadecimal, or comparing various objects.
All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.
The object of the wrapper class contains or wraps its respective primitive data type. Converting primitive data types into
object is called boxing, and this is taken care by the compiler. Therefore, while using a wrapper class you just need to pass the
value of the primitive data type to the constructor of the Wrapper class.
And the Wrapper object will be converted back to a primitive data type, and this process is called unboxing.
The Number class is part of the [Link] package.
Example
public class Test {
Output
15
When x is assigned an integer value, the compiler boxes the integer because x is integer object. Later, x is unboxed so that
they can be added as an integer.
As explain in above table all wrapper classes (except Character) take String as argument constructor. Please note we might get
NumberFormatException if we try to assign invalid argument in the constructor. For example to create Integer object we can
have the following syntax.
Integer intObj = new Integer (25);
Here in we can provide any number as string argument but not the words etc. Below statement will throw run time exception
(NumberFormatException)
Integer intObj3 = new Integer ("Two");
The following discussion focuses on the Integer wrapperclass, but applies in a general sense to all eight wrapper classes.
The most common methods of the Integer wrapper class are summarized in below table. Similar methods for the other wrapper
classes are found in the Java API documentation.
Method Purpose
int compareTo(int i) Compares the numerical value of the invoking object with that of i. Returns 0 if
the values are equal. Returns a negative value if the invoking object has a lower
value. Returns a positive value if the invoking object has a greater value.
static int compare(int Compares the values of num1 and num2. Returns 0 if the values are equal.
num1, int num2) Returns a negative value if num1 is less than num2. Returns a positive value if
num1 is greater than num2.
boolean equals(Object Returns true if the invoking Integer object is equivalent to intObj. Otherwise, it
intObj) returns false.
Let’s see java program which explains few wrapper classes methods.
view plaincopy to clipboardprint?
1. package WrapperIntro;
2. public class WrapperDemo {
3. public static void main (String args[]){
4. Integer intObj1 = new Integer (25);
5. Integer intObj2 = new Integer ("25");
6. Integer intObj3= new Integer (35);
7. //compareTo demo
8. [Link]("Comparing using compareTo Obj1 and Obj2: " + [Link](intObj2));
9. [Link]("Comparing using compareTo Obj1 and Obj3: " + [Link](intObj3));
10. //Equals demo
11. [Link]("Comparing using equals Obj1 and Obj2: " + [Link](intObj2));
12. [Link]("Comparing using equals Obj1 and Obj3: " + [Link](intObj3));
13. Float f1 = new Float("2.25f");
14. Float f2 = new Float("20.43f");
15. Float f3 = new Float(2.25f);
16. [Link]("Comparing using compare f1 and f2: " +[Link](f1,f2));
17. [Link]("Comparing using compare f1 and f3: " +[Link](f1,f3));
18. //Addition of Integer with Float
19. Float f = [Link]() + f1;
20. [Link]("Addition of intObj1 and f1: "+ intObj1 +"+" +f1+"=" +f );
21. }
22.
23. }
Output:
1. package WrapperIntro;
2. public class ValueOfDemo {
3. public static void main(String[] args) {
4. Integer intWrapper = [Link]("12345");
5. //Converting from binary to decimal
6. Integer intWrapper2 = [Link]("11011", 2);
7. //Converting from hexadecimal to decimal
8. Integer intWrapper3 = [Link]("D", 16);
9. [Link]("Value of intWrapper Object: "+ intWrapper);
10. [Link]("Value of intWrapper2 Object: "+ intWrapper2);
11. [Link]("Value of intWrapper3 Object: "+ intWrapper3);
12. [Link]("Hex value of intWrapper: " + [Link](intWrapper));
13. [Link]("Binary Value of intWrapper2: "+ [Link](intWrapper2));
14. }
15. }
[Link]
the object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone
an object.
The [Link] interface must be implemented by the class whose object clone we want to create. If we don't
implement Cloneable interface, clone() method generates CloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as follows:
The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new
keyword, it will take a lot of processing to be performed that is why we use object cloning.
Output:101 amit
101 amit
Database connectivity
Unit Structure
15.1 Introduction
15.2 A connection can be open with the help of following steps
15.3 Connecting to an ODBC Data Source
15.4 JDBC Programs
15.1
Introduction :
A Database connection is a facility in computer science that allows client software to
communicate with database server software, whether on the same machine or not. A connection is
required to send commands and receive answers.
Connections are built by supplying an underlying driver or provider with a connection
string, which is a way of addressing a specific database or server and instance as well as user
authentication credentials (for example, Server=sql_box;Database=Common;User
ID=uid;Pwd=password;). Once a connection has been built it can be opened and closed at will,
and properties (such as the command time-out length, or transaction, if one exists) can be set. The
Connection String is composed of a set of key/value pairs as dictated by the data access interface
and data provider being used.
15.2
A connection can be open with the help of following steps
1. Importing Packages
2. Registering the JDBC Drivers
3. Opening a Connection to a Database
4. Creating a Statement Object
5. Executing a Query and Returning a Result Set Object
6. Processing the Result Set
7. Closing the Result Set and Statement Objects
8. Closing the Connection
Connection m_con=[Link](m_url,m_userName,m_password);
SQL Statements
The statement interface provides three different methods for executing SQL statements :
Statement
Statement stmt=m_con.createStatement();
Statement stmt=m_con.createStatement(int resultSetType, int resultSetConcurrency);
PreparedStatement
CallableStatement
Note :
The sql parameter is in the form of ―{call <stored_procedure_name>[(arg1, arg2,...)]} ― or‖
{ ?=call <stored_procedure_name>[(arg1,arg2...)]}‖. It could contain one or more ‗?‘s in it, which
indiacates IN, OUT or INOUT parameters. The value of each IN parameter is set by calling a
setXXX mehod, while each OUT parameter should be registered by calling a
registerOutParameter method.
Statement :
PrepaedStatement :
ResultSet res=[Link]();
int rowCount=[Link]();
boolean result=[Link]();
CallableStatement :
ResultSet res=[Link]();
int rowCount=[Link]();
boolean result=[Link]();
A result set contains all of the rows which satisfied the conditions in an SQL statement
and it provides access to the data in those rows through getXXX mehods that allow access to the
various columns of the current row.
The [Link]() method is used to move to the next row of the ResultSet, making the
next row become the current row. [Link]() returns true if the new current row is valid,
false if there are no more rows. After all the works have been done, the ResultSet should be
closed with [Link]() method.
Because of limitations imposed by some DBMSs, it is recommended that for maximum
portability, all of the results generated by the execution of a CallableStatement object should be
retrieved before OUT parameters are retrieved using [Link] methods.
After all the works have been done, the result set and statement should be closed with the
following code :
Resultset : [Link]();
Statement : [Link]();
PrepaedStatement : [Link]();
CallableStatement : [Link]();
(Connection name)m_con.close();
15.3
Connecting to an ODBC Data Source
A database can be created and managed through Java applications. Java application that
uses a JDBC-ODBC bridge to connect to a database file either a dbase, Excel, FoxPro, Access,
SQL Server, Oracle or any other. Open the ODBC Data source from the control panel. A
database can be created and managed through Java applications.
Follow the following steps to connect to an ODBC Data Source for ―ORACLE‖.
4. Select the MS-ODBC for oracle or any other driver that felt it required.
5. Once clicking the finish button, the following window appears asking for
Data Source
name, description etc.
The DSN is now ready and the Java code can be written to access the database‘s tables.
15.4
JDBC Programs
// Create Table
import [Link].*; // imports all classes that belongs to the package [Link].*
import [Link].*;
{
ResultSet result;
try
{
[Link](―[Link]‖);
Connectioncon= [Link]
(jdbc:odbc:nitin‖ ,scott‖,‖tiger‖);
while([Link]())
{
[Link]([Link](I)+[Link](2));
}
}
catch(Exception e)
{
[Link](―Errors‖+e);
}
}
}
[Link] for viewing rows from a table
import [Link].*;
public class SelectEmp
{
public stativ void main(String args[])
{
String url=‖jdbc:odbc:nitin‖;
Connection con;
String s= ―select ename from emp 1‖;
Statement stmt;
try
{
[Link](―[Link]‖);
}
catch([Link] e)
{
[Link](―ClassNotFoundException:‖);
[Link]([Link]());
}
try
{
con=[Link](url,‖Scott‖,‖Tiger‖);
stmt=[Link]();
resultSet rs=[Link](s);
while([Link]())
{
String s1=[Link](―ename‖);
[Link](―Employee name:‖ +s1);
}
[Link]();
[Link]();
}
catch(SQLException ex)
{
[Link](―SQLException:‖+[Link]());
}
}
}
4. Example using prepared statements
import [Link].*;
while ([Link]())
{
String stname1 = [Link](1);