cs23312 - Unit 2
cs23312 - Unit 2
2.1 ARRAYS
Array is a collection of similar type of elements that have contiguous memory location.
In Java all arrays are dynamically allocated.
Since arrays are objects in Java, we can find their length using member length.
A Java array variable can also be declared like other variables with [] after the data type.
The variables in the array are ordered and each have an index beginning from 0.
Java array can be also be used as a static field, a local variable or a method parameter.
The size of an array must be specified by an int value and not long or short.
The direct superclass of an array type is Object.
Every array type implements the interfaces Cloneable and java.io.Serializable.
Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at
runtime.To solve this problem, collection framework is used in java.
One-Dimensional Arrays
An array is a group of like-typed variables that are referred to by a common name. An array
declaration has two components: the type and the name. type declares the element type of the array.
The element type determines the data type of each element that comprises the array. We can also
create an array of other primitive data types like char, float, double..etc or user defined data
type(objects of a class).Thus, the element type for the array determines what type of data the array
will hold.
Syntax:
type var-name[ ];
Instantiation of an Array in
javaarray-var = new type [size];
Example:
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
10
20
70
40
50
Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the array holding the reference of
other array. These are also known as Jagged Arrays. A multidimensional array is created by
appending one set of square brackets ([]) per dimension.
Syntax:
type var-name[ ][ ]=new type[row-size ][col-size ];
Example:
// Demonstrate a two-dimensional
array.class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Output:
01234
56789
10 11 12 13 14
15 16 17 18 19
When you allocate memory for a multidimensional array, you need only specify the memory for the
first (leftmost) dimension. You can allocate the remaining dimensions separately. For example, this
following code allocates memory for the first dimension of twoD when it is declared. It allocates the
second dimension manually.
Syntax:
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
Example:
// Manually allocate differing size second
dimensions.class TwoDAgain {
public static void main(String args[])
{
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++)
{
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++)
{
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Output:
0
12
345
6789
The array created by this program looks like this:
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2
numbers.*/
STRINGS
String Literal - Java String literal is created by using double quotes. For Example: String
s="welcome";
By new keyword - String s=new String("Welcome");
class Main {
// create strings
// print strings
class Main {
String methods
String methods:
1. char charAt(int index) returns char value for the particular index
2. int length() returns string length
3. static String format(String format, returns formatted string
Object... args)
4. static String format(Locale l, String returns formatted string with given locale
format, Object... args)
5. String substring(int beginIndex) returns substring for given begin index
6. String substring(int beginIndex, int returns substring for given begin index and end
endIndex) Index
7. boolean contains(CharSequence s) returns true or false after matching the sequence
of char value
8. static String join(CharSequence returns a joined string
delimiter, CharSequence... elements)
9. static String join(CharSequence returns a joined string
delimiter, Iterable<? extends
CharSequence> elements)
10. boolean equals(Object another) checks the equality of string with object
11. boolean isEmpty() checks if string is empty
12. String concat(String str) concatinates specified string
13. String replace(char old, char new) replaces all occurrences of specified char value
14. String replace(CharSequence old, replaces all occurrences of specified
CharSequence new) CharSequence
15. static String equalsIgnoreCase(String compares another string. It doesn't check case.
another)
16. String[] split(String regex) returns splitted string matching regex
17. String[] split(String regex, int limit) returns splitted string matching regex and limit
18. String intern() returns interned string
19. int indexOf(int ch) returns specified char value index
20. int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index
21. int indexOf(String substring) returns specified substring index
22. int indexOf(String substring, int returns specified substring index starting with
fromIndex) given index
23. String toLowerCase() returns string in lowercase.
24. String toLowerCase(Locale l) returns string in lowercase using specified locale.
25. String toUpperCase() returns string in uppercase.
26. String toUpperCase(Locale l) returns string in uppercase using specified
locale.
27. String trim() removes beginning and ending spaces of this
string.
28. static String valueOf(int value) converts given type into string. It is overloaded.
Example
public classstringmethod
{
public static void main(String[] args)
{
String string1 = new String("hello");
String string2 = new String("hello");
if (string1 == string2)
{
System.out.println("string1= "+string1+" string2= "+string2+" are equal");
}
else
{
System.out.println("string1= "+string1+" string2= "+string2+" are Unequal");
}
System.out.println("string1 and string2 is= "+string1.equals(string2));
String a="information";
System.out.println("Uppercase of String a is= "+a.toUpperCase());
String b="technology";
System.out.println("Concatenation of object a and b is= "+a.concat(b)); System.out.println("After
concatenation Object a is= "+a.toString()); System.out.println("\"RIT\'s\" is the greatest\\ college in
chennai"); System.out.println("Length of Object a is= "+a.length());
System.out.println("The third character of Object a is= "+a.charAt(2));
StringBuffer n=new StringBuffer("Technology");
StringBuffer m=new StringBuffer("Information");
System.out.println("Reverse of Object n is= "+n.reverse());
n= new StringBuffer("Technology");
System.out.println("Concatenation of Object m and n is= "+m.append(n)); System.out.println("After
concatenation of Object m is= "+m);
}
}
Output
string1= hello string2= hello are Unequal string1 and string2 is= true
Uppercase of String a is= INFORMATION
Concatenation of object a and b is= informationtechnology
After concatenation Object a is= information
"Joseph's" is the greatest\ college in chennai
Length of Object a is= 11
The third character of Object a is= f
Reverse of Object n is= ygolonhceT
Concatenation of Object m and n is= InformationTechnology
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.
Mutable String:
A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.
The append() method concatenates the given argument with this String.
Program
Class StringBufferExample
Output:
Hello Compiler
The insert() method inserts the given String with this string at the given position.
Program:
class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:
HJavaello
The replace() method replaces the given String from the specified beginIndex and endIndex.
StringBufferExample3.java
class StringBufferExample3{
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
OUTPUT:
HJavalo
The delete() method of the StringBuffer class deletes the String from the specified beginIndex to endIndex.
StringBufferExample4.java
class StringBufferExample4{
sb.delete(1,3);
System.out.println(sb);//prints Hlo
OUTPUT
Hlo
The reverse() method of the StringBuilder class reverses the current String.
StringBufferExample5.java
class StringBufferExample5{
public static void main(String args[]){
sb.reverse();
System.out.println(sb);//prints olleH
}}
OUTPUT
OlleH
The capacity() method of the StringBuffer class returns the current capacity of the buffer. The default
capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
StringBufferExample6.java
class StringBufferExample6{
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
}}
OUTPUT
16
16 34
The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the minimum to the
current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For
example if your current capacity is 16, it will be (16*2)+2=34.
StringBufferExample7.java
class StringBufferExample7{
public static void main(String args[]){
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}}
Output:
16
16
34
34
70
System.out.println("success");
Output:
Success
testout.txt
Java DataInputStream class allows an application to read primitive data from the input stream in a machine-
independent way.
Java application generally uses the data output stream to write data that can later be read by a data input
stream.
In this example, we are reading the data from the file testout.txt file.
import java.io.*;
inst.read(ary);
System.out.print(k+"-");
}
Here, we are assuming that you have following data in "testout.txt" file:
JAVA
Output:
J-A-V-A
Success
Java DataOutputStream class allows an application to write primitive Java data types to the output
stream in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read by a data
input stream.
Method Description
int size() It is used to return the number of bytes written to the data output
stream.
void write(int b) It is used to write the specified byte to the underlying output stream.
void write(byte[] b, int off, int It is used to write len bytes of data to the output stream.
len)
void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value.
void writeBytes(String s) It is used to write string to the output stream as a sequence of bytes.
void writeUTF(String str) It is used to write a string to the output stream using UTF-8 encoding in
portable manner.
void flush() It is used to flushes the data output stream.
In this example, we are writing the data to a text file testout.txt using DataOutputStream class.
package com.javatpoint;
import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
Output:
Succcess...
testout.txt:
A
Overloading Methods
1. Explain briefly about function overloading with a suitable example.
Nov/Dec 2021
2. Outline Method overriding with an example. Nov/Dec 2021
When two or more methods within the same class that have the same name, but their
parameter declarations are different. The methods are said to be overloaded, and the
process is referred to as method overloading. Method overloading is one of the ways that
Java supports polymorphism.
Example:
void test() {
System.out.println("No parameters");
}
// Overload test for a double parameter double test(double a) { System.out.println("double
a: " + a); return a*a;
class Overload {
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
Output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
When a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the
superclass. When an overridden method is called from within its subclass, it will always
refer to the version of that method defined by the subclass. The version of the method
defined by the superclass will be hidden.
Example:
int i, j;
A(int a, int b) { i = a;
j = b;
k = c;
class Override {
public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); // this calls
show() in B
Output:
k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B is
used. That is, the version of show( ) inside B overrides the version declared in A. If you
wish to access the superclass version of an overridden method, you can do so by using
super. For example, in this version of B, the superclass version of show( ) is invoked within
the subclass’ version. This allows all instance variables to be displayed. class B extends A {
int k;
super(a, b); k = c;
void show() {
If you substitute this version of A into the previous program, you will see the following
Output:
i and j: 1 2
k: 3
Java does this interesting thing that’s sort of a hybrid between pass-by-value and pass-by-
reference. Basically, a parameter cannot be changed by the function, but the function can
ask the parameter to change itself via calling some method within it.
• While creating a variable of a class type, we only create a reference to an object. Thus,
when we pass this reference to a method, the parameter that receives it will refer to
the same object as that referred to by the argument.
• This effectively means that objects act as if they are passed to methods by use of call -
by-reference.
• Changes to the object inside the method do reflect the object used as an argument.
Illustration: Let us suppose three objects ‘ob1’ , ‘ob2’ and ‘ob3’ are created:
From the method side, a reference of type Foo with a name a is declared and it’s initially
assigned to null.
boolean equalTo(ObjectPassDemo o);
As we call the method equalTo, the reference ‘o’ will be assigned to the object which is
passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as the following statement execute.
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob2’. Since
values of ‘a’ and ‘b’ are same for both the references, so if(condition) is true, so boolean
true will be return.
if(o.a == a && o.b == b)
Again ‘o’ will reassign to ‘ob3’ as the following statement execute.
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
• Now as we can see, the equalTo method is called on ‘ob1’, and ‘o’ is referring to ‘ob3’.
Since values of ‘a’ and ‘b’ are not the same for both the references, so if (condition) is
false, so else block will execute, and false will be returned.
Example
// Class 1
class ObjectReturnDemo {
int a;
// Constructor
ObjectReturnDemo(int i)
{ a = i; }
// Class 2
// Main class
public class GFG {
ob2 = ob1.incrByTen();
Output
ob1.a: 2
ob2.a: 12
Inner class means one class which is a member of another class. There are
basically four types of inner classes in java.
1) Static nested classes
2) Nested Inner class
3) Method Local inner classes
4) Anonymous inner classes
1) Static nested classes
Static nested classes are not technically an inner class. They are like a static member of
outer class.
Example:
class Outer {
private static void outerMethod() { System.out.println("inside outerMethod");
}
// A static inner class static class Inner {
public static void main(String[] args)
{
System.out.println("inside inner class Method");
outerMethod();
}
}
}
Output:
inside inner class Method inside outerMethod
Nested Inner class can access any private instance variable of outer class. Like
any other instance variable, we can have access modifier private, protected, public
and default modifier. Like class, interface can also be nested and can have access
specifiers.
Example:
class Outer {
// Simple
nested inner
class class
Inner {
public void show() {
System.out.println("In a nested class method");
}
}
}
class Main {
public static void
main(String[] args) {
Outer.Inner in = new
Outer().new Inner();
in.show();
}
}
Output:
In a nested class method
1. Explain in detail about various types of inheritance in java with neat diagram?
(NOV/DEC 2019)
4. Outline the use of extends keyword in Java with syntax. (NOV/DEC 2021)
5. When a class hierarchy is created, in what order are the constructors for the
classes that make up the hierarchy called? Outline with an example(NOV/DEC 2021)
6. Outline method overriding with an example. (NOV/DEC 2021)
SINGLE INHERITANCE
In Single Inheritance one class extends another class (one class only).
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
MULTILEVEL INHERITANCE
In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived
class becomes the base class for the new class.
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
//Assigning ClassC object to ClassC reference ClassC c = new ClassC();
//call dispA() method of ClassA c.dispA();
//call dispB() method of ClassB c.dispB();
//call dispC() method of ClassC c.dispC();
}
}
Output :
disp() method of ClassA disp() method of ClassB disp() method of ClassC
HIERARCHICAL INHERITANCE
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB b.dispB();
//call dispA() method of ClassA b.dispA();
//Assigning ClassC object to ClassC reference ClassC c = new ClassC();
//call dispC() method of ClassC c.dispC();
//call dispA() method of ClassA c.dispA();
Hybrid Inheritance is the combination of both Single and Multiple Inheritance. Again
Hybrid inheritance is also not directly supported in Java only through interface we can
achieve this. Flow diagram of the Hybrid inheritance will look like below. As you can
ClassA will be acting as the Parent class for ClassB & ClassC and ClassB & ClassC will be
acting as Parent for ClassD.
“super” KEYWORD
Even when we add explicitly also it behaves the same way as it did before. class
ParentClass
{
public ParentClass()
{
System.out.println("Parent Class default Constructor");
}
}
public class SubClass extends ParentClass
{
SubClass()
{
super();
System.out.println("Child Class default Constructor");
}
public static void main(String args[])
{
SubClass s = new SubClass();
}
}
Output:
Parent Class default Constructor
Child Class default Constructor
You can also call the parameterized constructor of the Parent Class. For example,
super(10) will call parameterized constructor of the Parent class.
class ParentClass
{
ParentClass()
{
System.out.println("Parent Class default Constructor called");
}
ParentClass(int val)
{
System.out.println("Parent Class parameterized Constructor, value: "+val);
}
}
public class SubClass extends ParentClass
{
SubClass()
{
super();//Has to be the first statement in the constructor System.out.println("Child Class
default Constructor called");
}
SubClass(int val)
{
super(10);
System.out.println("Child Class parameterized Constructor, value: "+val);
}
public static void main(String args[])
{
}
}
Output
Parent Class default Constructor called Child Class default Constructor called
Parent Class parameterized Constructor, value: 10
Child Class parameterized Constructor, value: 10
void disp()
{
System.out.println("Value is : "+val);
}
}
}
Output
Value is : 123
This will call only the val of the sub class only. Without super keyword, you cannot call
the val
which is present in the Parent Class. class ParentClass
{
int val=999;
}
public class SubClass extends ParentClass
{
int val=123;
void disp()
{
System.out.println("Value is : "+super.val);
}
void disp()
{
System.out.println("Child Class method");
}
void show()
{
disp();
}
public static void main(String args[])
{
}
}
Output:
void show()
{
//Calling SubClass disp() method disp();
//Calling ParentClass disp() method super.disp();
}
public static void main(String args[])
{
}
}
Output
When there is no method overriding then by default Parent Class disp() method will be
called. class ParentClass
{
public void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{
public void show()
{
disp();
}
public static void main(String args[])
{
SubClass s = new SubClass(); s.show(); }}
Output:
Parent Class method
Method Overriding
When a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the
superclass. When an overridden method is called from within its subclass, it will always
refer to the version of that method defined by the subclass. The version of the method
defined by the superclass will be hidden.
Example:
// Method overriding. class A {
int i, j;
A(int a, int b) { i = a;
j = b;
}
// display i and j void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A { int k;
B(int a, int b, int c) { super(a, b);
k = c;
}
// display k – this overrides show() in A void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); // this
calls show() in B
}
}
Output:
k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B is
used. That is, the version of show( ) inside B overrides the version declared in A. If you
wish to access the superclass version of an overridden method, you can do so by using
super. For example, in this version of B, the superclass version of show( ) is invoked
within the subclass’ version. This allows all instance variables to be displayed. class B
extends A {
int k;
B(int a, int b, int c) {
super(a, b); k = c;
}
void show() {
super.show(); // this calls A's show() System.out.println("k: " + k);
}
}
If you substitute this version of A into the previous program, you will see the following
Output:
i and j: 1 2
k: 3
Here, super.show( ) calls the superclass version of show( ).
class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method
Explanation:
The above program creates one superclass called A and it’s two subclasses B and C. These
subclasses overrides m1( ) method.
1. Inside the main() method in Dispatch class, initially objects of type A, B, and C are
declared.
2. A a = new A(); // object of type A
3. B b = new B(); // object of type B
4. C c = new C(); // object of type C
5. Now a reference of type A, called ref, is also declared, initially it will point to null.
6. A ref; // obtain a reference of type A
7. Now we are assigning a reference to each type of object (either A’s or B’s or C’s)
to ref, one-by-one, and uses that reference to invoke m1( ). As the output shows, the
version of m1( ) executed is determined by the type of object being referred to at
the time of the call.
8. ref = a; // r refers to an A object
9. ref.m1(); // calling A's version of m1()
ref = b; // now r refers to a B object
ref.m1(); // calling B's version of m1()
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).Abstraction is a process of
hiding the implementation details and showing only functionality to the user.
Abstraction lets you focus on what the object does instead of how it does it. It needs to be
extended and its method implemented. It cannot be instantiated.
Example abstract class:
abstract class A{}
abstract method:
A method that is declared as abstract and does not have implementation is known as
abstract method.
abstract void printStatus();//no body and abstract
In this example, Shape is the abstract class, its implementation is provided by the
Rectangle and Circle classes.
If you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked.
Example1:
File: TestAbstraction1.java abstract class Shape{ abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user class
Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In real scenario, object is provided through method e.g.
getShape() met hod
s.draw();
}
}
Output:
drawing circle
Abstract class having constructor, data member, methods
An abstract class can have data member, abstract method, method body, constructor and
even main() method.
Example2:
File: TestAbstraction2.java
//example of abstract class that have method body abstract class Bike{
Bike(){System.out.println("bike is created");} abstract void run();
void changeGear(){System.out.println("gear changed");}
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
class TestAbstraction2{
public static void main(String args[]){ Bike obj = new Honda();
obj.run(); obj.changeGear();
}
}
Output:
bike is created running safely.. gear changed
The abstract class can also be used to provide some implementation of the interface. In
such case, the end user may not be forced to override all the methods of the interface.
Example3:
interface A{ void a();
void b();
void c();
void d();
}
abstract class B implements A{
public void c(){System.out.println("I am c");}
}
class M extends B{
public void a(){System.out.println("I am a");} public void b(){System.out.println("I am
b");} public void d(){System.out.println("I am d");}
}
class Test5{
public static void main(String args[]){ A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output:
I am a I am b I am c I am d
Final keyword can be used along with variables, methods and classes.
1) final variable
2) final method
3) final class
1. Java final variable
A final variable is a variable whose value cannot be changed at anytime once assigned, it
remains as a constant forever.
Example:
public class Travel
{
final int SPEED=60;
void increaseSpeed(){
SPEED=70;
}
public static void main(String args[])
{
Travel t=new Travel();
t.increaseSpeed();
}
}
Output :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final field Travel.SPEED cannot be assigned
The above code will give you Compile time error, as we are trying to change the value of
a final
variable ‘SPEED’.
class Parent
{
public final void disp()
{
System.out.println("disp() method of parent class");
}
}
public class Child extends Parent
{
public void disp()
{
System.out.println("disp() method of child class");
}
public static void main(String args[])
{
Child c = new Child(); c.disp();
}
}
Output : We will get the below error as we are overriding the disp() method of the Parent
class. Exception in thread "main" java.lang.VerifyError: class
com.javainterviewpoint.Child overrides final method disp.()
at java.lang.ClassLoader.defineClass1(Native Method) at
java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source) at
java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source) at
java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
3. Java final class
A final class cannot be extended(cannot be subclassed), lets take a look into the below
example package com.javainterviewpoint;
1. What happens when the statement: int value = 25/0; is executed? (MAY/JUN 2016,
APR/MAY 2017, APR/MAY 2019)
2. Define runtime exceptions. (NOV/DEC 2018)
3. What is the use of assert keyword? (NOV/DEC 2018, NOV/DEC 2018)
4. Explain the types of exceptions in java. (NOV/DEC 2019)
5. Write a Java program to create user define exception. (APR/MAY 2017)
6. What is exception handling? Explain with an example exception handling in java.
(APR/MAY 2018)
7. Explain ‘Divide by zero’ Exception with an example. Java program. (APR/MAY 2019)
8. State the use of try block in Java exception handling. (NOV/DEC 2017)
9. Throw an exception if the matrices cannot be multiplied and handle it using a user
defined exception. (NOV/DEC 2017)
10. Discuss in detail on how exceptions are handled with an appropriate example.
(NOV/DEC 2019)
Errors indicate serious problems and abnormal conditions that most applications should not try
to handle. Error defines problems that are not expected to be caught under normal circumstances
by our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions. Few examples
• DivideByZero exception
• NullPointerException
• ArithmeticException
• ArrayIndexOutOfBoundsException
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled. If an exception is raised, which has not been handled by
programmer then program execution can get terminated and system prints a non-user-friendly
error message.
Ex: Exception in thread "main"
java.lang.ArithmeticException: / by zero at ExceptionDemo.main
(ExceptionDemo.java:5)
ExceptionDemo :
The class name main : The method
nameExceptionDemo.java : The
filename
java: 5: Line number
An exception can occur for many different reasons. Following are somescenarios where an exception
occurs.
• A user has entered an invalid data.
• A network connection has been lost in the middle of communications orthe JVM has run out
of memory.
Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class. Theexception class is a
subclassof the Throwable class.
1. try A try/catch block is placed around the code that might generate an
2. catch A catch statement involves declaring the type of exception we are trying
to catch.
Exception.
Output
Exception thrown :
java.lang.ArrayIndexOutOfBoundsException:3
First element value: 6
The finally statement is executed
Uncaught Exceptions
This small program includes an expression that intentionally causes a divide-by- zero
error: class Exc0 {
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}}
When the Java run-time system detects the attempt to divide by zero, it constructs a new
exception object and then throws this exception. This causes the execution of Exc0 to stop,
because once an exception has been thrown, it must be caught by an exception handler and
dealt with immediately Any exception that is not caught by your program will ultimately be
processed by the default handler. The default handler displays a string describing the exception,
prints a stack trace from the point at which the exception occurred, and terminates the
program.
Here is the exception generated when this example is
Exc0.main(Exc0.java:4)
Stack Trace
Stack Trace is a list of method calls from the point when the application was started to
the point where the exception was thrown. The most recent method calls are at the top. A
stacktrace is avery helpful debugging tool.
when an Exception was thrown. This is very useful because it doesn't only show you where the
error happened, but also how the program ended up in that place of the code. Using try and
Catch to guard against and handle a run-time error, simply enclose the code that you want to
monitor inside a try block. Immediately following the try block, include a catch clause that
specifies the exception type that you wish to catch. A try and its catch statement form a unit.
The following program includes a try block and a catch clause that processes the
ArithmeticException generated by the division-by-zero error
class Exc2
{
public static void main(String args[])
{
in
t
d,
a;
tr
y
{
// monitor a block of
code.d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by
zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output: Division by zero. After catch statement. The call
to println( ) inside the try block is never executed. Once an exception is thrown, program
control transfers out of the try block into the catch block.
3. PACKAGES AND INTERFACES
1. Describe the uses of interfaces in java?(NOV/DEC 2019)
2. What are the differences between classes and interfaces ? (NOV/DEC 2020)
Defining a Package
To create a package include a package command as the first statement in a Java source
file. Any classes declared within that file will belong to the specified package. The
package statement defines a name space in which classes are stored. If package
statement is omitted, the class names are put into the default package, which has no
name.
Syntax:
package <fully qualified package name>;
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a
package called MyPackage.
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any
classes you declare to be part of MyPackage must be stored in a directory called
MyPackage.
It is possible to create a hierarchy of packages. The general form of a multileveled
package statement is shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development
system. For example, a package declared as
package java.awt.image;
needs to be stored in java\awt\image in a Windows environment. We cannot rename a
package without renaming the directory in which the classes are stored.
First, by default, the Java run-time system uses the current working directory as its
starting point. Thus, if your package is in a subdirectory of the current directory, it will
be found. Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable. Third, you can use the - classpath option with java and javac to
specify the path to your classes.
When the second two options are used, the class path must not include MyPack,
itself. It must simply specify the path to MyPack. For example, in a Windows
environment, if the path to MyPack is C:\MyPrograms\Java\MyPack then the class path
to MyPack is C:\MyPrograms\Java
Example:
// A simple package package MyPack; class Balance { String name; double bal;
Balance(String n, double b) { name = n;
bal = b;
}
void show() { if(bal<0)
System.out.print("--> "); System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) { Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23); current[1] = new Balance("Will Tell",
157.02); current[2] = new Balance("Tom Jackson", -12.33); for(int i=0; i<3; i++)
current[i].show();
}
}
Call this file AccountBalance.java and put it in a directory called MyPack.
Next, compile the file. Make sure that the resulting .class file is also in the MyPack
directory. Then, try executing the AccountBalance class, using the following command
line:
java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this
command. (Alternatively, you can use one of the other two options described in the
preceding section to specify the path MyPack.)
As explained, AccountBalance is now part of the package MyPack. This means that it
cannot be executed by itself. That is, you cannot use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.
The above syntax will create the package given in the sourceFile at the <target location of pacakge>
if it is not yet created. If package already exist then only the .class (byte code file) will be stored to
the package given in sourceFile.
Compile the code with the command on the command prompt. javac -d
DemoPackage.java
1. The command will create the package at the current location with the name pck1, and
contains the file DemoPackage.class and Student.class
Note: The DemoPackate.class is now stored in pck1 package. So that we've to use fully qualified
type name to run or access it.
Output:
Roll No :: 1001 Name :: Alice
Address :: New York Roll No ::
1002 Name :: Bob
Address :: Washington
Interfaces
An interface in java is a blueprint of a class. It has static constants and abstract methods.The
interface in java is a mechanism to achieve abstraction and multiple inheritance.
Interface is declared by using interface keyword. It provides total abstraction; means all the
methods in interface are declared with empty body and are public and all fields are public, static
and final by default. A class that implement interface must implement all the methods declared in
the interface.
Syntax:
interface <interface_name>
{
Interface inheritance
A class implements interface but one interface extends another interface . Example: interface
Printable{ void print();
}
interface Showable extends Printable{ void show();
}
class TestInterface4 implements Showable{ public void
print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");} public static void main(String args[]){
TestInterface4 obj = new TestInterface4(); obj.print();
obj.show();
}}
Output:
Hello Welcome
An interface can have another interface i.e. known as nested interface. interface printable{
void print();
interface MessagePrintable{ void msg();
}
}
• Without bothering about the implementation part, we can achieve the security of
implementation
• In java, multiple inheritance is not allowed, however you can use interface to make use of it
as you can implement more than one interface.
I/O STREAMS
Java I/O (Input and Output) is used to process the input and produce the output based on the input.
Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes
required for input and output operations.
A stream can be defined as a sequence of data. there are two kinds of Streams
Java byte streams are used to perform input and output of 8-bit bytes FileInputStream , FileOutputStream.
Character Streams
Java Character streams are used to perform input and output for 16-bit unicode. FileReader , FileWriter
Standard Streams
• Standard Input: This is used to feed the data to user's program and usually a keyboard is used
as standard input stream and represented as System.in.
• Standard Output: This is used to output the data produced by the user's program and usually a
computer screen is used to standard output stream and represented as System.out.
• Standard Error: This is used to output the error data produced by the user's program and
usually a computer screen is used to standard error stream and represented as System.err.
Classification of Stream Classes
ByteStream classes have been designed to provide functional features for creating and manipulating
streams and files for reading and writing bytes. Since the streams are unidirectional, they can transmit bytes
in only one direction and therefore, Java provides two kinds of byte stream classes: InputStream class and
OutputStream class.
Input stream classes that are used to read 8-bit bytes include a super class known as InputStream and
number of subclasses for supporting various input- related functions.
The super class InputStream is an abstract class, so we cannot create object for the class.
InputStream class defines the methods to perform the following functions:-
• Reading Bytes
• Closing Streams
• Marking position in Streams
• Skipping ahead in streams
• Finding the number of bytes in stream.
OutputStream Class
The super class InputStream is an abstract class, so we cannot create object for the class.
InputStream class defines the methods to perform the following functions:
• Writing Bytes
• Closing Streams
• Flushing Streams
Hierarchy of Output Stream Classes
OutputStream Method
A stream is a method to sequentially access a file. I/O Stream means an input source or
output destination representing different types of sources e.g. disk files.The java.io package
provides classes thatallow you to convert between Unicode character streams and byte streams of
non-Unicode text.
Stream
Java BufferedInputStream class is used to read information from stream. It internally uses
buffermechanism to make the performance fast.
1. When the bytes from the stream are skipped or read, the internal buffer automatically
refilled from thecontained input stream, many bytes at a time.
import java.io.*;
public class
BufferedInputStreamExample{
args[]){
try{
FileInputStream fin=new
FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new
BufferedInputStream(fin);
int i;
while((i=bin.re
ad())!=-1){
System.out.prin
t((char)i);
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer
to storedata. It adds more efficiency than to write data directly into a stream. So, it makes the
performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the
syntax foradding the buffer in an OutputStream:
import java.io.*;
byte
b[]=s.getByte
s();
bout.write(b)
; bout.flush();
bout.close();
fout.close();