Академический Документы
Профессиональный Документы
Культура Документы
Java Array
Java array is an object the contains elements of similar data type. It is a data
structure where we store similar elements. We can store only fixed set of elements
in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Random access: We can get any data located at any index position.
Disadvantage of Java Array
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.
Multidimensional Array
In such case, data is stored in row and column based index (also known as matrix
form).
Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.
1. class Testarray3{
2. public static void main(String args[]){
3. //declaring and initializing 2D array
4. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
5. //printing 2D array
6. for(int i=0;i<3;i++){
7. for(int j=0;j<3;j++){
8. System.out.print(arr[i][j]+" ");
9. }
10. System.out.println();
11. }
12. }}
Output:1 2 3
2 4 5
4 4 5
JAVA INHERITANCE
Inheritance in Java
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.Inheritance represents the IS-A relationship, also
known as parent-child relationship.
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
The extends keyword indicates that you are making a new class that derives from
an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new
class is called a subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. Relationship between two classes is Programmer IS-A Employee.It
means that Programmer is a type of Employee.
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. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well
as of Employee class i.e. code reusability.
When a class extends multiple classes i.e. known as multiple inheritance. For
Example:
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.
Since compile time errors are better than runtime errors, java renders compile time
error if you inherit 2 classes. So whether you have same method or different, there
will be compile time error now.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Compile Time Error
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract
methods only.
The java compiler adds public and abstract keywords before the interface method
and public, static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods
are public and abstract.
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface
extends another interface but a class implements an interface.
In this example, Printable interface have only one method, its implementation is
provided in the A class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6. public static void main(String args[]){
7. A6 obj = new A6();
8. obj.print();
9. }
10. }
Output:Hello
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void show();
7. }
8.
9. class A7 implements Printable,Showable{
10.
11. public void print(){System.out.println("Hello");}
12. public void show(){System.out.println("Welcome");}
13.
14. public static void main(String args[]){
15. A7 obj = new A7();
16. obj.print();
17. obj.show();
18. }
19. }
Output:Hello
Welcome
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void print();
7. }
8.
9. class testinterface1 implements Printable,Showable{
10.
11. public void print(){System.out.println("Hello");}
12.
13. public static void main(String args[]){
14. testinterface1 obj = new testinterface1();
15. obj.print();
16. }
17. }
Test it Now
Hello
As you can see in the above example, Printable and Showable interface have same
methods but its implementation is provided by class A, so there is no ambiguity.
Interface inheritance
A class implements interface but one interface extends another interface .
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class Testinterface2 implements Showable{
8.
9. public void print(){System.out.println("Hello");}
10. public void show(){System.out.println("Welcome");}
11.
12. public static void main(String args[]){
13. Testinterface2 obj = new Testinterface2();
14. obj.print();
15. obj.show();
16. }
17. }
Test it Now
Hello
Welcome
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
Java Package
1. Java Package
2. Example of package
3. Accessing package
1. By import packagename.*
2. By import packagename.classname
4. Subpackage
6. -classpath switch
9. Static Import
Package in java can be categorized in two form, built-in package and user-defined
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.
Here, we will have the detailed learning of creating and using user-defined
packages.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You
can use any directory name like /home (in case of Linux), d:/abc (in case of
windows) etc. If you want to keep the package within the same directory, you can
use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination. The . represents the current folder.
How to access package from another
package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
The import keyword is used to make the classes and interface of another
package accessible to the current package.
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
If you import a package, all the classes and interface of that package will be
imported excluding the classes and interfaces of the subpackages. Hence, you need
to import the subpackage as well.
Subpackage in java
Package inside the package is called the subpackage. It should be created to
categorize the package further.
Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These
classes represent a particular group e.g. Reader and Writer classes are for
Input/Output operation, Socket and ServerSocket classes are for networking etc
and so on. So, Sun has subcategorized the java package into subpackages such as
lang, net, io etc. and put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
Output:Hello subpackage
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the
directory where the class file resides.
To run this program from e:\source directory, you can use -classpath switch of
java that tells where to look for class file. For example:
Output:Welcome to package
Temporary
o By -classpath switch
Permanent
o By creating the jar file, that contains all the class files, and copying the
jar file in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by
the public class name.
1. //save as C.java otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}
1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}
The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is
why we use exception handling. Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says there are three
types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between checked and
unchecked exceptions
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException, SQLException etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.
3) Error
int a=50/0;//ArithmeticException
If we have null value in any variable, performing any operation by the variable
occurs an NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
String s=null;
System.out.println(s.length());//N
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
String s="abc";
int i=Integer.parseInt(s);//Numbe
4) Scenario where ArrayIndexOutOfBoundsException
occurs
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
a[10]=50; //ArrayIndexOutOfBoundsException
1. try
2. catch
3. finally
4. throw
5. throws
Java try-catch
Output:
As displayed in the above example, rest of the code is not executed (in such case,
rest of the code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will
not be executed.
Output:
Now, as displayed in the above example, rest of the code is executed i.e. rest of the
code... statement is printed.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Output:task1 completed
rest of the code...
Rule: At a time only one Exception is occured and at a time only one catch block is
executed.
Rule: All catch blocks must be ordered from most specific to most general i.e. catch
for ArithmeticException must come before catch for Exception .
1. class TestMultipleCatchBlock1{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 co
mpleted");}
10. System.out.println("rest of the code...");
11. }
12. }
Test it Now
Output:
Compile-time error
Sometimes a situation may arise where a part of a block may cause one error and
the entire block itself may cause another error. In such cases, exception handlers
have to be nested.
Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
Java nested try example
Let's see a simple example of java nested try block.
1. class Excep6{
2. public static void main(String args[]){
3. try{
4. try{
5. System.out.println("going to divide");
6. int b =39/0;
7. }catch(ArithmeticException e){System.out.println(e);}
8.
9. try{
10. int a[]=new int[5];
11. a[5]=4;
12. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
13.
14. System.out.println("other statement);
15. }catch(Exception e){System.out.println("handeled");}
16.
17. System.out.println("normal flow..");
18. }
19. }
Case 1
Let's see the java finally example where exception doesn't occur.
1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Test it Now
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Test it Now
Case 3
Let's see the java finally example where exception occurs and handled.
Rule: For each try block there can be zero or more catch blocks, but only one finally
block.
Note: The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort).
We can throw either checked or uncheked exception in java by throw keyword. The
throw keyword is mainly used to throw custom exception. We will see custom
exceptions later.
1. throw exception;
Output: