JAVA New
JAVA New
Introduction to JAVA
1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These are traditional
software that we need to install on every machine. Examples of standalone application are Media player, antivirus, etc.
AWT and Swing are used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application. Currently, Servlet,
JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called enterprise application. It has
advantages of the high-level security, load balancing, and clustering. In Java, EJB is used for creating enterprise
applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android and Java ME are
used for creating mobile applications.
Java is an Object Oriented language
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects.
Abstraction: Hiding internal details and showing functionality is known as abstraction. For example
phone call, we don't know the internal processing. In Java, we use abstract class and interface to
achieve abstraction.
Encapsulation: Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines. A java class is the
example of encapsulation. Java bean is the fully encapsulated class because all the data members are
private here.
What is the difference between an
object-oriented programming language
and object-based programming language?
Mainly used for C++ is mainly used for system Java is mainly used for application programming. It is widely used in
programming. window, web-based, enterprise and mobile applications.
Design Goal C++ was designed for systems and Java was designed and created as an interpreter for printing systems but
applications programming. It was an later extended as a support network computing. It was designed with a goal
extension of of being easy to use and accessible to a broader audience.
C programming language.
Goto C++ supports the goto statement. Java doesn't support the goto statement.
Multiple inheritance C++ supports multiple inheritance. Java doesn't support multiple inheritance through class. It can be achieved
by interfaces in java.
Operator Overloading C++ supports operator overloading. Java doesn't support operator overloading.
Pointers C++ supports pointers. You can Java supports pointer internally. However, you can't write the pointer
write pointer program in C++. program in java. It means java has restricted pointer support in java.
Compiler and Interpreter C++ uses compiler only. C++ is Java uses compiler and interpreter both. Java source code is converted into
compiled and run using the compiler bytecode at compilation time. The interpreter executes this bytecode at
which converts source code into runtime and produces output. Java is interpreted that is why it is platform
machine code so, C++ is platform independent.
dependent.
Call by Value and Call by C++ supports both call by value and call by Java supports call by value only. There is no
reference reference. call by reference in java.
Structure and Union C++ supports structures and unions. Java doesn't support structures and unions.
Thread Support C++ doesn't have built-in support for threads. It Java has built-in thread support.
relies on third-party libraries for thread support.
Documentation comment C++ doesn't support documentation comment. Java supports documentation comment (/** ...
*/) to create documentation for java source
code.
Virtual Keyword C++ supports virtual keyword so that we can decide Java has no virtual keyword. We can override
whether or not override a function. all non-static methods by default. In other
words, non-static methods are virtual by
default.
unsigned right shift >>> C++ doesn't support >>> operator. Java supports unsigned right shift >>>
operator that fills zero at the top for the
negative numbers. For positive numbers, it
works same like >> operator.
Inheritance Tree C++ creates a new inheritance tree always. Java uses a single inheritance tree always
because all classes are the child of Object class
in java. The object class is the root of the
inheritance tree in java.
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have different
meaning in Java.
Class Names − For all class names the first letter should be in Upper Case. If several words are used to
form a name of the class, each inner word's first letter should be in Upper Case. Example: class
MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter. If several words are used to
form the name of the method, then each inner word's first letter should be in Upper Case. Example:
public void myMethodName()
Program File Name − Name of the program file should exactly match the class name. When saving the
file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the
end of the name (if the file name and the class name do not match, your program will not compile).
But please make a note that in case you do not have a public class present in the file then file name can be
different than class name. It is also not mandatory to have a public class in the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the main() method which
is a mandatory part of every Java program.
Java Identifiers
All Java components require names. Names used for classes, variables, and methods
are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows −
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or
an underscore (_).
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
Java Modifiers
prefix ++expr --expr +expr -expr ~ !
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Output: 22
21
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);
System.out.println(~b);
System.out.println(!c);
System.out.println(!d);
}}
Output:-11 (minus of total positive value which starts from 0)
9 (positive of total minus, positive starts from 0)
false (opposite of boolean value)
true
Arithmetic operator
class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}
Output: 21
Type Casting in Java
Type casting is used to convert an object or variable of one type into another.
Syntax: dataType variableName = (dataType) variableToConvert;
There are two casting directions: narrowing (larger to smaller type) and
widening (smaller to larger type). Widening can be done automatically (for
example, int to double), but narrowing must be done explicitly (like double to
int).
Widening or Automatic Type Conversion: Widening conversion takes place
when two data types are automatically converted. This happens when:
1. The two data types are compatible.
2. When we assign value of a smaller data type to a bigger data type.
Example:
class Test
{
public static void main(String[] args)
{
int i = 100;
//automatic type conversion
long l = i;
//automatic type conversion
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f); } }
If we want to assign a value of larger data type to a smaller data type we perform explicit
type casting or narrowing.
This is useful for incompatible data types where automatic conversion cannot be done.
Here, target-type specifies the desired type to convert the specified value to.
Example:
//Java program to illustrate incompatible data
// type for explicit type conversion
public class Test
{
public static void main(String[] argv)
{
char ch = 'c';
int num = 88;
ch = num;
}
}
Output:error: incompatible types: possible lossy conversion from int to char
ch = num;
^
1 error
Explicit Conversion
//Java program to illustrate explicit type conversion
class Test
{ public static void main(String[] args)
{ double d = 100.04;
//explicit type casting
long l = (long)d;
//explicit type casting
int i = (int)l;
System.out.println("Double value "+d);
//fractional part lost
System.out.println("Long value "+l);
//fractional part lost
System.out.println("Int value "+i); } }
The Java break is used to break loop or switch statement. It breaks the
current flow of the program at specified condition. In case of inner loop, it
breaks only inner loop.
For Loops
class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
}
}
}
Output: The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2
For loop example to iterate an array:
Here we are iterating and displaying array elements using the for loop.
class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
}
Output: 2
11
45
9
Enhanced For loop
Enhanced for loop is useful when you want to iterate Array/Collections, it is
easy to write and understand.
class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
for (int num : arr) {
System.out.println(num);
}
}
Output:
} 2
11
45
9
Practice for loop
Write a Java Program to find sum of natural numbers using for loop.
Write a Java Program to find factorial of a number using loops.
Write a Java Program to print Fibonacci Series using for loop.
While Loop
class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.println(i);
i--;
} } }
Output:10
9
8
7
6
5
4
3
2
Practice while loop
Output: 0 1 2 3 5 6
Object and class example
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
Output: 0
System.out.println(s1.name);
null
}
}
main outside the class
//Java Program to demonstrate having the main method in
//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id); Output: 0
System.out.println(s1.name); null
}
}
Ways to initialize object
1. By reference variable
2. By method
3. By constructor
By reference variable
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name=“Balagurusamy";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
Output: 101 Balagurusamy
}
By method
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n; }
void displayInformation(){System.out.println(rollno+" "+name); } }
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan"); Output: 111 Karan
222 Aryan
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation(); } }
Constructor
In order to overload a method, the argument lists of the methods must differ in either of
these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
Example 1: Overloading – Different Number of parameters in argument list
class DisplayOverloading
{ public void disp(char c)
{
System.out.println(c); }
public void disp(char c, int num) {
System.out.println(c + " "+num);
} }
class Sample
{ public static void main(String args[])
{ DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10); Output:a
} } a 10
Example 2: Overloading – Difference in data type of parameters
class DisplayOverloading2
{ public void disp(char c)
{ System.out.println(c); }
public void disp(int c)
{ System.out.println(c ); } }
class Sample2
{ public static void main(String args[])
{ DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5); } }
Output : a
5
Example3: Overloading – Sequence of data type of arguments
class DisplayOverloading3
{ public void disp(char c, int num)
{ System.out.println("I’m the first definition of method disp” +c);
}
public void disp(int num, char c)
{ System.out.println("I’m the second definition of method disp” + c );
} }
class Sample3
{ public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
Output: I’m the first definition of method disp 51
obj.disp(52, 'y'); } } I’m the second definition of method disp 52
Constructor overloading
Usage of java this keyword: Here is given the 6 usage of java this keyword.
Static keyword can be used with class, variable, method and block. Static members belong to the
class instead of a specific instance, this means if you make a member static, you can access it
without object.
The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block
Nested class
Java static variable
If you declare any variable as static, it is known as a static variable.
The static variable can be used to refer to the common property of all objects (which is not unique for each
object), for example, the company name of employees, college name of students, etc.
The static variable gets memory only once in the class area at the time of class loading.
Advantages of static variable: It makes your program memory efficient (i.e., it saves memory).
Understanding the problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get memory each time
when the object is created. All students have its unique rollno and name, so instance data member is good in
such case. Here, "college" refers to the common property of all objects. If we make it static, this field will
get the memory only once.
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n; }
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);} }
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Output: 111 Karan ITS
Student s1 = new Student(111,"Karan"); 222 Aryan ITS
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
Java static method
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
Example of static method
//Java Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x; }
public static void main(String args[]){
int result=Calculate.cube(5); Output: 125
System.out.println(result); } }
Java static block
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Example:
class Teacher {
String designation = "Teacher";
String collegeName = "Beginnersbook";
void does(){
System.out.println("Teaching");
}
}
public class PhysicsTeacher extends Teacher{
String mainSubject = "Physics";
public static void main(String args[]){
PhysicsTeacher obj = new PhysicsTeacher(); Output: Beginnersbook
System.out.println(obj.collegeName); Teacher
Physics
System.out.println(obj.designation);
Teaching
System.out.println(obj.mainSubject);
obj.does();
}
}
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
Single Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark(); Output: barking...
d.eat(); eating...
}}
Multilevel Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
} Output: weeping...
class TestInheritance2{ barking...
public static void main(String args[]){ eating...
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hierarchical Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Output: meowing...
Cat c=new Cat(); eating...
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Method overriding
Declaring a method in sub class which is already present in parent class is known as method
overriding.
Overriding is done so that a child class can give its own implementation to a method which is
already provided by the parent class.
In this case the method in parent class is called overridden method and the method in child class is
called overriding method.
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 code.
Method Overriding is an example of runtime polymorphism. When a parent class reference points
to the child class object then the call to the overridden method is determined at runtime, because
during method call which method(parent class or child class) is to be executed is determined by
the type of object. This process in which call to the overridden method is resolved at runtime is
known as dynamic method dispatch
Example
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Output:Boy is eating
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Example of dynamic dispatch
class ABC{
//Overridden method
public void disp()
{ System.out.println("disp() method of parent class"); } }
class Demo extends ABC{
//Overriding method
public void disp(){
System.out.println("disp() method of Child class"); }
public void newMethod(){
System.out.println("new method of child class"); }
public static void main( String args[]) {
// When Parent class reference refers to the parent class object then in this case overridden method (the
method of parent class) is called. //
ABC obj = new ABC();
obj.disp();
/* When parent class reference refers to the child class object then the overriding method (method of child
class) is called.
* This is called dynamic method dispatch and runtime polymorphism */ Output: disp() method of parent class
ABC obj2 = new Demo(); disp() method of Child class
obj2.disp(); } }
Rules of method overriding
The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
The access level cannot be more restrictive than the overridden method's access level. For
example: If the superclass method is declared public then the overridding method in the sub
class cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited, then it cannot be overridden.
A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared public or
protected.
An overriding method can throw any uncheck exceptions, regardless of whether the overridden
method throws exceptions or not. However, the overriding method should not throw checked
exceptions that are new or broader than the ones declared by the overridden method. The
overriding method can throw narrower or fewer exceptions than the overridden method.
Constructors cannot be overridden.
Super keyword
The super keyword is used for calling the parent class method/constructor.
super.myMethod() calls the myMethod() method of base class while super() calls the
constructor of base class.
class ABC{
public void myMethod()
{
System.out.println("Overridden method");
} }
class Demo extends ABC{
public void myMethod(){
//This will call the myMethod() of parent class
super.myMethod();
Output: Class ABC: mymethod()
System.out.println("Overriding method"); } Class Test: mymethod()
public static void main( String args[]) {
Demo obj = new Demo();
obj.myMethod(); } }
Final keyword
A final variable that is not initialized at the time of declaration is known as blank final variable.
We must initialize the blank final variable in constructor of the class otherwise it will throw a
compilation error.
Example: class Demo{
//Blank final variable
final int MAX_VALUE;
Demo(){
//It must be initialized in constructor
MAX_VALUE=100; }
void myMethod(){
System.out.println(MAX_VALUE); }
public static void main(String args[]){ Output: 100
StudentData(int rnum){
//It must be initialized in constructor
ROLL_NO=rnum;
}
void myMethod(){
System.out.println("Roll no is:"+ROLL_NO);
}
public static void main(String args[]){
StudentData obj=new StudentData(1234);
obj.myMethod();
}
}
Final static variable in Java
If we won’t initialize a static variable, then by default JVM will provide a default value for static
variable. But when we declare a static variable with final modifier then we should take care of the
following conventions:
Declaring variables only as static can lead to change in their values by one or more instances of a class
in which it is declared.
Declaring them as static final will help you to create a CONSTANT. Only one copy of variable exists
which can’t be reinitialize.
Important points about final static variable:
1. Initialization of variable Mandatory : If the static variable declared as final, then we have to perform
initialization explicitly whether we are using it or not and JVM won’t provide any default value for the
final static variable.
2. Initialization before class loading : For final static variable, it is compulsory that we should perform
initialization before class loading completion. We can initialize a final static variable at the time of
declaration.
3. Initialize inside a static block : We can also initialize a final static variable inside a static block
because we should initialize a final static variable before class and we know that static block is
executed before main() method.
Initialization of variable Mandatory :
class Test {
final static int x;
public static void main(String[] args)
{ System.out.println(x);
}
}
Output: Error: variable x might not have been initialized
Initialization before class loading
/ Java program to illustrate that final static variable can be initialized at the time of declaration
class Test {
final static int x = 10;
public static void main(String[] args)
{
System.out.println(x);
}
}
Output: 10
Initialize inside a static block
// Java program to illustrate that final static variable can be initialized inside static block
class Test {
final static int x;
static
{
x = 10;
}
public static void main(String[] args)
{
System.out.println(x);
}
}
Output: 10
Java final method
When a method is declared with final keyword, it is called a final method. A final method cannot
be overridden.
class Bike{
final void run(){System.out.println("running");}
}
2. Multidimensional Array
Creating an array
Creation of an array involves three steps:
1. Declaring the array.
2. Creating memory locations.
3. Putting values into the memory locations.
1. Syntax for declaring an one dimensional array
type var-name[];
OR
type[] var-name;
2. Creating memory locations.
Java allows us to create array using new operator only.
arrayname=new type[size];
The above statement does two things −
It creates an array using new type[Size].
It assigns the reference of the newly created array to the variable arrayname
Putting values into memory locations:
Type[] arrayname = {value0, value1, ..., valuek};
Example of array
/Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
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;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array Output:10
System.out.println(a[i]); 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. Examples:
279
361
742
Passing Arrays to Methods
class Test {
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
// passing array to method m1
sum(arr); }
public static void sum(int[] arr) {
// getting sum of array values
int sum = 0;
for (int i = 0; i < arr.length; i++) Output: sum of array values : 15
sum+=arr[i];
System.out.println("sum of array values : " + sum); } }
Returning Arrays from Methods
class Test {
// Driver method
public static void main(String args[])
{
int arr[] = m1();
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" "); }
public static int[] m1()
{ // returning array
return new int[]{1,2,3}; Output: 1 2 3
} }
Some methods use in Array
length()
copyOf(original array, length)
sort(array)
reverse(array)
copyOfRange(original array, from, to)
equals(array1, array 2)
fill(array , value)
toString(array)
String
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, Object... args) returns a formatted string.
4 static String format(Locale l, String format, Object... args) returns formatted string with given locale.
9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) returns a joined string.
10 boolean equals(Object another) checks the equality of string with the given object.
14 String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified
CharSequence.
15 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
20 int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index.
22 int indexOf(String substring, int fromIndex) returns the specified substring index starting with given index.
28 static String valueOf(int value) converts given type into string. It is an overloaded method.
Interfaces
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.
Declaring Interfaces: The interface keyword is used to declare an interface.
interface MyInterface
{
/* All the methods are public abstract by default
* As you see they have no body
*/
public void method1();
public void method2();
}
An interface is similar to a class in the following ways −
An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
The byte code of an interface appears in a .class file.
Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
However, an interface is different from a class in several ways, including −
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.
interface MyInterface
{
public void method1();
public void method2();}
class Demo implements MyInterface{
// This class must have to implement both the abstract methods else you will get
compilation error
public void method1() {
System.out.println("implementation of method1"); }
public void method2() {
System.out.println("implementation of method2"); }
public static void main(String arg[]) {
MyInterface obj = new Demo();
obj.method1(); } }
key points to remember about interfaces:
1) We can’t instantiate an interface in java. That means we cannot create the object of an interface
2) Interface provides full abstraction as none of its methods have body. On the other hand abstract class provides partial abstraction
as it can have abstract and concrete(methods with body) methods both.
3) implements keyword is used by classes to implement an interface.
4) While providing implementation in class of any method of an interface, it needs to be mentioned as public.
5) Class that implements any interface must implement all the methods of that interface, else the class should be declared abstract.
6) Interface cannot be declared as private, protected or transient.
7) All the interface methods are by default abstract and public.
8) Variables declared in interface are public, static and final by default.
9) Interface variables must be initialized at the time of declaration otherwise compiler will throw an error.
10) Inside any implementation class, you cannot change the variables declared in interface because by default, they are public,
static and final.
11) An interface can extend any interface but cannot implement it. Class implements interface and interface extends interface.
12) A class can implement any number of interfaces.
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.
14) A class cannot implement two interfaces that have methods with same name but different return type.
15) Variable names conflicts can be resolved by interface name.
Multiple Inheritance
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
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");}
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
Output: drawing rectangle
default method
Static Method in Interface
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw(); Output: drawing rectangle
27
System.out.println(Drawable.cube(3));
}}
Difference between abstract class and
interface
Abstract class Interface
1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Since Java 8, it can
have default and static methods also.
3) Abstract class can have final, non-final, static and non-static Interface has only static and final variables.
variables.
4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class.
5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
6) An abstract class can extend another Java class and implement An interface can extend another Java interface only.
multiple Java interfaces.
7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword "implements".
8) A Java abstract class can have class members like private, Members of a Java interface are public by default.
protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Packages
A java package is a group of similar types of classes, interfaces and sub-
packages
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.
Advantages of using a package in Java
Reusability
Better Organization
Name Conflicts
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in
packages.
Example of package
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
Syntax: javac -d directory javafilename
Ex: javac -d . Simple.java
To Run: java mypack.Simple
How to access package
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
Using packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using packagename.classname
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
How to send the class file to another directory or drive
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
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.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
e:\sources> java -classpath c:\classes mypack.Simple
How to put two public classes in a package
//save as A.java
package javatpoint;
public class A{}
//save as B.java
package javatpoint;
public class B{}
Sub packages in Java
A package inside another package is known as sub package. For example If I create a
package inside letmecalculate package then that will be called sub package.
Lets say I have created another package inside letmecalculate and the sub package name
is multiply. So if I create a class in this subpackage it should have this package declaration
in the beginning:
Syntax: package letmecalculate.multiply;
Multiplication.java
package letmecalculate.multiply;
public class Multiplication {
int product(int a, int b){
return a*b; } }
Now if I need to use this Multiplication class I have to either import the package like this:
import letmecalculate.multiply;
or I can use fully qualified name like this:
letmecalculate.multiply.Multiplication obj =
new letmecalculate.multiply.Multiplication();
Static import
Static import is a feature introduced in Java programming language ( versions 5 and above
) that allows members ( fields and methods ) defined in a class as public static to be used
in Java code without specifying the class in which the field is defined.
Simple Example of static import
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
out.println("Hello");//Now no need of System.out
out.println("Java");
}
}
Access Modifier in JAVA
Exception Handling
The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that normal flow of the application can
be maintained.
Default Exception Handling : Whenever inside a method, if an
exception has occurred, the method creates an Object known as
Exception Object and hands it off to the run-time system(JVM). The
exception object contains name and description of the exception, and
current state of the program where exception has occurred. Creating
the Exception Object and handling it to the run-time system is called
throwing an Exception
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an
error is considered as the unchecked exception. According to Oracle, there
are three types of exceptions:
Checked Exception
Unchecked Exception
Error
Difference between Checked and Unchecked
Exceptions
1) Checked Exception
The classes which directly inherit 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 which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Example of Exception
A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler. So, if you have to perform different tasks at
the occurrence of different exceptions, use java multi-catch block.
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0; }
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e) {
Output:Arithmetic Exception occurs
System.out.println("Parent Exception occurs"); } rest of the code
System.out.println("rest of the code"); } }
Nested try catch Block
When a try catch block is present in another try block then it is called the
nested try catch block. Each time a try block does not have a catch handler
for a particular exception, then the catch blocks of parent try block are
inspected for that exception, if match is found that that catch block
executes.
class NestingDemo{
public static void main(String args[]){ //main try-block
try{ //try-block2
try{ //try-block3
try{ int arr[]= {1,2,3,4};
// I'm trying to display the value of an element which doesn't exist. The code should throw an exception
System.out.println(arr[10]);
}catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block3"); } }
catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2"); } }
catch(ArithmeticException e3){
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block"); }
catch(ArrayIndexOutOfBoundsException e4){
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block"); } Output:
catch(Exception e5){ ArrayIndexOutOfBoundsException handled in main try-block
System.out.print("Exception");
System.out.println(" handled in main try-block"); } }}
Finally Block
Java finally block is a block that is used to execute important code such as
closing connection, stream etc.
Java finally block is always executed whether
exception is handled or not.
Java finally block follows try or catch block.
class Example
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num); }
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero"); }
//Finally block will always execute even if there is no exception in try block
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
} }
Output:
Number should not be divided by zero
This is finally block
Out of try-catch-finally
Throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The
throw keyword is mainly used to throw custom exception.
Syntax: throw new Throwable subclass;
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote"); }
public static void main(String args[]){
validate(13);
System.out.println("rest of the code..."); } }
} catch(SQLException e) {
logger.log(e);
} catch(IOException e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
try {
} catch(SQLException | IOException e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
Try with resource statement
The Java try with resources is an exception handling mechanism that can automatically close
resources like a Java InputStream or a JDBC Connection when you are done with them. To do so, you
must open and use the resource within a Java try-with-resources block. When the execution leaves
the try-with-resources block, any resource opened within the try-with-resources block is
automatically closed, regardless of whether any exceptions are thrown either from inside the try-
with-resources block, or when attempting to close the resources.
Ex: private static void printFile() throws IOException {
New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the
thread. It is also referred to as a born thread.
Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered
to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform
a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to
continue executing.
Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in
this state transitions back to the runnable state when that time interval expires or when the event it is waiting for
occurs.
Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise
terminates.
Stopping and Blocking a thread
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
Output:running thread name is:Thread-0
} running thread priority is:10
running thread name is:Thread-1
}
running thread priority is:1
Synchronization
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared
resource.
The synchronization is mainly used to : 1. To prevent thread interference.
2. To prevent consistency problem.
class Table{
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{ Thread.sleep(400);
}catch(Exception e){System.out.println(e);} } } }
Table t;
MyThread1(Table t){
this.t=t; }
t.printTable(5); } }
Table t;
MyThread2(Table t){
this.t=t; }
t.printTable(100); } }