Вы находитесь на странице: 1из 23

 Abstract Class  Interface

 An abstract class can extend only one  An interface can extend any number of interfaces at a
1
class or one abstract class at a time time

  An abstract class can extend another


2  An interface can only extend another interface
concrete (regular) class or abstract class

 An abstract class can have both abstract
3  An interface can have only abstract methods
and concrete methods

 In abstract class keyword “abstract” is


 In an interface keyword “abstract” is optional to
4 mandatory to declare a method as an
declare a method as an abstract
abstract

 An abstract class can have protected and  An interface can have only have public abstract
5
public abstract methods methods

 An abstract class can have static, final or


 interface can only have public static final (constant)
6 static final variable with any access
variable
specifier

Access Specifiers in JAVA

An access modifier restricts the access of a class, constructor, data member and method in another class.
In java we have four access modifiers:
1. default
2. private
3. protected
4. Public

1. Default access modifier

When we do not mention any access modifier, it is called default access modifier. The scope of this
modifier is limited to the package only. This means that if we have a class with the default access modifier
in a package, only those classes that are in this package can access this class. No other class outside this
package can access this class. 

package abcpackage;
public class Addition {
/* Since we didn't mention any access modifier here, it would
* be considered as default.
*/
int addTwoNumbers(int a, int b){
return a+b;
}
}
Test.java

package xyzpackage;

/* We are importing the abcpackage


* but still we will get error because the
* class we are trying to use has default access
* modifier.
*/
import abcpackage.*;
public class Test {
public static void main(String args[]){
Addition obj = new Addition();
/* It will throw error because we are trying to access
* the default method in another package
*/
obj.addTwoNumbers(10, 21);
}
}
Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:


The method addTwoNumbers(int, int) from the type Addition is not visible
at xyzpackage.Test.main(Test.java:12)

2. Private access modifier

The scope of private modifier is limited to the class only.

1. Private Data members and methods are only accessible within the class

2. Class and Interface cannot be declared as private

3. If a class has private constructor then you cannot create the object of that class from outside of the
class.
Example

class ABC{
private double num = 100;
private int square(int a){
return a*a;
}
}
public class Example{
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
Output:

Compile - time error

3. Protected Access Modifier

Protected data member and method are only accessible by the classes of the same package and the
subclasses present in any package. You can also say that the protected access modifier is similar to
default access modifier with one exception that it has visibility in sub classes.
Classes cannot be declared protected. This access modifier is generally used in a parent child
relationship.

4. Public access modifier

The members, methods and classes that are declared public can be accessed from anywhere. This
modifier doesn’t put any restriction on the access.

The scope of access modifiers in tabular form

------------+-------+---------+--------------+--------------+--------
| Class | Package | Subclass | Subclass |Outside|
————————————+———————+———
public | Yes | Yes | Yes | Yes | Yes |
————————————+———————+————
protected | Yes | Yes | Yes | Yes | No |
————————————+———————+———
default | Yes | Yes | Yes | No | No |
————————————+———————+———
private | Yes | No | No | No | No |
------------+-------+---------+--------------+--------------+-------

Continue Statement in Java

Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control
directly jumps to the beginning of the loop for next iteration, skipping the execution of statements inside
loop’s body for the current iteration.

public class ContinueExample {

public static void main(String args[]){


for (int j=0; j<=6; j++)
{
if (j==4)
{
continue;
}

System.out.print(j+" ");
}
}
}
Output:
012356

Break Statement in Java

The break statement is usually used in following two scenarios:

a) Use break statement to come out of the loop instantly. Whenever a break statement is encountered
inside a loop, the control directly comes out of loop and the loop gets terminated for rest of the iterations.
It is used along with if statement, whenever used inside loop so that the loop gets terminated for a
particular condition.

The important point to note here is that when a break statement is used inside a nested loop, then only
the inner loop gets terminated.

b) It is also used in switch case control. Generally all cases in switch case are followed by a break
statement so that whenever the program control jumps to a case, it doesn’t execute subsequent cases
(see the example below). As soon as a break is encountered in switch-case block, the control comes out of
the switch-case body.
----------------------------------------------------------------------------------------------------------------------------------

Java static import with example

Static import allows you to access the static member of a class directly without using the fully qualified
name.

Lets understand this with the help of examples:

Example 1: Without Static Imports

class Demo1{

public static void main(String args[])

double var1= Math.sqrt(5.0);

double var2= Math.tan(30);

System.out.println("Square of 5 is:"+ var1);

System.out.println("Tan of 30 is:"+ var2);

Output:

Square of 5 is:2.23606797749979

Tan of 30 is:-6.405331196646276

Example 2: Using Static Imports

import static java.lang.System.out;

import static java.lang.Math.*;

class Demo2{

public static void main(String args[])

//instead of Math.sqrt need to use only sqrt


double var1= sqrt(5.0);

//instead of Math.tan need to use only tan

double var2= tan(30);

//need not to use System in both the below statements

out.println("Square of 5 is:"+var1);

out.println("Tan of 30 is:"+var2);

Output:

Square of 5 is:2.23606797749979

Tan of 30 is:-6.405331196646276

Error Handling Exception Classes


In previous Section of this Chapter, we have listed the different classes for handling
exceptions in Java. In this Section, let us get a brief introduction about the main of them :

ArithmeticException: An ArithmeticException is thrown if one try to divide an integer by zero


or take a modules by zero. For example, the following code causes an ArithmeticException to
be thrown:

int wrongMath ( ) {
int n = 100;
int result ;
for (int i = 9; i > -1; i- - )
result = n % i; // modulo remainder.
return (result );
}

ArrayIndexOutofBoundsException : In ArrayIndexOutofBoundsException is thrown when one


try to access an array element that is out of bounds, meaning that one using an index of less
than zero or greater than or equal to the size of the array. Here is a token example that would
throw an ArrayIndexOutofBoundsException :

void wrongArrayAccess ( ) {
int anArray = new int[10] ; // An array of size having index 0,1,..,9

��..
anArray[10] = 999 ; // index out of range
}

ArrayStoreException : This exception occurs when one try to store a value into an array of
incompatible class or type. Following is an example where ArrayStoreException will be
thrown.

void badArrayStore ( ) {
int storeArray = new int[15]; // An array of integers
boolean boolArray =new boolean[5]; // An array of booleans
System.arraycopy(storeArray, 2, boolArrary, 2, 4);
// Copy the element boolArray[3,4,5] into storeArray
starting at storeArray[2]
}

ClassCastException : In Java, an instance of a class of one type can be possible to cast for
another type. Here an instance of class can be casted to its super class but one can not cast
an instance of class to its subclasses. If one attempt this cast, a ClassCastException will
occur. The following example, results a ClassCastException at run time :

class ClassA { // a token of a simple class

���
}

class ClassB extends ClassA{ // A sub class of ClassA

���.
void bMethod ( ) { . . . . }
}
class Test {
void wrongCast ( ) {
ClassA anInstanceA = new ClassA( );
ClassB anInstanceB = (Class B ) anInstanceA; // Exception
anInstanceB.bMethod ( );
}
}

IllegalArgumentException : This IllegalArgumentException occurs when one attempt to pass


a parameter that is not in valid range or value for the method. The following method throws
an IllegalArgumentException if passed an illegal parameter value:

static void wrongArgumentPass (int agru ) {


if (argu == 0)
throw new IllegalArgumentException ( "Argument cannot be 0 ");
int x = 555 / argu;
}

Not that, in the above example, method wrongArgumentPass(int) throws an exception when
caller passes unacceptable value.
IllegalThreadStateException : This exception is thrown by some methods in the system
package classes when one try to illegally change the state of thread, for example, by trying
to start a thread that is already running.

IndexOutofBoundsException : This exception can be thrown in a method when one passed


an index value that is out side an acceptable range. Example is already visited in ealier
discussions.

NegativeArraySizeException : This exception is thrown when an array with a negative size is


attempted to be allocated. The following method results in a NegativeArraySizeException at
run time :

Void negativeSizeArray ( ) {
int theSize = -5;
int foolArray = new int[theSize];
}
NullPointerException : This exception is thrown when one attempt to use a method or
variable in a variable name that contains a null object reference. The following method
results in a NullPointerException at run time:

void nullPointer ( ) {
String myString = null; // myString is a null reference object
if ( myString.equals (" Sahara" )) {
System.out.println (" Howz!"); }
}

NumberFormatException : This exception is thrown by some methods in classes of System


package when one try to convert an invalid string to a number or vice versa.

SecurityException : This exception is thrown by some methods in the System package when
one attempt to call a method that will perform an action not allowed by the current security
settings of the browser within which the applet code is running. It can also be thrown if the
program denies permission when prompted whether to allow an action such as writing to a
file.

StringIndexOutOfBoundsException : A StringIndexOutOfBoundsException is thrown when


one try to access a character that is out of the bounds of a string, meaning that using an
index of less than zero or greater than or equal to the length of the string. Following is an
example that would throw a StringIndexOutOfBoundException :

void wrongStringIndex ( ) {
String theString = " N E R I S T",
char theChar = theString.charat(20); // Index should be between 0 and 10
}

ClassNoFoundException : This exception is thrown by the class loader when a class file is
not found when a class is attempted to be instantiated.

DataFormatException : This exception is thrown when data being read from a string appears
to be in an invalid format.

IllegalAccessException : This exception is thrown by methods in java.lang class when


instantiating a class by its name if the class is not public or there is no public constructor.
One might encounter this exception if calling a method that, in turn, calls one of these
methods.
InstantiationException : This exception is thrown when an attempt is made to instantiate an
abstract class, primarily by methods in java.lang class when instantiating a class by its
name.

InterruptedException : This exception is thrown within a thread when it is interrupted by


some other thread. This exception will be illustrated during the discussion of Thread in Java.

NoSuchMethodException : This exception is thrown when a particular method in an object or


class cannot be found

Example Program

Here is an example program. Notice that methodA has two try/catch structures. The first uses
the static method parseInt() of class Integer to convert a string of characters into a
primitive int.

If the string can't be converted, parseInt() throws a NumberFormatException.

The second try/catch structure calls methodB, which might throw


an ArithmeticException. If that happens, the second catch{} will handle it.

The clause throws ArithmeticException in the header of methodB() is not


required, because ArithmeticExceptions are not checked.

import java.lang.* ;
import java.io.* ;

public class BuckPasser


{
public static int methodB( int divisor ) throws ArithmeticException
{
int result = 12 / divisor; // may throw an ArithmeticException
return result;
}

public static void methodA( String input )


{
int value = 0;

try
{
value = Integer.parseInt( input ); // Convert the string to an
int.
// May throw a
NumberFormatException
}
catch ( NumberFormatException badData )
{
System.out.println( "Bad Input Data!!" );
return; // this is necessary; without it control will continue
with the next try.
}

try
{
System.out.println( "Result is: " + methodB( value ) );
}
catch ( ArithmeticException zeroDiv )
{
System.out.println( "Division by zero!!" );
}

public static void main ( String[] a )


{
Scanner scan = new Scanner( System.in );
String inData;

System.out.print("Enter the divisor: ");


inData = scan.next(); // Read a string from standard input
methodA( inData ); // send the string to methodA
}
}

What is JUnit Annotations?

Annotation is a special form of syntactic meta-data that can be added to Java source code for better code
readability and structure. Variables, parameters, packages, methods and classes can be annotated.

Below is the list of important and frequently used annotations:

@Before

@Before: When writing tests, it is common to find that several tests need similar objects created before
they can run. Annotating a public void method with @Before causes that method to be run before the
Test method. The @Before methods of super classes will be run before those of the current class.

@BeforeClass

@BeforeClass: Sometimes several tests need to share computationally expensive setup (like logging into
a database). While this can compromise the independence of tests, sometimes it is a necessary
optimization. Annotating a public static void no-arg method with @BeforeClass causes it to be run once
before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before
those the current class.

The annotations @BeforeClass and @Before are same in functionality. The only difference is the method
annotated with @BeforeClass will be called once per test class based, and the method annotated with
@Before will be called once per test based.

@After

@After: If you allocate external resources in a Before method you need to release them after the test runs.
Annotating a public void method with @After causes that method to be run after the Test method. All @After
methods are guaranteed to run even if a Before or Test method throws an exception. The @After methods
declared in superclasses will be run after those of the current class.

@AfterClass

@AfterClass: If you allocate expensive external resources in a BeforeClass method you need to release
them after all the tests in the class have run. Annotating a public static void method with @AfterClass
causes that method to be run after all the tests in the class have been run. All @AfterClass methods are
guaranteed to run even if a BeforeClass method throws an exception. The @AfterClass methods declared
in superclasses will be run after those of the current class.
The annotations @AfterClass and @After are same in functionality. The only difference is the method
annotated with @AfterClass will be called once per test class based, and the method annotated with
@After will be called once per test based.

@Test

@Test: The Test annotation tells JUnit that the public void method to which it is attached can be run as a test
case. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method.
Any exceptions thrown by the test will be reported by JUnit as a failure. If no exceptions are thrown, the test is
assumed to have succeeded.

@Test(timeout=500)

@Test(timeout=100): Somethimes we need to mesure the performance in terms of time. The @Test annotations
provides an optional parameter called 'timeout', which causes a test to fail if it takes longer than a specified
amount of clock time (measured in milliseconds).

@Test(expected=IllegalArgumentException.class)

Sometimes we need to test the exception to be thrown by the test. @Test annotation provides a
parameter called 'expected', declares that a test method should throw an exception. If it doesn't throw an
exception or if it throws a different exception than the one declared, the test fails.

@Ignores

Sometimes you want to temporarily disable a test or a group of tests. Methods annotated with Test that
are also annotated with @Ignore will not be executed as tests. Also, you can annotate a class containing
test methods with @Ignore and none of the containing tests will be executed. Native JUnit 4 test runners
should report the number of ignored tests along with the number of tests that ran and the number of
tests that failed.

You can also use @Ignore annotation at class level.

This annotation can be used if you want to ignore some statements during test execution for e.g. disabling
some test cases during test execution.

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or
uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be
initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be constant).

2) Java final method

If you make any method as final, you cannot override it.

3) Java final class

If you make any class as final, you cannot extend it.

Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it.

Q) What is blank or uninitialized final variable?


A final variable that is not initialized at the time of declaration is known as blank final variable.

If you want to create a variable that is initialized at the time of creating object and once initialized may
not be changed, it is useful. For example PAN CARD number of an employee.

It can be initialized only in constructor.

Example of blank final variable


1. class Student{  
2. int id;  
3. String name;  
4. final String PAN_CARD_NUMBER;  
5. ...  
6. }  

Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:

1. class Bike10{  
2.   final int speedlimit;//blank final variable  
3.     
4.   Bike10(){  
5.   speedlimit=70;  
6.   System.out.println(speedlimit);  
7.   }  
8.   
9.   public static void main(String args[]){  
10.     new Bike10();  
11.  }  
12. }  
Test it Now
Output: 70

Q) Can we declare a constructor final?


No, because constructor is never inherited.

static blank final variable


A static final variable that is not initialized at the time of declaration is known as static blank final variable.
It can be initialized only in static block.

1)What value does readLine() return when it has reached the end of a file?

ANS: The readLine() method returns null when it has reached the end of a file.

2)What value does readLine() return when it has reached the end of a file?

Here is the real definition of InputStream.read() ... as defined in the javadoc:

"public abstract int read() throws IOException

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to
255. If no byte is available because the end of the stream has been reached, the value -1 is returned."

3) What are the two types of I/O available in Java?

Java IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make
input and output operation in java. In general, a stream means continuous flow of data. Streams are
clean way to deal with input/output without having every part of your code understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,

1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.

Java Byte Stream Classes


Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and
OutputStream.

These two abstract classes have several concrete classes that handle various devices such as disk
files, network connection etc.

Some important Byte stream classes.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStrea Used for Buffered Output Stream.


m

DataInputStream Contains method for reading java


standard datatype

DataOutputStream An output stream that contain


method for writing java standard
data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream


input.

OutputStream Abstract class that describe stream


output.

PrintStream Output Stream that


contain print() and println() method

These classes define several key methods. Two most important are

1. read() : reads byte of data.


2. write() : Writes byte of data.

Java Character Stream Classes


Character stream is also defined by using two abstract class at the top of hierarchy, they are Reader
and Writer.

These two abstract classes have several concrete classes that handle unicode character.

Some important Charcter stream classes


Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

Reading Console Input


We use the object of BufferedReader class to take inputs from the keyboard.
Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns integer
type value has we need to use typecasting to convert it into char type.
int read() throws IOException

Below is a simple example explaining character input.


class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}

Reading Strings in Java

To read string we have to use readLine() function with BufferedReader class's object.


String readLine() throws IOException

Program to take String input from Keyboard in Java


import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}

Program to read from a file using BufferedReader class


import java. Io *;
class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}

Program to write to a File using FileWriter class


import java. Io *;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}

Serialization and Deserialization in Java

Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly
used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization where byte-stream is converted into an


object. The serialization and deserialization process is platform-independent, it means you can serialize an
object in a platform and deserialize in different platform.

For serializing the object, we call the writeObject() method ObjectOutputStream, and for deserialization


we call the readObject() method of ObjectInputStream class.

java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so
that the objects of these classes may get a certain capability. The Cloneable and Remote are also marker
interfaces.

It must be implemented by the class whose object you want to persist.

The String class and all the wrapper classes implement the java.io.Serializable interface by default.

Let's see the example given below:

1. import java.io.Serializable;  
2. public class Student implements Serializable{  
3.  int id;  
4.  String name;  
5.  public Student(int id, String name) {  
6.   this.id = id;  
7.   this.name = name;  
8.  }  
9. }  
In the above example, Student class implements Serializable interface. Now its objects can be converted
into stream.

Example of Java Serialization

In this example, we are going to serialize the object of Student class. The writeObject() method of
ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the
object in the file named f.txt.

1. import java.io.*;  
2. class Persist{  
3.  public static void main(String args[]){  
4.   try{  
5.   //Creating the object  
6.   Student s1 =new Student(211,"ravi");  
7.   //Creating stream and writing the object  
8.   FileOutputStream fout=new FileOutputStream("f.txt");  
9.   ObjectOutputStream out=new ObjectOutputStream(fout);  
10.   out.writeObject(s1);  
11.   out.flush();  
12.   //closing the stream  
13.   out.close();  
14.   System.out.println("success");  
15.   }catch(Exception e){System.out.println(e);}  
16.  }  
17. }  

Example of Java Deserialization


1. import java.io.*;  
2. class Depersist{  
3.  public static void main(String args[]){  
4.   try{  
5.   //Creating stream to read the object  
6.   ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));  
7.   Student s=(Student)in.readObject();  
8.   //printing the data of the serialized object  
9.   System.out.println(s.id+" "+s.name);  
10.   //closing the stream  
11.   in.close();  
12.   }catch(Exception e){System.out.println(e);}  
13.  }  
14. }  

Java Transient Keyword


Java transient keyword is used in serialization. If you define any data member as transient, it will not
be serialized.

Let's take an example, I have declared a class as Student, it has three data members id, name and age. If
you serialize the object, all the values will be serialized but I don't want to serialize one value, e.g. age
then we can declare the age data member as transient.

Вам также может понравиться