Java Tutorial
What is Java
Java is a programming language and a platform.
Java is a high level, robust, secured and object-oriented programming language.
Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java has its own runtime environment (JRE) and API, it is called platform.
Java Example
Let's have a quick look at java programming example. A detailed description of hello java example is given in next page.
- class Simple{
- public static void main(String args[]){
- System.out.println("Hello Java");
- }
- }
Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently used. Some of them are as follows:
- Desktop Applications such as acrobat reader, media player, antivirus etc.
- Web Applications such as irctc.co.in, javatpoint.com etc.
- Enterprise Applications such as banking applications.
- Mobile
- Embedded System
- Smart Card
- Robotics
- Games etc.
Types of Java Applications
There are mainly 4 type of applications that can be created using java programming:
1) Standalone Application
It is also known as desktop application or window-based application. An application that we need to install on every machine such as 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 dynamic page, is called web application. Currently, servlet, jsp, struts, 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. It has the advantage of high level security, load balancing and clustering. In java, EJB is used for creating enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile applications.
History of Java
Java history is interesting to know. The history of java starts from Green Team. Java team members (also known as Green Team), initiated a revolutionary task to develop a language for digital devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was suited for internet programming. Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There are given the major points that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
Why Oak name for java language?
5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like U.S.A., France, Germany, Romania etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
Why Java name for java language?
7) Why they choosed java name for java language? The team gathered to choose a new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They wanted something that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to say.
According to James Gosling "Java was one of the top choices along with Silk". Since java was so unique, most of the team members preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
9) Notice that Java is just a name not an acronym.
10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(January 23, 1996).
Java Version History
There are many java versions that has been released. Current stable release of Java is Java SE 8.
- JDK Alpha and Beta (1995)
- JDK 1.0 (23rd Jan, 1996)
- JDK 1.1 (19th Feb, 1997)
- J2SE 1.2 (8th Dec, 1998)
- J2SE 1.3 (8th May, 2000)
- J2SE 1.4 (6th Feb, 2002)
- J2SE 5.0 (30th Sep, 2004)
- Java SE 6 (11th Dec, 2006)
- Java SE 7 (28th July, 2011)
- Java SE 8 (18th March, 2014)
Features of Java
There is given many features of java. They are also known as java buzzwords. The Java Features given below are simple and easy to understand.
- Simple
- Object-Oriented
- Platform independent
- Secured
- Robust
- Architecture neutral
- Portable
- Dynamic
- Interpreted
- High Performance
- Multithreaded
- Distributed
Simple
According to Sun, Java language is simple because:
|
syntax is based on C++ (so easier for programmers to learn it after C++).
|
removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc.
|
No need to remove unreferenced objects because there is Automatic Garbage Collection in java.
|
Object-oriented
Object-oriented means we organize our software as a combination of different types of objects that incorporates both data and behaviour.
|
Object-oriented programming(OOPs) is a methodology that simplify software development and maintenance by providing some rules.
|
Basic concepts of OOPs are:
|
|
Platform Independent
A platform is the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform. The Java platform differs from most other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms.It has two components:
|
Java code can be run on multiple platforms e.g.Windows,Linux,Sun Solaris,Mac/OS etc. Java code is compiled by the compiler and converted into bytecode.This bytecode is a platform independent code because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).
|
Secured
Java is secured because:
|
|
|
These security are provided by java language. Some security can also be provided by application developer through SSL,JAAS,cryptography etc.
|
Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java. All these points makes java robust.
|
Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.
|
Portable
We may carry the java bytecode to any platform.
|
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a compiled language (e.g., C++)
|
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it shares the same memory. Threads are important for multi-media, Web applications etc.
Types of Java Applications
There are mainly 4 type of applications that can be created using java programming:
1) Standalone Application
It is also known as desktop application or window-based application. An application that we need to install on every machine such as 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 dynamic page, is called web application. Currently, servlet, jsp, struts, 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. It has the advantage of high level security, load balancing and clustering. In java, EJB is used for creating enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile applications.
Simple Program of Java
In this page, we will learn how to write the simple program of java. We can write a simple hello java program easily after installing the JDK.
To create a simple java program, you need to create a class that contains main method. Let's understand the requirement first.
Creating hello java example
Let's create the hello java program:- class Simple{
- public static void main(String args[]){
- System.out.println("Hello Java");
- }
- }
save this file as Simple.java
To compile:
|
javac Simple.java
|
To execute:
|
java Simple
|
Output:Hello Java
Understanding first java program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().- class keyword is used to declare a class in java.
- public keyword is an access modifier which represents visibility, it means it is visible to all.
- static is a keyword, if we declare any method as static, it is known as static method. The core advantage of static method is that there is no need to create object to invoke the static method. The main method is executed by the JVM, so it doesn't require to create object to invoke the main method. So it saves memory.
- void is the return type of the method, it means it doesn't return any value.
- main represents startup of the program.
- String[] args is used for command line argument. We will learn it later.
- System.out.println() is used print statement. We will learn about the internal working of System.out.println statement later.
What happens at compile time?
At compile time, java file is compiled by Java Compiler (It does not interact with OS) and converts the java code into bytecode.
Difference between JDK, JRE and JVM
Understanding the difference between JDK, JRE and JVM is important in Java. We are having brief overview of JVM here.
If you want to get the detailed knowledge of Java Virtural Machine, move to the next page. Firstly, let's see the basic differences between the JDK, JRE and JVM.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.
|
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent.
|
The JVM performs following main tasks:
|
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at runtime.
|
Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.
|
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.
|
JVM (Java Virtual Machine)
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.JVMs are available for many hardware and software platforms (i.e.JVM is plateform dependent).
What is JVM?
It is:- A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
- An implementation Its implementation is known as JRE (Java Runtime Environment).
- Runtime Instance Whenever you write java command on the command prompt to run the java class, and instance of JVM is created.
What it does?
The JVM performs following operation:- Loads code
- Verifies code
- Executes code
- Provides runtime environment
- Memory area
- Class file format
- Register set
- Garbage-collected heap
- Fatal error reporting etc.
Variable and Datatype in Java
In this page, we will learn about the variable and java data types. Variable is a name of memory location. There are three types of variables: local, instance and static. There are two types of datatypes in java, primitive and non-primitive.
|
Types of Variable
Local Variable
A variable that is declared inside the method is called local variable.
|
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It is not declared as static.
|
Static variable
A variable that is declared as static is called static variable. It cannot be local.
|
Data Types in Java
In java, there are two types of data types
|
Operators in java
Operator in java is a symbol that is used to perform operations. There are many types of operators in java such as unary operator, arithmetic operator, relational operator, shift operator, bitwise operator, ternary operator and assignment operator.
Operators
|
Precedence
|
postfix
|
expr++ expr--
|
unary
|
++expr --expr +expr -expr ~ !
|
multiplicative
|
* / %
|
additive
|
+ -
|
shift
|
<< >> >>>
|
relational
|
< > <= >= instanceof
|
equality
|
== !=
|
bitwise AND
|
&
|
bitwise exclusive OR
|
^
|
bitwise inclusive OR
|
|
|
logical AND
|
&&
|
logical OR
|
||
|
ternary
|
? :
|
assignment
|
= += -= *= /= %= &= ^= |= <<= >>= >>>=
|
Java Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of running the java program.The arguments passed from the console can be received in the java program and it can be used as an input.
So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one argument from the command prompt.
|
- class CommandLineExample{
- public static void main(String args[]){
- System.out.println("Your first argument is: "+args[0]);
- }
- }
- compile by > javac CommandLineExample.java
- run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo
Example of command-line argument that prints all the values
In this example, we are printing all the arguments passed from the command-line. For this purpose, we have traversed the array using for loop.
|
- class A{
- public static void main(String args[]){
- for(int i=0;i
- System.out.println(args[i]);
- }
- }
- compile by > javac A.java
- run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method.
|
Example of call by value in java
In case of call by value original value is not changed. Let's take a simple example:
|
- class Operation{
- int data=50;
- void change(int data){
- data=data+100;//changes will be in the local variable only
- }
- public static void main(String args[]){
- Operation op=new Operation();
- System.out.println("before change "+op.data);
- op.change(500);
- System.out.println("after change "+op.data);
- }
- }
Output:before change 50
after change 50
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,
- Byte Stream : It provides a convenient means for handling input and output of byte.
- Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses Unicode and therefore can be internationalized.
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(); }
}
}
Java Array
Normally, array is a collection of similar type of elements that have contiguous memory location.
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.
Advantage of Java Array
- 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.
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.
Types of Array in java
There are two types of array.- Single Dimensional Array
- Multidimensional Array
Single Dimensional Array in java
Syntax to Declare an Array in java
- dataType[] arr; (or)
- dataType []arr; (or)
- dataType arr[];
Instantiation of an Array in java
- arrayRefVar=new datatype[size];
Example of single dimensional java array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an 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;
- //printing array
- for(int i=0;i//length is the property of array
Output: 10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:- int a[]={33,3,4,5};//declaration, instantiation and initialization
- class Testarray1{
- public static void main(String args[]){
- int a[]={33,3,4,5};//declaration, instantiation and initialization
- //printing array
- for(int i=0;i//length is the property of array
Output:33
3
4
5
Passing Array to method in java
We can pass the java array to method so that we can reuse the same logic on any array.Let's see the simple example to get minimum number of an array using method.
- class Testarray2{
- static void min(int arr[]){
- int min=arr[0];
- for(int i=1;i
- if(min>arr[i])
- min=arr[i];
- System.out.println(min);
- }
- public static void main(String args[]){
- int a[]={33,3,4,5};
- min(a);//passing array to method
- }}
Output:3
Multidimensional array in java
In such case, data is stored in row and column based index (also known as matrix form).Syntax to Declare Multidimensional Array in java
- dataType[][] arrayRefVar; (or)
- dataType [][]arrayRefVar; (or)
- dataType arrayRefVar[][]; (or)
- dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in java
- int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in java
- arr[0][0]=1;
- arr[0][1]=2;
- arr[0][2]=3;
- arr[1][0]=4;
- arr[1][1]=5;
- arr[1][2]=6;
- arr[2][0]=7;
- arr[2][1]=8;
- arr[2][2]=9;
Example of Multidimensional java array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.- class Testarray3{
- public static void main(String args[]){
- //declaring and initializing 2D array
- int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
- //printing 2D array
- for(int i=0;i<3;i++){
- for(int j=0;j<3;j++){
- System.out.print(arr[i][j]+" ");
- }
- System.out.println();
- }
- }}
Output:1 2 3
2 4 5
4 4 5
Addition of 2 matrices in java
Let's see a simple example that adds two matrices.- class Testarray5{
- public static void main(String args[]){
- //creating two matrices
- int a[][]={{1,3,4},{3,4,5}};
- int b[][]={{1,3,4},{3,4,5}};
- //creating another matrix to store the sum of two matrices
- int c[][]=new int[2][3];
- //adding and printing addition of 2 matrices
- for(int i=0;i<2;i++){
- for(int j=0;j<3;j++){
- c[i][j]=a[i][j]+b[i][j];
- System.out.print(c[i][j]+" ");
- }
- System.out.println();//new line
- }
- }}
Output:2 6 8
6 8 10
Object and Class in Java
In this page, we will learn about java objects and classes. In object-oriented programming technique, we design a program using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java
An object has three characteristics:
- state: represents data (value) of an object.
- behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
- identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But,it is used internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is its behavior.
|
Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the instance(result) of a class.
|
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.
|
- data member
- method
- constructor
- block
- class and interface
Syntax to declare a class:
- class
{ - data member;
- method;
- }
Simple Example of Object and class that maintains the records of students
In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insert Record method on it. Here, we are displaying the state (data) of the objects by invoking the display Information method.
|
- int rollno;
- String name;
- void insertRecord(int r, String n){ //method
- rollno=r;
- name=n;
- }
- void displayInformation(){System.out.println(rollno+" "+name);}//method
- public static void main(String args[]){
- Student2 s1=new Student2();
- Student2 s2=new Student2();
- s1.insertRecord(111,"Karan");
- s2.insertRecord(222,"Aryan");
- s1.displayInformation();
- s2.displayInformation();
- }
- }
Another Example of Object and Class
- class Rectangle{
- int length;
- int width;
- void insert(int l,int w){
- length=l;
- width=w;
- }
- void calculateArea(){System.out.println(length*width);}
- public static void main(String args[]){
- Rectangle r1=new Rectangle();
- Rectangle r2=new Rectangle();
- r1.insert(11,5);
- r2.insert(3,15);
- r1.calculateArea();
- r2.calculateArea();
- }
- }
Output:55
45
Creating multiple objects by one type only
We can create multiple objects by one type only as we do in case of primitives.
|
- Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
Let's see the example:
|
- class Rectangle{
- int length;
- int width;
- void insert(int l,int w){
- length=l;
- width=w;
- }
- void calculateArea(){System.out.println(length*width);}
- public static void main(String args[]){
- Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
- r1.insert(11,5);
- r2.insert(3,15);
- r1.calculateArea();
- r2.calculateArea();
- }
- }
Output:55
45
Method Overloading in Java
If a class have multiple methods by same name but different parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behaviour of the method because its name differs. So, we perform method overloading to figure out the program quickly.
Advantage of method overloading?
Method overloading increases the readability of the program.Different ways to overload the method
There are two ways to overload the method in java
|
|
In java, Methood Overloading is not possible by changing the return type of the method.
1)Example of Method Overloading by changing the no. of arguments
In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers.- class Calculation{
- void sum(int a,int b){System.out.println(a+b);}
- void sum(int a,int b,int c){System.out.println(a+b+c);}
- public static void main(String args[]){
- Calculation obj=new Calculation();
- obj.sum(10,10,10);
- obj.sum(20,20);
- }
- }
Output:30
40
2)Example of Method Overloading by changing data type of argument
In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two double arguments.- class Calculation2{
- void sum(int a,int b){System.out.println(a+b);}
- void sum(double a,double b){System.out.println(a+b);}
- public static void main(String args[]){
- Calculation2 obj=new Calculation2();
- obj.sum(10.5,10.5);
- obj.sum(20,20);
- }
- }
Output:21.0
40
Que) Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let's see how ambiguity may occur:because there was problem:
- class Calculation3{
- int sum(int a,int b){System.out.println(a+b);}
- double sum(int a,int b){System.out.println(a+b);}
- public static void main(String args[]){
- Calculation3 obj=new Calculation3();
- int result=obj.sum(20,20); //Compile Time Error
- }
- }
Can we overload main() method?
Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple example:- class Overloading1{
- public static void main(int a){
- System.out.println(a);
- }
- public static void main(String args[]){
- System.out.println("main() method invoked");
- main(10);
- }
- }
Output:main() method invoked
10
Method Overloading and TypePromotion
One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept by the figure given below:Example of Method Overloading with TypePromotion
- class OverloadingCalculation1{
- void sum(int a,long b){System.out.println(a+b);}
- void sum(int a,int b,int c){System.out.println(a+b+c);}
- public static void main(String args[]){
- OverloadingCalculation1 obj=new OverloadingCalculation1();
- obj.sum(20,20);//now second int literal will be promoted to long
- obj.sum(20,20,20);
- }
- }
Output:40
60
Constructor in JavaConstructor in java is a special type of method that is used to initialize the object.Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. Rules for creating java constructorThere are basically two rules defined for the constructor.
Types of java constructorsThere are two types of constructors:
Java Default Constructor
Syntax of default constructor:
Example of default constructor
Bike is created Rule: If there is no constructor in a class, compiler automatically creates a default constructor.Q) What is the purpose of default constructor?Default constructor provides the default values to the object like 0, null etc. depending on the type.Example of default constructor that displays the default values
0 null 0 nullExplanation:In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor. | ||||||||||||||||
Why use parameterized constructor?
Example of parameterized constructor
111 Karan 222 Aryan
|
Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.
|
Example of Constructor Overloading
- class Student5{
- int id;
- String name;
- int age;
- Student5(int i,String n){
- id = i;
- name = n;
- }
- Student5(int i,String n,int a){
- id = i;
- name = n;
- age=a;
- }
- void display(){System.out.println(id+" "+name+" "+age);}
- public static void main(String args[]){
- Student5 s1 = new Student5(111,"Karan");
- Student5 s2 = new Student5(222,"Aryan",25);
- s1.display();
- s2.display();
- }
- }
111 Karan 0
222 Aryan 25
Difference between constructor and method in java
There are many differences between constructors and methods. They are given below.
Java Constructor
|
Java Method
|
Constructor is used to initialize the state of an object.
|
Method is used to expose behaviour of an object.
|
Constructor must not have return type.
|
Method must have return type.
|
Constructor is invoked implicitly.
|
Method is invoked explicitly.
|
The java compiler provides a default constructor if you don't have any constructor.
|
Method is not provided by compiler in any case.
|
Constructor name must be same as the class name.
|
Method name may or may not be same as class name.
|
Java Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++.There are many ways to copy the values of one object into another in java. They are:
- By constructor
- By assigning the values of one object into another
- By clone() method of Object class
- class Student6{
- int id;
- String name;
- Student6(int i,String n){
- id = i;
- name = n;
- }
- Student6(Student6 s){
- id = s.id;
- name =s.name;
- }
- void display(){System.out.println(id+" "+name);}
- public static void main(String args[]){
- Student6 s1 = new Student6(111,"Karan");
- Student6 s2 = new Student6(s1);
- s1.display();
- s2.display();
- }
- }
111 Karan
111 Karan
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.- class Student7{
- int id;
- String name;
- Student7(int i,String n){
- id = i;
- name = n;
- }
- Student7(){}
- void display(){System.out.println(id+" "+name);}
- public static void main(String args[]){
- Student7 s1 = new Student7(111,"Karan");
- Student7 s2 = new Student7();
- s2.id=s1.id;
- s2.name=s1.name;
- s1.display();
- s2.display();
- }
- }
111 Karan
111 Karan
Q) Does constructor return any value?
Ans:yes, that is current class instance (You cannot use return type yet it returns a value).Can constructor perform other tasks instead of initialization?
Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the method.
Java static keyword
The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
- variable (also known as class variable)
- method (also known as class method)
- block
- nested class
Java static property is shared to all objects.
Example of static variable
- //Program of static variable
- class Student8{
- int rollno;
- String name;
- static String college ="ITS";
- Student8(int r,String n){
- rollno = r;
- name = n;
- }
- void display (){System.out.println(rollno+" "+name+" "+college);}
- public static void main(String args[]){
- Student8 s1 = new Student8(111,"Karan");
- Student8 s2 = new Student8(222,"Aryan");
- s1.display();
- s2.display();
- }
- }
Output:111 Karan ITS
222 Aryan ITS
Program of counter without static variable
In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable.- class Counter{
- int count=0;//will get memory when instance is created
- Counter(){
- count++;
- System.out.println(count);
- }
- public static void main(String args[]){
- Counter c1=new Counter();
- Counter c2=new Counter();
- Counter c3=new Counter();
- }
- }
Output:1
1
1
Program of counter by static variable
As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
|
- class Counter2{
- static int count=0;//will get memory only once and retain its value
- Counter2(){
- count++;
- System.out.println(count);
- }
- public static void main(String args[]){
- Counter2 c1=new Counter2();
- Counter2 c2=new Counter2();
- Counter2 c3=new Counter2();
- }
- }
Output:1
2
3
2) 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 object of a class.
- A static method can be invoked without the need for creating an instance of a class.
- static method can access static data member and can change the value of it.
Example of static method
- //Program of changing the common property of all objects(static field).
- class Student9{
- int rollno;
- String name;
- static String college = "ITS";
- static void change(){
- college = "BBDIT";
- }
- Student9(int r, String n){
- rollno = r;
- name = n;
- }
- void display (){System.out.println(rollno+" "+name+" "+college);}
- public static void main(String args[]){
- Student9.change();
- Student9 s1 = new Student9 (111,"Karan");
- Student9 s2 = new Student9 (222,"Aryan");
- Student9 s3 = new Student9 (333,"Sonoo");
- s1.display();
- s2.display();
- s3.display();
- }
- }
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Another example of static method that performs normal calculation
- //Program to get cube of a given number by static method
- class Calculate{
- static int cube(int x){
- return x*x*x;
- }
- public static void main(String args[]){
- int result=Calculate.cube(5);
- System.out.println(result);
- }
- }
Output:125
Restrictions for static method
There are two main restrictions for the static method. They are:
|
|
- class A{
- int a=40;//non static
- public static void main(String args[]){
- System.out.println(a);
- }
- }
Output:Compile Time Error
Q) why java main method is static?
Ans) because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.
|
3) Java static block
- Is used to initialize the static data member.
- It is executed before main method at the time of classloading.
Example of static block
- class A2{
- static{System.out.println("static block is invoked");}
- public static void main(String args[]){
- System.out.println("Hello main");
- }
- }
Output:static block is invoked
Hello main
Q) Can we execute a program without main() method?
Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.- class A3{
- static{
- System.out.println("static block is invoked");
- System.exit(0);
- }
- }
Output:static block is invoked (if not JDK7)In JDK7 and above, output will be:
Output:Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
this keyword in java
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.Usage of java this keyword
Here is given the 6 usage of java this keyword.- this keyword can be used to refer current class instance variable.
- this() can be used to invoke current class constructor.
- this keyword can be used to invoke current class method (implicitly)
- this can be passed as an argument in the method call.
- this can be passed as argument in the constructor call.
- this keyword can also be used to return the current class instance.
- //example of this keyword
- class Student11{
- int id;
- String name;
- Student11(int id,String name){
- this.id = id;
- this.name = name;
- }
- void display(){System.out.println(id+" "+name);}
- public static void main(String args[]){
- Student11 s1 = new Student11(111,"Karan");
- Student11 s2 = new Student11(222,"Aryan");
- s1.display();
- s2.display();
- }
- }
18.
Output111 Karan
222 Aryan
2) this() can be used to invoked current class constructor.
The this() constructor call can be used to invoke the current class constructor (constructor chaining). This approach is better if you have many constructors in the class and want to reuse that constructor.- //Program of this() constructor call (constructor chaining)
- class Student13{
- int id;
- String name;
- Student13(){System.out.println("default constructor is invoked");}
- Student13(int id,String name){
- this ();//it is used to invoked current class constructor.
- this.id = id;
- this.name = name;
- }
- void display(){System.out.println(id+" "+name);}
- public static void main(String args[]){
- Student13 e1 = new Student13(111,"karan");
- Student13 e2 = new Student13(222,"Aryan");
- e1.display();
- e2.display();
- }
- }
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
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).
- For Code Reusability.
Syntax of Java Inheritance
- class Subclass-name extends Superclass-name
- {
- //methods and fields
- }
In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass.
Understanding the simple example of inheritance
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.
- class Employee{
- float salary=40000;
- }
- class Programmer extends Employee{
- int bonus=10000;
- public static void main(String args[]){
- Programmer p=new Programmer();
- System.out.println("Programmer salary is:"+p.salary);
- System.out.println("Bonus of Programmer is:"+p.bonus);
- }
- }
Programmer salary is:40000.0
Bonus of programmer is:10000In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.
Q) 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.
- class A{
- void msg(){System.out.println("Hello");}
- }
- class B{
- void msg(){System.out.println("Welcome");}
- }
- class C extends A,B{//suppose if it were
- Public Static void main(String args[]){
- C obj=new C();
- obj.msg();//Now which msg() method would be invoked?
- }
- }
Compile Time Error
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
- Method overriding is used to provide specific implementation of a method that is already provided by its super class.
- Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
- method must have same name as in the parent class
- method must have same parameter as in the parent class.
- must be IS-A relationship (inheritance).
Understanding the problem without method overriding
Let's understand the problem that we may face in the program if we don't use method overriding.- class Vehicle{
- void run(){System.out.println("Vehicle is running");}
- }
- class Bike extends Vehicle{
- public static void main(String args[]){
- Bike obj = new Bike();
- obj.run();
- }
- }
Output:Vehicle is runningProblem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.
Example of method overriding
In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.- class Vehicle{
- void run(){System.out.println("Vehicle is running");}
- }
- class Bike2 extends Vehicle{
- void run(){System.out.println("Bike is running safely");}
- public static void main(String args[]){
- Bike2 obj = new Bike2();
- obj.run();
- }
Output:Bike is running safely
Real example of Java Method Overriding
Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.- class Bank{
- int getRateOfInterest(){return 0;}
- }
- class SBI extends Bank{
- int getRateOfInterest(){return 8;}
- }
- class ICICI extends Bank{
- int getRateOfInterest(){return 7;}
- }
- class AXIS extends Bank{
- int getRateOfInterest(){return 9;}
- }
- class Test2{
- public static void main(String args[]){
- SBI s=new SBI();
- ICICI i=new ICICI();
- AXIS a=new AXIS();
- System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
- System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
- System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
- }
- }
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Can we override static method?
No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.Why we cannot override static method?
because static method is bound with class whereas instance method is bound with object. Static belongs to class area and instance belongs to heap area.Can we override java main method?
No, because main is a static method.Difference between method Overloading and Method Overriding in java
Difference between method overloading and method overriding in java
There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below:
No.
|
Method Overloading
|
Method Overriding
|
1)
|
Method overloading is used to increase the readability of the program.
|
Method overriding is used to provide the specific implementation of the method that is already provided by its super class.
|
2)
|
Method overloading is performed within class.
|
Method overriding occurs in two classes that have IS-A (inheritance) relationship.
|
3)
|
In case of method overloading, parameter must be different.
|
In case of method overriding, parameter must be same.
|
4)
|
Method overloading is the example of compile time polymorphism.
|
Method overriding is the example of run time polymorphism.
|
5)
|
In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter.
|
Return type must be same or covariant in method overriding.
|
Java Method Overloading example
- class OverloadingExample{
- static int add(int a,int b){return a+b;}
- static int add(int a,int b,int c){return a+b+c;}
- }
Java Method Overriding example
- class Animal{
- void eat(){System.out.println("eating...");}
- }
- class Dog extends Animal{
- void eat(){System.out.println("eating bread...");}
- }
super keyword in java
The super keyword in java is a reference variable that is used to refer immediate parent class object.Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.
Usage of java super Keyword
- super is used to refer immediate parent class instance variable.
- super() is used to invoke immediate parent class constructor.
- super is used to invoke immediate parent class method.
1) super is used to refer immediate parent class instance variable.
Problem without super keyword
- class Vehicle{
- int speed=50;
- }
- class Bike3 extends Vehicle{
- int speed=100;
- void display(){
- System.out.println(speed);//will print speed of Bike
- }
- public static void main(String args[]){
- Bike3 b=new Bike3();
- b.display();
- }
- }
Output:100
In the above example Vehicle and Bike both class have a common property speed. Instance variable of current class is refered by instance bydefault, but I have to refer parent class instance variable that is why we use super keyword to distinguish between parent class instance variable and current class instance variable.
|
Solution by super keyword
- //example of super keyword
- class Vehicle{
- int speed=50;
- }
- class Bike4 extends Vehicle{
- int speed=100;
- void display(){
- System.out.println(super.speed);//will print speed of Vehicle now
- }
- public static void main(String args[]){
- Bike4 b=new Bike4();
- b.display();
- }
- }
Output:50
2) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor as given below:
|
- class Vehicle{
- Vehicle(){System.out.println("Vehicle is created");}
- }
- class Bike5 extends Vehicle{
- Bike5(){
- super();//will invoke parent class constructor
- System.out.println("Bike is created");
- }
- public static void main(String args[]){
- Bike5 b=new Bike5();
- }
- }
Output:Vehicle is created
Bike is created
Note: super() is added in each class constructor automatically by compiler.
As we know well that default constructor is provided by compiler automatically but it also adds super() for the first statement.If you are creating your own constructor and you don't have either this() or super() as the first statement, compiler will provide super() as the first statement of the constructor.Another example of super keyword where super() is provided by the compiler implicitly.
- class Vehicle{
- Vehicle(){System.out.println("Vehicle is created");}
- }
- class Bike6 extends Vehicle{
- int speed;
- Bike6(int speed){
- this.speed=speed;
- System.out.println(speed);
- }
- public static void main(String args[]){
- Bike6 b=new Bike6(10);
- }
- }
Output:Vehicle is created
10
3) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used in case subclass contains the same method as parent class as in the example given below:
|
- class Person{
- void message(){System.out.println("welcome");}
- }
- class Student16 extends Person{
- void message(){System.out.println("welcome to java");}
- void display(){
- message();//will invoke current class message() method
- super.message();//will invoke parent class message() method
- }
- public static void main(String args[]){
- Student16 s=new Student16();
- s.display();
- }
- }
Output:welcome to java
welcome
In the above example Student and Person both classes have message() method if we call message() method from Student class, it will call the message() method of Student class not of Person class because priority is given to local.
|
In case there is no method in subclass as parent, there is no need to use super. In the example given below message() method is invoked from Student class but Student class does not have message() method, so you can directly call message() method.
|
Program in case super is not required
- class Person{
- void message(){System.out.println("welcome");}
- }
- class Student17 extends Person{
- void display(){
- message();//will invoke parent class message() method
- }
- public static void main(String args[]){
- Student17 s=new Student17();
- s.display();
- }
- }
Output:welcome
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:
- variable
- method
- 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).Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.- class Bike9{
- final int speedlimit=90;//final variable
- void run(){
- speedlimit=400;
- }
- public static void main(String args[]){
- Bike9 obj=new Bike9();
- obj.run();
- }
- }//end of class
Output:Compile Time Error
Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:- class Bike{
- final void run(){System.out.println("running...");}
- }
- class Honda2 extends Bike{
- public static void main(String args[]){
- new Honda2().run();
- }
- }
Output:running...
Que) Can we initialize blank final variable?
Yes, but only in constructor. For example:- class Bike10{
- final int speedlimit;//blank final variable
- Bike10(){
- speedlimit=70;
- System.out.println(speedlimit);
- }
- public static void main(String args[]){
- new Bike10();
- }
- }
Output:70
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.Example of static blank final variable
- class A{
- static final int data;//static blank final variable
- static{ data=50;}
- public static void main(String args[]){
- System.out.println(A.data);
- }
- }
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it.- class Bike11{
- int cube(final int n){
- n=n+2;//can't be changed as n is final
- n*n*n;
- }
- public static void main(String args[]){
- Bike11 b=new Bike11();
- b.cube(5);
- }
- }
Output:Compile Time Error
Q) Can we declare a constructor final?
No, because constructor is never inherited.
Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.
If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.
Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime.Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
- class Bike{
- void run(){System.out.println("running");}
- }
- class Splender extends Bike{
- void run(){System.out.println("running safely with 60km");}
- public static void main(String args[]){
- Bike b = new Splender();//upcasting
- b.run();
- }
- }
Output:running safely with 60km.
Java Runtime Polymorphism with data member
Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data members.
|
In the example given below, both the classes have a datamember speedlimit, we are accessing the datamember by the reference variable of Parent class which refers to the subclass object. Since we are accessing the datamember which is not overridden, hence it will access the datamember of Parent class always.
|
Rule: Runtime polymorphism can't be achieved by data members.
- class Bike{
- int speedlimit=90;
- }
- class Honda3 extends Bike{
- int speedlimit=150;
- public static void main(String args[]){
- Bike obj=new Honda3();
- System.out.println(obj.speedlimit);//90
- }
Output:90
Java Runtime Polymorphism with Multilevel Inheritance
Let's see the simple example of Runtime Polymorphism with multilevel inheritance.- class Animal{
- void eat(){System.out.println("eating");}
- }
- class Dog extends Animal{
- void eat(){System.out.println("eating fruits");}
- }
- class BabyDog extends Dog{
- void eat(){System.out.println("drinking milk");}
- public static void main(String args[]){
- Animal a1,a2,a3;
- a1=new Animal();
- a2=new Dog();
- a3=new BabyDog();
- a1.eat();
- a2.eat();
- a3.eat();
- }
- }
Output: eating
eating fruits
drinking Milk
Static Binding and Dynamic Binding
Connecting a method call to the method body is known as binding.
There are two types of binding
- static binding (also known as early binding).
- dynamic binding (also known as late binding).
static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.If there is any private, final or static method in a class, there is static binding.
Example of static binding
- class Dog{
- private void eat(){System.out.println("dog is eating...");}
- public static void main(String args[]){
- Dog d1=new Dog();
- d1.eat();
- }
- }
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.Example of dynamic binding
- class Animal{
- void eat(){System.out.println("animal is eating...");}
- }
- class Dog extends Animal{
- void eat(){System.out.println("dog is eating...");}
- public static void main(String args[]){
- Animal a=new Dog();
- a.eat();
- }
- }
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.
|
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java- Abstract class (0 to 100%)
- Interface (100%)
Abstract class in Java
A class that is declared as abstract is known as abstract class. 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.
|
Example abstract method
- abstract void printStatus();//no body and abstract
Example of abstract class that has abstract method
In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class.- abstract class Bike{
- abstract void run();
- }
- class Honda4 extends Bike{
- void run(){System.out.println("running safely..");}
- public static void main(String args[]){
- Bike obj = new Honda4();
- obj.run();
- }
- }
running safely..
Another example of abstract class in java
File: TestBank.java
- abstract class Bank{
- abstract int getRateOfInterest();
- }
- class SBI extends Bank{
- int getRateOfInterest(){return 7;}
- }
- class PNB extends Bank{
- int getRateOfInterest(){return 7;}
- }
- class TestBank{
- public static void main(String args[]){
- Bank b=new SBI();//if object is PNB, method of PNB will be invoked
- int interest=b.getRateOfInterest();
- System.out.println("Rate of Interest is: "+interest+" %");
- }}
Rate of Interest is: 7 %
Abstract class having constructor, data member, methods etc.
An abstract class can have data member, abstract method, method body, constructor and even main() method.
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();
- }
- }
bike is created
running safely..
gear changed
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods only.The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.- It is used to achieve fully abstraction.
- By interface, we can support the functionality of multiple inheritance.
- It can be used to achieve loose coupling.
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 andSimple example of Java interface
In this example, Printable interface have only one method, its implementation is provided in the A class.
|
- interface printable{
- void print();
- }
- class A6 implements printable{
- public void print(){System.out.println("Hello");}
- public static void main(String args[]){
- A6 obj = new A6();
- obj.print();
- }
- }
Output:Hello
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as 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");}
- public static void main(String args[]){
- A7 obj = new A7();
- obj.print();
- obj.show();
- }
- }
Output:Hello
Welcome
Interface inheritance
A class implements interface but one interface extends another interface .- interface Printable{
- void print();
- }
- interface Showable extends Printable{
- void show();
- }
- class Testinterface2 implements Showable{
- public void print(){System.out.println("Hello");}
- public void show(){System.out.println("Welcome");}
- public static void main(String args[]){
- Testinterface2 obj = new Testinterface2();
- obj.print();
- obj.show();
- }
- }
Test it Now
Hello
Welcome
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Abstract class
|
Interface
|
1) Abstract class can have abstract and non-abstract methods.
|
Interface can have only abstract methods.
|
2) Abstract class doesn't support multiple inheritance.
|
Interface supports multiple inheritance.
|
3) Abstract class can have final, non-final, static and non-static variables.
|
Interface has only static and final variables.
|
4) Abstract class can have static methods, main method and constructor.
|
Interface can't have static methods, main method or constructor.
|
5) Abstract class can provide the implementation of interface.
|
Interface can't provide the implementation of abstract class.
|
6) The abstract keyword is used to declare abstract class.
|
The interface keyword is used to declare interface.
|
7) Example:
public abstract class Shape{ public abstract void draw(); } |
Example:
public interface Drawable{ void draw(); } |
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).
Example of abstract class and interface in Java
Let's see a simple example where we are using interface and abstract class both.- //Creating interface that has 4 methods
- interface A{
- void a();//bydefault, public and abstract
- void b();
- void c();
- void d();
- }
- //Creating abstract class that provides the implementation of one method of A interface
- abstract class B implements A{
- public void c(){System.out.println("I am C");}
- }
- //Creating subclass of abstract class, now we need to provide the implementation of rest of the methods
- 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");}
- }
- //Creating a test class that calls the methods of A interface
- class Test5{
- public static void main(String args[]){
- A a=new M();
- a.a();
- a.b();
- a.c();
- a.d();
- }}
I am a
I am b
I am c
I am d
Java Package
- Java Package
- Example of package
- Accessing package
- By import packagename.*
- By import packagename.classname
- By fully qualified name
- Subpackage
- Sending class file to another directory
- -classpath switch
- 4 ways to load the class file or jar file
- How to put two public class in a package
- Static Import
- Package class
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.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.2) Java package provides access protection.
3) Java package removes naming collision.
Simple example of java package
The package keyword is used to create a package in java.- //save as Simple.java
- package mypack;
- public class Simple{
- public static void main(String args[]){
- System.out.println("Welcome to package");
- }
- }
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:- javac -d directory javafilename
- javac -d . Simple.java
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
|
To Run: java mypack.Simple
|
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) 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.
|
Example of package that import the packagename.*
- //save by A.java
- package pack;
- public class A{
- public void msg(){System.out.println("Hello");}
- }
- //save by B.java
- package mypack;
- import pack.*;
- class B{
- public static void main(String args[]){
- A obj = new A();
- obj.msg();
- }
- }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.Example of package by import package.classname
- //save by A.java
- package pack;
- public class A{
- public void msg(){System.out.println("Hello");}
- }
- //save by B.java
- package mypack;
- import pack.A;
- class B{
- public static void main(String args[]){
- A obj = new A();
- obj.msg();
- }
- }
Output:Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.
Example of package by import fully qualified name
- //save by A.java
- package pack;
- public class A{
- public void msg(){System.out.println("Hello");}
- }
- //save by B.java
- package mypack;
- class B{
- public static void main(String args[]){
- pack.A obj = new pack.A();//using fully qualified name
- obj.msg();
- }
- }
Output:Hello
Note: If you import a package, subpackages will not be imported.
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.Note: Sequence of the program must be package then import then class.
Access Modifiers in java
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:
- private
- default
- protected
- public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers.
1) private access modifier
The private access modifier is accessible only within class.
|
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and private method. We are accessing these private members from outside the class, so there is compile time error.
|
- class A{
- private int data=40;
- private void msg(){System.out.println("Hello java");}
- }
- public class Simple{
- public static void main(String args[]){
- A obj=new A();
- System.out.println(obj.data);//Compile Time Error
- obj.msg();//Compile Time Error
- }
- }
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:
|
- class A{
- private A(){}//private constructor
- void msg(){System.out.println("Hello java");}
- }
- public class Simple{
- public static void main(String args[]){
- A obj=new A();//Compile Time Error
- }
- }
Note: A class cannot be private or protected except nested class.
2) default access modifier
If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.
|
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package.
|
- //save by A.java
- package pack;
- class A{
- void msg(){System.out.println("Hello");}
- }
- //save by B.java
- package mypack;
- import pack.*;
- class B{
- public static void main(String args[]){
- A obj = new A();//Compile Time Error
- obj.msg();//Compile Time Error
- }
- }
3) protected access modifier
The protected access modifier is accessible within package and outside the package but through inheritance only.The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.- //save by A.java
- package pack;
- public class A{
- protected void msg(){System.out.println("Hello");}
- }
- //save by B.java
- package mypack;
- import pack.*;
- class B extends A{
- public static void main(String args[]){
- B obj = new B();
- obj.msg();
- }
- }
Output:Hello
4) public access modifier
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
|
Example of public access modifier
- //save by A.java
- package pack;
- public class A{
- public void msg(){System.out.println("Hello");}
- }
- //save by B.java
- package mypack;
- import pack.*;
- class B{
- public static void main(String args[]){
- A obj = new A();
- obj.msg();
- }
- }
Output:Hello
Understanding all java access modifiers
Let's understand the access modifiers by a simple table.
Access Modifier
|
within class
|
within package
|
outside package by subclass only
|
outside package
|
Private
|
Y
|
N
|
N
|
N
|
Default
|
Y
|
Y
|
N
|
N
|
Protected
|
Y
|
Y
|
Y
|
N
|
Public
|
Y
|
Y
|
Y
|
Y
|
Java String
Java String provides a lot of concepts that can be performed on a string such as compare, concat, equals, split, length, replace, compareTo, intern, substring etc.
In java, string is basically an object that represents sequence of char values.
An array of characters works same as java string. For example:
- char[] ch={'j','a','v','a','t','p','o','i','n','t'};
- String s=new String(ch);
is same as:
- String s="javatpoint";
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
The java String is immutable i.e. it cannot be changed but a new instance is created. For mutable class, you can use StringBuffer and StringBuilder class.
We will discuss about immutable string later. Let's first understand what is string in java and how to create the string object.
How to create String object?
There are two ways to create String object:
|
1) String Literal
Java String literal is created by using double quotes. For Example:- String s="welcome";
Note: String objects are stored in a special memory area known as string constant pool.
Why java uses concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).2) By new keyword
- String s=new String("Welcome");//creates two objects and one reference variable
Java String Example
- public class StringExample{
- public static void main(String args[]){
- String s1="java";//creating string by java string literal
- char ch[]={'s','t','r','i','n','g','s'};
- String s2=new String(ch);//converting char array to string
- String s3=new String("example");//creating java string by new keyword
- System.out.println(s1);
- System.out.println(s2);
- System.out.println(s3);
- }}
java
strings
example
String class
It is a predefined class in java.lang package can be used to handle the String. String class is immutable that means whose content can not be changed at the time of execution of program.String class object is immutable that means when we create an object of String class it never changes in the existing object.
Example:
Example
class StringHandling
{
public static void main(String arg[])
{
String s=new String("java");
s.concat("software");
System.out.println(s);
}
}
Output
javaExplanation: Here we can not change the object of String class so output is only java not java software.
Methods of String class
length()
length(): This method is used to get the number of character of any string.Example
class StringHandling
{
public static void main(String arg[])
{
int l;
String s=new String("Java");
l=s.length();
System.out.println("Length: "+l);
}
}
Output
Length: 4
charAt(index)
charAt(): This method is used to get the character at a given index value.Example
class StringHandling
{
public static void main(String arg[])
{
char c;
String s=new String("Java");
c=s.charAt(2);
System.out.println("Character: "+c);
}
}
Output
Character: v
toUpperCase()
toUpperCase(): This method is use to convert lower case string into upper case.Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java";
System.out.println("String: "+s.toUpperCase());
}
}
Output
String: JAVA
toLowerCase()
toLowerCase(): This method is used to convert lower case string into upper case.Example
class StringHandling
{
public static void main(String arg[])
{
String s="JAVA";
System.out.println("String: "+s.toLowerCase());
}
}
Output
String: java
concat()
concat(): This method is used to combined two string.Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
System.out.println("Combined String: "+s1.concat(s2));
}
}
Output
Combined String: HiteshRaddy
equals()
equals(): This method is used to compare two strings, It return true if strings are same otherwise return false. It is case sensitive method.Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
String s3="Hitesh";
System.out.println("Compare String: "+s1.equals(s2));
System.out.println("Compare String: "+s1.equals(s3));
}
}
Output
Compare String: false
Compare String: true
equalsIgnoreCase()
equalsIgnoreCase(): This method is case insensitive method, It return true if the contents of both strings are same otherwise false.Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="HITESH";
String s3="Raddy";
System.out.println("Compare String: "+s1.equalsIgnoreCase(s2));
System.out.println("Compare String: "+s1.equalsIgnoreCase(s3));
}
}
Output
Compare String: true
Compare String: false
compareTo()
compareTo(): This method is used to compare two strings by taking unicode values, It return 0 if the string are same otherwise return +ve or -ve integer values.Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
int i;
i=s1.compareTo(s2);
if(i==0)
{
System.out.println("Strings are same");
}
else
{
System.out.println("Strings are not same");
}
}
}
Output
Strings are not same
compareToIgnoreCase()
compareToIgnoreCase(): This method is case insensitive method, which is used to compare two strings similar to compareTo().Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="HITESH";
int i;
i=s1.compareToIgnoreCase(s2);
if(i==0)
{
System.out.println("Strings are same");
}
else
{
System.out.println("Strings are not same");
}
}
}
Output
Strings are same
startsWith()
startsWith(): This method return true if string is start with given another string, otherwise it returns false.Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.startsWith("Java"));
}
}
Output
true
endsWith()
endsWith(): This method return true if string is end with given another string, otherwise it returns false.Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.endsWith("language"));
}
}
Output
true
subString()
subString(): This method is used to get the part of given string.Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8)); // 8 is starting index
}
}
Output
programming language
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8, 12));
}
}
Output
prog
indexOf()
indexOf(): This method is used find the index value of given string. It always gives starting index value of first occurrence of string.Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.indexOf("programming"));
}
}
Output
8
lastIndexOf()
lastIndexOf(): This method used to return the starting index value of last occurence of the given string.Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Java is programming language";
String s2="Java is good programming language";
System.out.println(s1.lastIndexOf("programming"));
System.out.println(s2.lastIndexOf("programming"));
}
}
Output
8
13
trim()
trim(): This method remove space which are available before starting of string and after ending of string.Example
class StringHandling
{
public static void main(String arg[])
{
String s=" Java is programming language ";
System.out.println(s.trim());
}
}
Output
Java is programming language
split()
split(): This method is used to divide the given string into number of parts based on delimiter (special symbols like @ space , ).Example
class StringHandling
{
public static void main(String arg[])
{
String s="contact@tutorial4us.com";
String[] s1=s.split("@"); // divide string based on @
for(String c:s1) // foreach loop
{
System.out.println(c);
}
}
}
Output
contact
@tutorial4us.com
replace()
replace(): This method is used to return a duplicate string by replacing old character with new character.Note: In this method data of original string will never be modify.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="java";
String s2=s1.replace('j', 'k');
System.out.println(s2);
}
}
Output
kava
Exception Handling in Java
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.In this page, we will learn about java exception, its type and the difference between checked and unchecked exceptions.
What is exception
Dictionary Meaning: Exception is an abnormal condition.In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
What is exception handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.Advantage of Exception Handling
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;
- statement 5;//exception occurs
- statement 6;
- statement 7;
- statement 8;
- statement 9;
- statement 10;
Hierarchy of Java Exception classes
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:- Checked Exception
- Unchecked Exception
- 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
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.Common scenarios where exceptions may occur
There are given some scenarios where unchecked exceptions can occur. They are as follows:1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.- int a=50/0;//ArithmeticException
2) Scenario where NullPointerException occurs
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
3) Scenario where NumberFormatException occurs
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException.- String s="abc";
- int i=Integer.parseInt(s);//NumberFormatException
4) Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:- int a[]=new int[5];
- a[10]=50; //ArrayIndexOutOfBoundsException
Java Exception Handling Keywords
There are 5 keywords used in java exception handling.- try
- catch
- finally
- throw
- throws
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the method.Java try block must be followed by either catch or finally block.
Syntax of java try-catch
- try{
- //code that may throw exception
- }catch(Exception_class_Name ref){}
Syntax of try-finally block
- try{
- //code that may throw exception
- }finally{}
- public class Testtrycatch2{
- public static void main(String args[]){
- try{
- int data=50/0;
- }catch(ArithmeticException e){System.out.println(e);}
- System.out.println("rest of the code...");
- }
- }
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Java Multi catch block
If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block.Let's see a simple example of java multi-catch block.
- public class TestMultipleCatchBlock{
- public static void main(String args[]){
- try{
- int a[]=new int[5];
- a[5]=30/0;
- }
- catch(ArithmeticException e){System.out.println("task1 is completed");}
- catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
- catch(Exception e){System.out.println("common task completed");}
- System.out.println("rest of the code...");
- }
- }
Output:task1 completed
rest of the code...
Java nested try example
Let's see a simple example of java nested try block.- class Excep6{
- public static void main(String args[]){
- try{
- try{
- System.out.println("going to divide");
- int b =39/0;
- }catch(ArithmeticException e){System.out.println(e);}
- try{
- int a[]=new int[5];
- a[5]=4;
- }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
- System.out.println("other statement);
- }catch(Exception e){System.out.println("handeled");}
- System.out.println("normal flow..");
- }
- }
Usage of Java finally
- class TestFinallyBlock{
- public static void main(String args[]){
- try{
- int data=25/5;
- System.out.println(data);
- }
- catch(NullPointerException e){System.out.println(e);}
- finally{System.out.println("finally block is always executed");}
- System.out.println("rest of the code...");
- }
- }
Output:5
finally block is always executed
rest of the code...
Let's see the java finally example where exception occurs and not handled.
- class TestFinallyBlock1{
- public static void main(String args[]){
- try{
- int data=25/0;
- System.out.println(data);
- }
- catch(NullPointerException e){System.out.println(e);}
- finally{System.out.println("finally block is always executed");}
- System.out.println("rest of the code...");
- }
- }
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
java throw keyword example
In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.- 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...");
- }
- }
Exception in thread main java.lang.ArithmeticException:not valid
Java throws example
Let's see the example of java throws clause which describes that checked exceptions can be propagated by throws keyword.- import java.io.IOException;
- class Testthrows1{
- void m()throws IOException{
- throw new IOException("device error");//checked exception
- }
- void n()throws IOException{
- m();
- }
- void p(){
- try{
- n();
- }catch(Exception e){System.out.println("exception handled");}
- }
- public static void main(String args[]){
- Testthrows1 obj=new Testthrows1();
- obj.p();
- System.out.println("normal flow...");
- }
- }
exception handled
normal flow...
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side.Advantage of Applet
There are many advantages of applet. They are as follows:- It works at client side so less response time.
- Secured
- It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.
Drawback of Applet
- Plugin is required at client browser to execute applet.
Lifecycle of Java Applet
- Applet is initialized.
- Applet is started.
- Applet is painted.
- Applet is stopped.
- Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle methods for an applet.java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.- public void init(): is used to initialized the Applet. It is invoked only once.
- public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
- public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
- public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.- public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc.
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.How to run an Applet?
There are two ways to run an applet- By html file.
- By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet code in html file. Now click the html file.- //First.java
- import java.applet.Applet;
- import java.awt.Graphics;
- public class First extends Applet{
- public void paint(Graphics g){
- g.drawString("welcome",150,150);
- }
- }
Note: class must be public because its object is created by Java Plugin software that resides on the browser.
myapplet.html
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for testing purpose only.- //First.java
- import java.applet.Applet;
- import java.awt.Graphics;
- public class First extends Applet{
- public void paint(Graphics g){
- g.drawString("welcome to applet",150,150);
- }
- }
- /*
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
Commonly used methods of Graphics class:
- public abstract void drawString(String str, int x, int y): is used to draw the specified string.
- public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height.
- public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and specified width and height.
- public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and height.
- public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified width and height.
- public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2).
- public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image.
- public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or elliptical arc.
- public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or elliptical arc.
- public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
- public abstract void setFont(Font font): is used to set the graphics current font to the specified font.
- import java.applet.Applet;
- import java.awt.*;
- public class GraphicsDemo extends Applet{
- public void paint(Graphics g){
- g.setColor(Color.red);
- g.drawString("Welcome",50, 50);
- g.drawLine(20,30,20,300);
- g.drawRect(70,100,30,30);
- g.fillRect(170,100,30,30);
- g.drawOval(70,200,30,30);
- g.setColor(Color.pink);
- g.fillOval(170,200,30,30);
- g.drawArc(90,150,30,30,30,270);
- g.fillArc(270,150,30,30,0,180);
- }
- }
myapplet.html
Example of animation in applet:
- import java.awt.*;
- import java.applet.*;
- public class AnimationExample extends Applet {
- Image picture;
- public void init() {
- picture =getImage(getDocumentBase(),"bike_1.gif");
- }
- public void paint(Graphics g) {
- for(int i=0;i<500;i++){
- g.drawImage(picture, i,30, this);
- try{Thread.sleep(100);}catch(Exception e){}
- }
- }
- }
myapplet.html
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the simple example of event handling in applet that prints a message by click on the button.
|
- import java.applet.*;
- import java.awt.*;
- import java.awt.event.*;
- public class EventApplet extends Applet implements ActionListener{
- Button b;
- TextField tf;
- public void init(){
- tf=new TextField();
- tf.setBounds(30,40,150,20);
- b=new Button("Click");
- b.setBounds(80,150,60,50);
- add(b);add(tf);
- b.addActionListener(this);
- setLayout(null);
- }
- public void actionPerformed(ActionEvent e){
- tf.setText("Welcome");
- }
- }
In the above example, we have created all the controls in init() method because it is invoked only once.
|
myapplet.html
JApplet class in Applet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The JApplet class extends the Applet class.
|
- import java.applet.*;
- import javax.swing.*;
- import java.awt.event.*;
- public class EventJApplet extends JApplet implements ActionListener{
- JButton b;
- JTextField tf;
- public void init(){
- tf=new JTextField();
- tf.setBounds(30,40,150,20);
- b=new JButton("Click");
- b.setBounds(80,150,70,40);
- add(b);add(tf);
- b.addActionListener(this);
- setLayout(null);
- }
- public void actionPerformed(ActionEvent e){
- tf.setText("Welcome");
- }
- }
In the above example, we have created all the controls in init() method because it is invoked only once.
|
myapplet.html
Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of MouseMotionListener.
|
- import java.awt.*;
- import java.awt.event.*;
- import java.applet.*;
- public class MouseDrag extends Applet implements MouseMotionListener{
- public void init(){
- addMouseMotionListener(this);
- setBackground(Color.red);
- }
- public void mouseDragged(MouseEvent me){
- Graphics g=getGraphics();
- g.setColor(Color.white);
- g.fillOval(me.getX(),me.getY(),5,5);
- }
- public void mouseMoved(MouseEvent me){}
- }
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis and y-axis. The getGraphics() method of Component class returns the object of Graphics.
|
myapplet.html
- import java.applet.*;
- import java.awt.*;
- import java.util.*;
- import java.text.*;
- public class DigitalClock extends Applet implements Runnable {
- Thread t = null;
- int hours=0, minutes=0, seconds=0;
- String timeString = "";
- public void init() {
- setBackground( Color.green);
- }
- public void start() {
- t = new Thread( this );
- t.start();
- }
- public void run() {
- try {
- while (true) {
- Calendar cal = Calendar.getInstance();
- hours = cal.get( Calendar.HOUR_OF_DAY );
- if ( hours > 12 ) hours -= 12;
- minutes = cal.get( Calendar.MINUTE );
- seconds = cal.get( Calendar.SECOND );
- SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
- Date date = cal.getTime();
- timeString = formatter.format( date );
- repaint();
- t.sleep( 1000 ); // interval given in milliseconds
- }
- }
- catch (Exception e) { }
- }
- public void paint( Graphics g ) {
- g.setColor( Color.blue );
- g.drawString( timeString, 50, 50 );
- }
- }
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis and y-axis. The getGraphics() method of Component class returns the object of Graphics.
|
myapplet.html
Core Java Questions
What is JIT compiler?
Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.What is platform?
A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform.What is the main difference between Java platform and other platforms?
The Java platform differs from most other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms.It has two components:- Runtime Environment
- API(Application Programming Interface)
What gives Java its 'write once and run anywhere' nature?
The bytecode. Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform.What is classloader?
The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.Is Empty .java file name a valid source file name?
Yes, save your java file by .java only, compile it by javac .java and run by java yourclassname Let's take a simple example:- //save by .java only
- class A{
- public static void main(String args[]){
- System.out.println("Hello java");
- }
- }
- //compile by javac .java
- //run by java A
run it by java A
Is delete,next,main,exit or null keyword in java?
No.If I don't provide any arguments on the command line, then the String array of Main method will be empty or null?
It is empty. But not null.What if I write static public void instead of public static void?
Program compiles and runs properly.What is difference between object oriented programming language and object based programming language?
Object based programming languages follow all the features of OOPs except Inheritance. Examples of object based programming languages are JavaScript, VBScript etc.What will be the initial value of an object reference which is defined as an instance variable?
The object references are all initialized to null in Java.Is constructor inherited?
No, constructor is not inherited.Can you make a constructor final?
No, constructor can't be final.What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".Which class is the superclass for every class.
Object class.Why Java does not support pointers?
Pointer is a variable that refers to the memory address. They are not used in java because they are unsafe(unsecured) and complex to understand.Can you use this() and super() both in a constructor?
No. Because super() or this() must be the first statement.Can we override static method?
No, you can't override the static method because they are the part of class not object.Why we cannot override static method?
It is because the static method is the part of class and it is bound with class whereas instance method is bound with object and static gets memory in class area and instance gets memory in heap.Can we override the overloaded method?
Yes.Difference between method Overloading and Overriding.
Method Overloading
|
Method Overriding
|
1) Method overloading increases the readability of the program.
|
Method overriding provides the specific implementation of the method that is already provided by its super class.
|
2) method overlaoding is occurs within the class.
|
Method overriding occurs in two classes that have IS-A relationship.
|
3) In this case, parameter must be different.
|
In this case, parameter must be same.
|