Ravi Tutorials Provide Project Training

Java Tutorial







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.
  1. class Simple{
  2. public static void main(String args[]){
  3. System.out.println("Hello Java");
  4. }
  5. }

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:
  1. Desktop Applications such as acrobat reader, media player, antivirus etc.
  2. Web Applications such as irctc.co.in, javatpoint.com etc.
  3. Enterprise Applications such as banking applications.
  4. Mobile
  5. Embedded System
  6. Smart Card
  7. Robotics
  8. 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

  1.  
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.
  1. JDK Alpha and Beta (1995)
  2. JDK 1.0 (23rd Jan, 1996)
  3. JDK 1.1 (19th Feb, 1997)
  4. J2SE 1.2 (8th Dec, 1998)
  5. J2SE 1.3 (8th May, 2000)
  6. J2SE 1.4 (6th Feb, 2002)
  7. J2SE 5.0 (30th Sep, 2004)
  8. Java SE 6 (11th Dec, 2006)
  9. Java SE 7 (28th July, 2011)
  10. 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.
  1. Simple
  2. Object-Oriented
  3. Platform independent
  4. Secured
  5. Robust
  6. Architecture neutral
  7. Portable
  8. Dynamic
  9. Interpreted
  10. High Performance
  11. Multithreaded
  12. 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:
  1. Object
  2. Class
  3. Inheritance
  4. Polymorphism
  5. Abstraction
  6. Encapsulation

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:
  1. Runtime Environment
  2. API(Application Programming Interface)

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:
  • No explicit pointer
  • Programs run inside virtual machine sandbox.




  • Classloader- adds security by separating the package for the classes of the local file system from those that are imported from network sources.
  • Bytecode Verifier- checks the code fragments for illegal code that can violate access right to objects.
  • Security Manager- determines what resources a class can access such as reading and writing to the local disk.
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:
  1. class Simple{  
  2.     public static void main(String args[]){  
  3.      System.out.println("Hello Java");  
  4.     }  
  5. }  

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:
  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

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:
  1. 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.
  2. An implementation Its implementation is known as JRE (Java Runtime Environment).
  3. 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
JVM provides definitions for the:
  • 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
  • primitive data types
  • non-primitive 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.
  1. class CommandLineExample{  
  2. public static void main(String args[]){  
  3. System.out.println("Your first argument is: "+args[0]);  
  4. }  
  5. }  
  1. compile by > javac CommandLineExample.java  
  2. 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.
  1. class A{  
  2. public static void main(String args[]){  
  3.   
  4. for(int i=0;i
  5. System.out.println(args[i]);  
  6.   
  7. }  
  8. }  
  1. compile by > javac A.java  
  2. 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:
  1. class Operation{  
  2.  int data=50;  
  3.   
  4.  void change(int data){  
  5.  data=data+100;//changes will be in the local variable only  
  6.  }  
  7.      
  8.  public static void main(String args[]){  
  9.    Operation op=new Operation();  
  10.   
  11.    System.out.println("before change "+op.data);  
  12.    op.change(500);  
  13.    System.out.println("after change "+op.data);  
  14.   
  15.  }  
  16. }  
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,
  1. Byte Stream : It provides a convenient means for handling input and output of byte.
  2. Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses Unicode and therefore can be internationalized.

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

  1. dataType[] arr; (or)  
  2. dataType []arr; (or)  
  3. dataType arr[];  

Instantiation of an Array in java

  1. 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.
  1. class Testarray{  
  2. public static void main(String args[]){  
  3.   
  4. int a[]=new int[5];//declaration and instantiation  
  5. a[0]=10;//initialization  
  6. a[1]=20;  
  7. a[2]=70;  
  8. a[3]=40;  
  9. a[4]=50;  
  10.   
  11. //printing array  
  12. for(int i=0;i//length is the property of array
  

  • System.out.println(a[i]);  



  •   



  • }}  



  • Output: 10
           20
           70
           40
           50
          

    Declaration, Instantiation and Initialization of Java Array

    We can declare, instantiate and initialize the java array together by:
    1. int a[]={33,3,4,5};//declaration, instantiation and initialization  
    Let's see the simple example to print this array.
    1. class Testarray1{  
    2. public static void main(String args[]){  
    3.   
    4. int a[]={33,3,4,5};//declaration, instantiation and initialization  
    5.   
    6. //printing array  
    7. for(int i=0;i//length is the property of array
      

  • System.out.println(a[i]);  



  •   



  • }}  



  • 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.
    1. class Testarray2{  
    2. static void min(int arr[]){  
    3. int min=arr[0];  
    4. for(int i=1;i
    5.  if(min>arr[i])  
    6.   min=arr[i];  
    7.   
    8. System.out.println(min);  
    9. }  
    10.   
    11. public static void main(String args[]){  
    12.   
    13. int a[]={33,3,4,5};  
    14. min(a);//passing array to method  
    15.   
    16. }}  
    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

    1. dataType[][] arrayRefVar; (or)  
    2. dataType [][]arrayRefVar; (or)  
    3. dataType arrayRefVar[][]; (or)  
    4. dataType []arrayRefVar[];   

    Example to instantiate Multidimensional Array in java

    1. int[][] arr=new int[3][3];//3 row and 3 column  

    Example to initialize Multidimensional Array in java

    1. arr[0][0]=1;  
    2. arr[0][1]=2;  
    3. arr[0][2]=3;  
    4. arr[1][0]=4;  
    5. arr[1][1]=5;  
    6. arr[1][2]=6;  
    7. arr[2][0]=7;  
    8. arr[2][1]=8;  
    9. arr[2][2]=9;  

    Example of Multidimensional java array

    Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
    1. class Testarray3{  
    2. public static void main(String args[]){  
    3.   
    4. //declaring and initializing 2D array  
    5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};  
    6.   
    7. //printing 2D array  
    8. for(int i=0;i<3;i++){  
    9.  for(int j=0;j<3;j++){  
    10.    System.out.print(arr[i][j]+" ");  
    11.  }  
    12.  System.out.println();  
    13. }  
    14.   
    15. }}  
    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.
    1. class Testarray5{  
    2. public static void main(String args[]){  
    3. //creating two matrices  
    4. int a[][]={{1,3,4},{3,4,5}};  
    5. int b[][]={{1,3,4},{3,4,5}};  
    6.   
    7. //creating another matrix to store the sum of two matrices  
    8. int c[][]=new int[2][3];  
    9.   
    10. //adding and printing addition of 2 matrices  
    11. for(int i=0;i<2;i++){  
    12. for(int j=0;j<3;j++){  
    13. c[i][j]=a[i][j]+b[i][j];  
    14. System.out.print(c[i][j]+" ");  
    15. }  
    16. System.out.println();//new line  
    17. }  
    18.   
    19. }}  
    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 entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or logical (tengible and intengible). The example of integible object is banking system.
    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.
    A class in java can contain:
    • data member
    • method
    • constructor
    • block
    • class and interface

    Syntax to declare a class:

    1. class {  
    2.     data member;  
    3.     method;  
    4. }  

     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.
    class Student2{
    1.  int rollno;  
    2.  String name;  
    3.   
    4.  void insertRecord(int r, String n){  //method  
    5.   rollno=r;  
    6.   name=n;  
    7.  }  
    8.   
    9.  void displayInformation(){System.out.println(rollno+" "+name);}//method  
    10.   
    11.  public static void main(String args[]){  
    12.   Student2 s1=new Student2();  
    13.   Student2 s2=new Student2();  
    14.   
    15.   s1.insertRecord(111,"Karan");  
    16.   s2.insertRecord(222,"Aryan");  
    17.   
    18.   s1.displayInformation();  
    19.   s2.displayInformation();  
    20.   
    21.  }  
    22. }  
         

    Another Example of Object and Class

    1. class Rectangle{  
    2.  int length;  
    3.  int width;  
    4.   
    5.  void insert(int l,int w){  
    6.   length=l;  
    7.   width=w;  
    8.  }  
    9.   
    10.  void calculateArea(){System.out.println(length*width);}  
    11.   
    12.  public static void main(String args[]){  
    13.   Rectangle r1=new Rectangle();  
    14.   Rectangle r2=new Rectangle();  
    15.   
    16.   r1.insert(11,5);  
    17.   r2.insert(3,15);  
    18.   
    19.   r1.calculateArea();  
    20.   r2.calculateArea();  
    21. }  
    22. }  
    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.
    1. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects  
    Let's see the example:
    1. class Rectangle{  
    2.  int length;  
    3.  int width;  
    4.   
    5.  void insert(int l,int w){  
    6.   length=l;  
    7.   width=w;  
    8.  }  
    9.   
    10.  void calculateArea(){System.out.println(length*width);}  
    11.   
    12.  public static void main(String args[]){  
    13.   Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects  
    14.     
    15.   r1.insert(11,5);  
    16.   r2.insert(3,15);  
    17.   
    18.   r1.calculateArea();  
    19.   r2.calculateArea();  
    20. }  
    21. }  
    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

    1. By changing number of arguments
    2. By changing the data type

    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.
    1. class Calculation{  
    2.   void sum(int a,int b){System.out.println(a+b);}  
    3.   void sum(int a,int b,int c){System.out.println(a+b+c);}  
    4.   
    5.   public static void main(String args[]){  
    6.   Calculation obj=new Calculation();  
    7.   obj.sum(10,10,10);  
    8.   obj.sum(20,20);  
    9.   
    10.   }  
    11. }  
    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.
    1. class Calculation2{  
    2.   void sum(int a,int b){System.out.println(a+b);}  
    3.   void sum(double a,double b){System.out.println(a+b);}  
    4.   
    5.   public static void main(String args[]){  
    6.   Calculation2 obj=new Calculation2();  
    7.   obj.sum(10.5,10.5);  
    8.   obj.sum(20,20);  
    9.   
    10.   }  
    11. }  
    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:
    1. class Calculation3{  
    2.   int sum(int a,int b){System.out.println(a+b);}  
    3.   double sum(int a,int b){System.out.println(a+b);}  
    4.   
    5.   public static void main(String args[]){  
    6.   Calculation3 obj=new Calculation3();  
    7.   int result=obj.sum(20,20); //Compile Time Error  
    8.   
    9.   }  
    10. }  
    int result=obj.sum(20,20); //Here how can java determine which sum() method should be called

    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:
    1. class Overloading1{  
    2.   public static void main(int a){  
    3.   System.out.println(a);  
    4.   }  
    5.     
    6.   public static void main(String args[]){  
    7.   System.out.println("main() method invoked");  
    8.   main(10);  
    9.   }  
    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:
    As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int,long,float or double. The char datatype can be promoted to int,long,float or double and so on.

    Example of Method Overloading with TypePromotion

    1. class OverloadingCalculation1{  
    2.   void sum(int a,long b){System.out.println(a+b);}  
    3.   void sum(int a,int b,int c){System.out.println(a+b+c);}  
    4.   
    5.   public static void main(String args[]){  
    6.   OverloadingCalculation1 obj=new OverloadingCalculation1();  
    7.   obj.sum(20,20);//now second int literal will be promoted to long  
    8.   obj.sum(20,20,20);  
    9.   
    10.   }  
    11. }  
    Output:40
           60

    Constructor in Java

    Constructor 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 constructor

    There are basically two rules defined for the constructor.
    1. Constructor name must be same as its class name
    2. Constructor must have no explicit return type

    Types of java constructors

    There are two types of constructors:
    1. Default constructor (no-arg constructor)
    2. Parameterized constructor


    Java Default Constructor

    A constructor that have no parameter is known as default constructor.

    Syntax of default constructor:

    1. (){}  

    Example of default constructor

    In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
    1. class Bike1{  
    2. Bike1(){System.out.println("Bike is created");}  
    3. public static void main(String args[]){  
    4. Bike1 b=new Bike1();  
    5. }  
    6. }  
    Output:
    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

    1. class Student3{  
    2. int id;  
    3. String name;  
    4.   
    5. void display(){System.out.println(id+" "+name);}  
    6.   
    7. public static void main(String args[]){  
    8. Student3 s1=new Student3();  
    9. Student3 s2=new Student3();  
    10. s1.display();  
    11. s2.display();  
    12. }  
    13. }  
    Output:
    0 null
    0 null
    Explanation: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.
    A constructor that have parameters is known as parameterized constructor.

    Java parameterized constructor

    Why use parameterized constructor?

    Parameterized constructor is used to provide different values to the distinct objects.

    Example of parameterized constructor

    In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.
    1. class Student4{  
    2.     int id;  
    3.     String name;  
    4.       
    5.     Student4(int i,String n){  
    6.     id = i;  
    7.     name = n;  
    8.     }  
    9.     void display(){System.out.println(id+" "+name);}  
    10.    
    11.     public static void main(String args[]){  
    12.     Student4 s1 = new Student4(111,"Karan");  
    13.     Student4 s2 = new Student4(222,"Aryan");  
    14.     s1.display();  
    15.     s2.display();  
    16.    }  
    17. }  
    Output:
    111 Karan
    222 Aryan


    Constructor Overloading in Java

    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

    1. class Student5{  
    2.     int id;  
    3.     String name;  
    4.     int age;  
    5.     Student5(int i,String n){  
    6.     id = i;  
    7.     name = n;  
    8.     }  
    9.     Student5(int i,String n,int a){  
    10.     id = i;  
    11.     name = n;  
    12.     age=a;  
    13.     }  
    14.     void display(){System.out.println(id+" "+name+" "+age);}  
    15.    
    16.     public static void main(String args[]){  
    17.     Student5 s1 = new Student5(111,"Karan");  
    18.     Student5 s2 = new Student5(222,"Aryan",25);  
    19.     s1.display();  
    20.     s2.display();  
    21.    }  
    22. }  
    Output:
    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
    In this example, we are going to copy the values of one object into another using java constructor.
    1. class Student6{  
    2.     int id;  
    3.     String name;  
    4.     Student6(int i,String n){  
    5.     id = i;  
    6.     name = n;  
    7.     }  
    8.       
    9.     Student6(Student6 s){  
    10.     id = s.id;  
    11.     name =s.name;  
    12.     }  
    13.     void display(){System.out.println(id+" "+name);}  
    14.    
    15.     public static void main(String args[]){  
    16.     Student6 s1 = new Student6(111,"Karan");  
    17.     Student6 s2 = new Student6(s1);  
    18.     s1.display();  
    19.     s2.display();  
    20.    }  
    21. }  
    Output:
    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.
    1. class Student7{  
    2.     int id;  
    3.     String name;  
    4.     Student7(int i,String n){  
    5.     id = i;  
    6.     name = n;  
    7.     }  
    8.     Student7(){}  
    9.     void display(){System.out.println(id+" "+name);}  
    10.    
    11.     public static void main(String args[]){  
    12.     Student7 s1 = new Student7(111,"Karan");  
    13.     Student7 s2 = new Student7();  
    14.     s2.id=s1.id;  
    15.     s2.name=s1.name;  
    16.     s1.display();  
    17.     s2.display();  
    18.    }  
    19. }  

    Output:
    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:
    1. variable (also known as class variable)
    2. method (also known as class method)
    3. block
    4. nested class

    Java static property is shared to all objects.

    Example of static variable

    1. //Program of static variable  
    2.   
    3. class Student8{  
    4.    int rollno;  
    5.    String name;  
    6.    static String college ="ITS";  
    7.      
    8.    Student8(int r,String n){  
    9.    rollno = r;  
    10.    name = n;  
    11.    }  
    12.  void display (){System.out.println(rollno+" "+name+" "+college);}  
    13.   
    14.  public static void main(String args[]){  
    15.  Student8 s1 = new Student8(111,"Karan");  
    16.  Student8 s2 = new Student8(222,"Aryan");  
    17.    
    18.  s1.display();  
    19.  s2.display();  
    20.  }  
    21. }  
    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.
    1. class Counter{  
    2. int count=0;//will get memory when instance is created  
    3.   
    4. Counter(){  
    5. count++;  
    6. System.out.println(count);  
    7. }  
    8.   
    9. public static void main(String args[]){  
    10.   
    11. Counter c1=new Counter();  
    12. Counter c2=new Counter();  
    13. Counter c3=new Counter();  
    14.   
    15.  }  
    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.
    1. class Counter2{  
    2. static int count=0;//will get memory only once and retain its value  
    3.   
    4. Counter2(){  
    5. count++;  
    6. System.out.println(count);  
    7. }  
    8.   
    9. public static void main(String args[]){  
    10.   
    11. Counter2 c1=new Counter2();  
    12. Counter2 c2=new Counter2();  
    13. Counter2 c3=new Counter2();  
    14.   
    15.  }  
    16. }  
    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

    1. //Program of changing the common property of all objects(static field).  
    2.   
    3. class Student9{  
    4.      int rollno;  
    5.      String name;  
    6.      static String college = "ITS";  
    7.        
    8.      static void change(){  
    9.      college = "BBDIT";  
    10.      }  
    11.   
    12.      Student9(int r, String n){  
    13.      rollno = r;  
    14.      name = n;  
    15.      }  
    16.   
    17.      void display (){System.out.println(rollno+" "+name+" "+college);}  
    18.   
    19.     public static void main(String args[]){  
    20.     Student9.change();  
    21.   
    22.     Student9 s1 = new Student9 (111,"Karan");  
    23.     Student9 s2 = new Student9 (222,"Aryan");  
    24.     Student9 s3 = new Student9 (333,"Sonoo");  
    25.   
    26.     s1.display();  
    27.     s2.display();  
    28.     s3.display();  
    29.     }  
    30. }  
    Output:111 Karan BBDIT
           222 Aryan BBDIT
           333 Sonoo BBDIT

    Another example of static method that performs normal calculation

    1. //Program to get cube of a given number by static method  
    2.   
    3. class Calculate{  
    4.   static int cube(int x){  
    5.   return x*x*x;  
    6.   }  
    7.   
    8.   public static void main(String args[]){  
    9.   int result=Calculate.cube(5);  
    10.   System.out.println(result);  
    11.   }  
    12. }  
    Output:125

    Restrictions for static method

    There are two main restrictions for the static method. They are:

    1. The static method can not use non static data member or call non-static method directly.
    2. this and super cannot be used in static context.
    1. class A{  
    2.  int a=40;//non static  
    3.    
    4.  public static void main(String args[]){  
    5.   System.out.println(a);  
    6.  }  
    7. }        
    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

    1. class A2{  
    2.   static{System.out.println("static block is invoked");}  
    3.   public static void main(String args[]){  
    4.    System.out.println("Hello main");  
    5.   }  
    6. }  
    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.
    1. class A3{  
    2.   static{  
    3.   System.out.println("static block is invoked");  
    4.   System.exit(0);  
    5.   }  
    6. }  
    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.
    1. this keyword can be used to refer current class instance variable.
    2. this() can be used to invoke current class constructor.
    3. this keyword can be used to invoke current class method (implicitly)
    4. this can be passed as an argument in the method call.
    5. this can be passed as argument in the constructor call.
    6. this keyword can also be used to return the current class instance.
    Suggestion: If you are beginner to java, lookup only two usage of this keyword.
    1. //example of this keyword  
    2. class Student11{  
    3.     int id;  
    4.     String name;  
    5.       
    6.     Student11(int id,String name){  
    7.     this.id = id;  
    8.     this.name = name;  
    9.     }  
    10.     void display(){System.out.println(id+" "+name);}  
    11.     public static void main(String args[]){  
    12.     Student11 s1 = new Student11(111,"Karan");  
    13.     Student11 s2 = new Student11(222,"Aryan");  
    14.     s1.display();  
    15.     s2.display();  
    16. }  
    17. }  
    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.
    1. //Program of this() constructor call (constructor chaining)  
    2.   
    3. class Student13{  
    4.     int id;  
    5.     String name;  
    6.     Student13(){System.out.println("default constructor is invoked");}  
    7.       
    8.     Student13(int id,String name){  
    9.     this ();//it is used to invoked current class constructor.  
    10.     this.id = id;  
    11.     this.name = name;  
    12.     }  
    13.     void display(){System.out.println(id+" "+name);}  
    14.       
    15.     public static void main(String args[]){  
    16.     Student13 e1 = new Student13(111,"karan");  
    17.     Student13 e2 = new Student13(222,"Aryan");  
    18.     e1.display();  
    19.     e2.display();  
    20.    }  
    21. }  
    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

    1. class Subclass-name extends Superclass-name  
    2. {  
    3.    //methods and fields  
    4. }  
    The extends keyword indicates that you are making a new class that derives from an existing class.
    In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass.

    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.
    1. class Employee{  
    2.  float salary=40000;  
    3. }  
    4. class Programmer extends Employee{  
    5.  int bonus=10000;  
    6.  public static void main(String args[]){  
    7.    Programmer p=new Programmer();  
    8.    System.out.println("Programmer salary is:"+p.salary);  
    9.    System.out.println("Bonus of Programmer is:"+p.bonus);  
    10. }  
    11. }  

    Programmer salary is:40000.0
    Bonus of programmer is:10000
    In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.

    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.
    1. class A{  
    2. void msg(){System.out.println("Hello");}  
    3. }  
    4. class B{  
    5. void msg(){System.out.println("Welcome");}  
    6. }  
    7. class C extends A,B{//suppose if it were  
    8.    
    9.  Public Static void main(String args[]){  
    10.    C obj=new C();  
    11.    obj.msg();//Now which msg() method would be invoked?  
    12. }  
    13. }  
    Compile Time Error

    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

    1. method must have same name as in the parent class
    2. method must have same parameter as in the parent class.
    3. 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.
    1. class Vehicle{  
    2.   void run(){System.out.println("Vehicle is running");}  
    3. }  
    4. class Bike extends Vehicle{  
    5.     
    6.   public static void main(String args[]){  
    7.   Bike obj = new Bike();  
    8.   obj.run();  
    9.   }  
    10. }  
    Output:Vehicle is running
    Problem 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.
    1. class Vehicle{  
    2. void run(){System.out.println("Vehicle is running");}  
    3. }  
    4. class Bike2 extends Vehicle{  
    5. void run(){System.out.println("Bike is running safely");}  
    6.   
    7. public static void main(String args[]){  
    8. Bike2 obj = new Bike2();  
    9. obj.run();  
    10. }  
    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.
    1. class Bank{  
    2. int getRateOfInterest(){return 0;}  
    3. }  
    4.   
    5. class SBI extends Bank{  
    6. int getRateOfInterest(){return 8;}  
    7. }  
    8.   
    9. class ICICI extends Bank{  
    10. int getRateOfInterest(){return 7;}  
    11. }  
    12. class AXIS extends Bank{  
    13. int getRateOfInterest(){return 9;}  
    14. }  
    15.   
    16. class Test2{  
    17. public static void main(String args[]){  
    18. SBI s=new SBI();  
    19. ICICI i=new ICICI();  
    20. AXIS a=new AXIS();  
    21. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());  
    22. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());  
    23. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());  
    24. }  
    25. }  
    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

    1. class OverloadingExample{  
    2. static int add(int a,int b){return a+b;}  
    3. static int add(int a,int b,int c){return a+b+c;}  
    4. }  

    Java Method Overriding example

    1. class Animal{  
    2. void eat(){System.out.println("eating...");}  
    3. }  
    4. class Dog extends Animal{  
    5. void eat(){System.out.println("eating bread...");}  
    6. }  


    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

    1. super is used to refer immediate parent class instance variable.
    2. super() is used to invoke immediate parent class constructor.
    3. super is used to invoke immediate parent class method.

    1) super is used to refer immediate parent class instance variable.

    Problem without super keyword
    1. class Vehicle{  
    2.   int speed=50;  
    3. }  
    4. class Bike3 extends Vehicle{  
    5.   int speed=100;  
    6.   void display(){  
    7.    System.out.println(speed);//will print speed of Bike   
    8.   }  
    9.   public static void main(String args[]){  
    10.    Bike3 b=new Bike3();  
    11.    b.display();  
    12. }  
    13. }  
    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
    1. //example of super keyword  
    2.   
    3. class Vehicle{  
    4.   int speed=50;  
    5. }  
    6.   
    7. class Bike4 extends Vehicle{  
    8.   int speed=100;  
    9.       
    10.   void display(){  
    11.    System.out.println(super.speed);//will print speed of Vehicle now  
    12.   }  
    13.   public static void main(String args[]){  
    14.    Bike4 b=new Bike4();  
    15.    b.display();  
    16.      
    17. }  
    18. }  
    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:
    1. class Vehicle{  
    2.   Vehicle(){System.out.println("Vehicle is created");}  
    3. }  
    4.   
    5. class Bike5 extends Vehicle{  
    6.   Bike5(){  
    7.    super();//will invoke parent class constructor  
    8.    System.out.println("Bike is created");  
    9.   }  
    10.   public static void main(String args[]){  
    11.    Bike5 b=new Bike5();  
    12.         
    13. }  
    14. }  
    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.

    1. class Vehicle{  
    2.   Vehicle(){System.out.println("Vehicle is created");}  
    3. }  
    4.   
    5. class Bike6 extends Vehicle{  
    6.   int speed;  
    7.   Bike6(int speed){  
    8.     this.speed=speed;  
    9.     System.out.println(speed);  
    10.   }  
    11.   public static void main(String args[]){  
    12.    Bike6 b=new Bike6(10);  
    13.  }  
    14. }  
    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:
    1. class Person{  
    2. void message(){System.out.println("welcome");}  
    3. }  
    4.   
    5. class Student16 extends Person{  
    6. void message(){System.out.println("welcome to java");}  
    7.   
    8. void display(){  
    9. message();//will invoke current class message() method  
    10. super.message();//will invoke parent class message() method  
    11. }  
    12.   
    13. public static void main(String args[]){  
    14. Student16 s=new Student16();  
    15. s.display();  
    16. }  
    17. }  
    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

    1. class Person{  
    2. void message(){System.out.println("welcome");}  
    3. }  
    4.   
    5. class Student17 extends Person{  
    6.   
    7. void display(){  
    8. message();//will invoke parent class message() method  
    9. }  
    10.   
    11. public static void main(String args[]){  
    12. Student17 s=new Student17();  
    13. s.display();  
    14. }  
    15. }  
    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:
    1. variable
    2. method
    3. class
    The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.

    1) Java final variable

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

    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.
    1. class Bike9{  
    2.  final int speedlimit=90;//final variable  
    3.  void run(){  
    4.   speedlimit=400;  
    5.  }  
    6.  public static void main(String args[]){  
    7.  Bike9 obj=new  Bike9();  
    8.  obj.run();  
    9.  }  
    10. }//end of class  
    Output:Compile Time Error

    Is final method inherited?

    Ans) Yes, final method is inherited but you cannot override it. For Example:
    1. class Bike{  
    2.   final void run(){System.out.println("running...");}  
    3. }  
    4. class Honda2 extends Bike{  
    5.    public static void main(String args[]){  
    6.     new Honda2().run();  
    7.    }  
    8. }  
    Output:running...

    Que) Can we initialize blank final variable?

    Yes, but only in constructor. For example:
    1. class Bike10{  
    2.   final int speedlimit;//blank final variable  
    3.     
    4.   Bike10(){  
    5.   speedlimit=70;  
    6.   System.out.println(speedlimit);  
    7.   }  
    8.   
    9.   public static void main(String args[]){  
    10.     new Bike10();  
    11.  }  
    12. }  
    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

    1. class A{  
    2.   static final int data;//static blank final variable  
    3.   static{ data=50;}  
    4.   public static void main(String args[]){  
    5.     System.out.println(A.data);  
    6.  }  
    7. }  

    Q) What is final parameter?

    If you declare any parameter as final, you cannot change the value of it.
    1. class Bike11{  
    2.   int cube(final int n){  
    3.    n=n+2;//can't be changed as n is final  
    4.    n*n*n;  
    5.   }  
    6.   public static void main(String args[]){  
    7.     Bike11 b=new Bike11();  
    8.     b.cube(5);  
    9.  }  
    10. }  
    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.
    1. class Bike{  
    2.   void run(){System.out.println("running");}  
    3. }  
    4. class Splender extends Bike{  
    5.   void run(){System.out.println("running safely with 60km");}  
    6.   
    7.   public static void main(String args[]){  
    8.     Bike b = new Splender();//upcasting  
    9.     b.run();  
    10.   }  
    11. }  
    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.

    1. class Bike{  
    2.  int speedlimit=90;  
    3. }  
    4. class Honda3 extends Bike{  
    5.  int speedlimit=150;  
    6.   
    7.  public static void main(String args[]){  
    8.   Bike obj=new Honda3();  
    9.   System.out.println(obj.speedlimit);//90  
    10. }  
    Output:90

    Java Runtime Polymorphism with Multilevel Inheritance

    Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
    1. class Animal{  
    2. void eat(){System.out.println("eating");}  
    3. }  
    4.   
    5. class Dog extends Animal{  
    6. void eat(){System.out.println("eating fruits");}  
    7. }  
    8.   
    9. class BabyDog extends Dog{  
    10. void eat(){System.out.println("drinking milk");}  
    11.   
    12. public static void main(String args[]){  
    13. Animal a1,a2,a3;  
    14. a1=new Animal();  
    15. a2=new Dog();  
    16. a3=new BabyDog();  
    17.   
    18. a1.eat();  
    19. a2.eat();  
    20. a3.eat();  
    21. }  
    22. }  
    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
    1. static binding (also known as early binding).
    2. 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

    1. class Dog{  
    2.  private void eat(){System.out.println("dog is eating...");}  
    3.   
    4.  public static void main(String args[]){  
    5.   Dog d1=new Dog();  
    6.   d1.eat();  
    7.  }  
    8. }  

    Dynamic binding

    When type of the object is determined at run-time, it is known as dynamic binding.

    Example of dynamic binding

    1. class Animal{  
    2.  void eat(){System.out.println("animal is eating...");}  
    3. }  
    4.   
    5. class Dog extends Animal{  
    6.  void eat(){System.out.println("dog is eating...");}  
    7.   
    8.  public static void main(String args[]){  
    9.   Animal a=new Dog();  
    10.   a.eat();  
    11.  }  
    12. }  
    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
    1. Abstract class (0 to 100%)
    2. 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

    1. 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

    1. 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.
    1. abstract class Bike{  
    2.   abstract void run();  
    3. }  
    4.   
    5. class Honda4 extends Bike{  
    6. void run(){System.out.println("running safely..");}  
    7.   
    8. public static void main(String args[]){  
    9.  Bike obj = new Honda4();  
    10.  obj.run();  
    11. }  
    12. }  
    running safely..

    Another example of abstract class in java

    File: TestBank.java
    1.  abstract class Bank{    
    2. abstract int getRateOfInterest();    
    3. }    
    4.     
    5. class SBI extends Bank{    
    6. int getRateOfInterest(){return 7;}    
    7. }    
    8. class PNB extends Bank{    
    9. int getRateOfInterest(){return 7;}    
    10. }    
    11.     
    12. class TestBank{    
    13. public static void main(String args[]){    
    14. Bank b=new SBI();//if object is PNB, method of PNB will be invoked    
    15. int interest=b.getRateOfInterest();    
    16. System.out.println("Rate of Interest is: "+interest+" %");    
    17. }}    
    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
    1. //example of abstract class that have method body  
    2.  abstract class Bike{  
    3.    Bike(){System.out.println("bike is created");}  
    4.    abstract void run();  
    5.    void changeGear(){System.out.println("gear changed");}  
    6.  }  
    7.   
    8.  class Honda extends Bike{  
    9.  void run(){System.out.println("running safely..");}  
    10.  }  
    11.  class TestAbstraction2{  
    12.  public static void main(String args[]){  
    13.   Bike obj = new Honda();  
    14.   obj.run();  
    15.   obj.changeGear();  
    16.  }  
    17. }  
           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 and


    Simple example of Java interface

    In this example, Printable interface have only one method, its implementation is provided in the A class.
    1. interface printable{  
    2. void print();  
    3. }  
    4.   
    5. class A6 implements printable{  
    6. public void print(){System.out.println("Hello");}  
    7.   
    8. public static void main(String args[]){  
    9. A6 obj = new A6();  
    10. obj.print();  
    11.  }  
    12. }  
    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.
    1. interface Printable{  
    2. void print();  
    3. }  
    4.   
    5. interface Showable{  
    6. void show();  
    7. }  
    8.   
    9. class A7 implements Printable,Showable{  
    10.   
    11. public void print(){System.out.println("Hello");}  
    12. public void show(){System.out.println("Welcome");}  
    13.   
    14. public static void main(String args[]){  
    15. A7 obj = new A7();  
    16. obj.print();  
    17. obj.show();  
    18.  }  
    19. }  
    Output:Hello
           Welcome

    Interface inheritance

    A class implements interface but one interface extends another interface .
    1. interface Printable{  
    2. void print();  
    3. }  
    4. interface Showable extends Printable{  
    5. void show();  
    6. }  
    7. class Testinterface2 implements Showable{  
    8.   
    9. public void print(){System.out.println("Hello");}  
    10. public void show(){System.out.println("Welcome");}  
    11.   
    12. public static void main(String args[]){  
    13. Testinterface2 obj = new Testinterface2();  
    14. obj.print();  
    15. obj.show();  
    16.  }  
    17. }  
    Test it Now
           Hello
           Welcome

    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.
    1. //Creating interface that has 4 methods  
    2. interface A{  
    3. void a();//bydefault, public and abstract  
    4. void b();  
    5. void c();  
    6. void d();  
    7. }  
    8.   
    9. //Creating abstract class that provides the implementation of one method of A interface  
    10. abstract class B implements A{  
    11. public void c(){System.out.println("I am C");}  
    12. }  
    13.   
    14. //Creating subclass of abstract class, now we need to provide the implementation of rest of the methods  
    15. class M extends B{  
    16. public void a(){System.out.println("I am a");}  
    17. public void b(){System.out.println("I am b");}  
    18. public void d(){System.out.println("I am d");}  
    19. }  
    20.   
    21. //Creating a test class that calls the methods of A interface  
    22. class Test5{  
    23. public static void main(String args[]){  
    24. A a=new M();  
    25. a.a();  
    26. a.b();  
    27. a.c();  
    28. a.d();  
    29. }}  
    Output:
           I am a
           I am b
           I am c
           I am d

    Java Package

    1. Java Package
    2. Example of package
    3. Accessing package
      1. By import packagename.*
      2. By import packagename.classname
      3. By fully qualified name
    4. Subpackage
    5. Sending class file to another directory
    6. -classpath switch
    7. 4 ways to load the class file or jar file
    8. How to put two public class in a package
    9. Static Import
    10. Package class
    A java package is a group of similar types of classes, interfaces and sub-packages.
    Package in java can be categorized in two form, built-in package and user-defined package.
    There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
    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.
    1. //save as Simple.java  
    2. package mypack;  
    3. public class Simple{  
    4.  public static void main(String args[]){  
    5.     System.out.println("Welcome to package");  
    6.    }  
    7. }  

    How to compile java package

    If you are not using any IDE, you need to follow the syntax given below:
    1. javac -d directory javafilename  
    For example
    1. javac -d . Simple.java  
    The -d switch specifies the destination where to put the generated class file. You can use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use . (dot).

    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. import package.*;
    2. import package.classname;
    3. fully qualified name.

    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.*

    1. //save by A.java  
    2.   
    3. package pack;  
    4. public class A{  
    5.   public void msg(){System.out.println("Hello");}  
    6. }  
    1. //save by B.java  
    2.   
    3. package mypack;  
    4. import pack.*;  
    5.   
    6. class B{  
    7.   public static void main(String args[]){  
    8.    A obj = new A();  
    9.    obj.msg();  
    10.   }  
    11. }  
    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

    1. //save by A.java  
    2.   
    3. package pack;  
    4. public class A{  
    5.   public void msg(){System.out.println("Hello");}  
    6. }  
    1. //save by B.java  
    2.   
    3. package mypack;  
    4. import pack.A;  
    5.   
    6. class B{  
    7.   public static void main(String args[]){  
    8.    A obj = new A();  
    9.    obj.msg();  
    10.   }  
    11. }  
    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

    1. //save by A.java  
    2.   
    3. package pack;  
    4. public class A{  
    5.   public void msg(){System.out.println("Hello");}  
    6. }  
    1. //save by B.java  
    2.   
    3. package mypack;  
    4. class B{  
    5.   public static void main(String args[]){  
    6.    pack.A obj = new pack.A();//using fully qualified name  
    7.    obj.msg();  
    8.   }  
    9. }  
    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:
    1. private
    2. default
    3. protected
    4. 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.
    1. class A{  
    2. private int data=40;  
    3. private void msg(){System.out.println("Hello java");}  
    4. }  
    5.   
    6. public class Simple{  
    7.  public static void main(String args[]){  
    8.    A obj=new A();  
    9.    System.out.println(obj.data);//Compile Time Error  
    10.    obj.msg();//Compile Time Error  
    11.    }  
    12. }  

    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:
    1. class A{  
    2. private A(){}//private constructor  
    3. void msg(){System.out.println("Hello java");}  
    4. }  
    5. public class Simple{  
    6.  public static void main(String args[]){  
    7.    A obj=new A();//Compile Time Error  
    8.  }  
    9. }  

    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.
    1. //save by A.java  
    2. package pack;  
    3. class A{  
    4.   void msg(){System.out.println("Hello");}  
    5. }  
    1. //save by B.java  
    2. package mypack;  
    3. import pack.*;  
    4. class B{  
    5.   public static void main(String args[]){  
    6.    A obj = new A();//Compile Time Error  
    7.    obj.msg();//Compile Time Error  
    8.   }  
    9. }  
    In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.

    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.
    1. //save by A.java  
    2. package pack;  
    3. public class A{  
    4. protected void msg(){System.out.println("Hello");}  
    5. }  
    1. //save by B.java  
    2. package mypack;  
    3. import pack.*;  
    4.   
    5. class B extends A{  
    6.   public static void main(String args[]){  
    7.    B obj = new B();  
    8.    obj.msg();  
    9.   }  
    10. }  
    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

    1. //save by A.java  
    2.   
    3. package pack;  
    4. public class A{  
    5. public void msg(){System.out.println("Hello");}  
    6. }  
    1. //save by B.java  
    2.   
    3. package mypack;  
    4. import pack.*;  
    5.   
    6. class B{  
    7.   public static void main(String args[]){  
    8.    A obj = new A();  
    9.    obj.msg();  
    10.   }  
    11. }  
    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:
    1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};  
    2. String s=new String(ch);  
    is same as:
    1. 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. By string literal
    2. By new keyword

    1) String Literal

    Java String literal is created by using double quotes. For Example:
    1. 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

    1. String s=new String("Welcome");//creates two objects and one reference variable  
    In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).

    Java String Example

    1. public class StringExample{  
    2. public static void main(String args[]){  
    3. String s1="java";//creating string by java string literal  
    4.   
    5. char ch[]={'s','t','r','i','n','g','s'};  
    6. String s2=new String(ch);//converting char array to string  
    7.   
    8. String s3=new String("example");//creating java string by new keyword  
    9.   
    10. System.out.println(s1);  
    11. System.out.println(s2);  
    12. System.out.println(s3);  
    13. }}  
    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

    java
    Explanation: 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:
    1. statement 1;  
    2. statement 2;  
    3. statement 3;  
    4. statement 4;  
    5. statement 5;//exception occurs  
    6. statement 6;  
    7. statement 7;  
    8. statement 8;  
    9. statement 9;  
    10. statement 10;  
    Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the exception will be executed. That is why we use exception handling in java.


    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:
    1. Checked Exception
    2. Unchecked Exception
    3. Error

    Difference between checked and unchecked exceptions

    1) Checked Exception

    The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

    2) Unchecked Exception

    The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

    3) Error

    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.
    1. 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.
    1. String s=null;  
    2. 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.
    1. String s="abc";  
    2. 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:
    1. int a[]=new int[5];  
    2. a[10]=50//ArrayIndexOutOfBoundsException  

    Java Exception Handling Keywords

    There are 5 keywords used in java exception handling.
    1. try
    2. catch
    3. finally
    4. throw
    5. 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

    1. try{  
    2. //code that may throw exception  
    3. }catch(Exception_class_Name ref){}  

    Syntax of try-finally block

    1. try{  
    2. //code that may throw exception  
    3. }finally{}  
    4. public class Testtrycatch2{  
    5.   public static void main(String args[]){  
    6.    try{  
    7.       int data=50/0;  
    8.    }catch(ArithmeticException e){System.out.println(e);}  
    9.    System.out.println("rest of the code...");  
    10. }  
    11. }  
    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.
    1. public class TestMultipleCatchBlock{  
    2.   public static void main(String args[]){  
    3.    try{  
    4.     int a[]=new int[5];  
    5.     a[5]=30/0;  
    6.    }  
    7.    catch(ArithmeticException e){System.out.println("task1 is completed");}  
    8.    catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}  
    9.    catch(Exception e){System.out.println("common task completed");}  
    10.   
    11.    System.out.println("rest of the code...");  
    12.  }  
    13. }  
    Output:task1 completed
           rest of the code...

    Java nested try example

    Let's see a simple example of java nested try block.
    1. class Excep6{  
    2.  public static void main(String args[]){  
    3.   try{  
    4.     try{  
    5.      System.out.println("going to divide");  
    6.      int b =39/0;  
    7.     }catch(ArithmeticException e){System.out.println(e);}  
    8.    
    9.     try{  
    10.     int a[]=new int[5];  
    11.     a[5]=4;  
    12.     }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}  
    13.      
    14.     System.out.println("other statement);  
    15.   }catch(Exception e){System.out.println("handeled");}  
    16.   
    17.   System.out.println("normal flow..");  
    18.  }  
    19. }  

    Usage of Java finally

    1. class TestFinallyBlock{  
    2.   public static void main(String args[]){  
    3.   try{  
    4.    int data=25/5;  
    5.    System.out.println(data);  
    6.   }  
    7.   catch(NullPointerException e){System.out.println(e);}  
    8.   finally{System.out.println("finally block is always executed");}  
    9.   System.out.println("rest of the code...");  
    10.   }  
    11. }  
    Output:5
           finally block is always executed
           rest of the code...
    Let's see the java finally example where exception occurs and not handled.
    1. class TestFinallyBlock1{  
    2.   public static void main(String args[]){  
    3.   try{  
    4.    int data=25/0;  
    5.    System.out.println(data);  
    6.   }  
    7.   catch(NullPointerException e){System.out.println(e);}  
    8.   finally{System.out.println("finally block is always executed");}  
    9.   System.out.println("rest of the code...");  
    10.   }  
    11. }  
    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.
    1. public class TestThrow1{  
    2.    static void validate(int age){  
    3.      if(age<18)  
    4.       throw new ArithmeticException("not valid");  
    5.      else  
    6.       System.out.println("welcome to vote");  
    7.    }  
    8.    public static void main(String args[]){  
    9.       validate(13);  
    10.       System.out.println("rest of the code...");  
    11.   }  
    12. }  
    Output:
    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.
    1. import java.io.IOException;  
    2. class Testthrows1{  
    3.   void m()throws IOException{  
    4.     throw new IOException("device error");//checked exception  
    5.   }  
    6.   void n()throws IOException{  
    7.     m();  
    8.   }  
    9.   void p(){  
    10.    try{  
    11.     n();  
    12.    }catch(Exception e){System.out.println("exception handled");}  
    13.   }  
    14.   public static void main(String args[]){  
    15.    Testthrows1 obj=new Testthrows1();  
    16.    obj.p();  
    17.    System.out.println("normal flow...");  
    18.   }  
    19. }  
    Output:
    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

    1. Applet is initialized.
    2. Applet is started.
    3. Applet is painted.
    4. Applet is stopped.
    5. 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.
    1. public void init(): is used to initialized the Applet. It is invoked only once.
    2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
    3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
    4. 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.
    1. 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
    1. By html file.
    2. 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.
    1. //First.java  
    2. import java.applet.Applet;  
    3. import java.awt.Graphics;  
    4. public class First extends Applet{  
    5.   
    6. public void paint(Graphics g){  
    7. g.drawString("welcome",150,150);  
    8. }  
    9.   
    10. }  

    Note: class must be public because its object is created by Java Plugin software that resides on the browser.

    myapplet.html

    1.   
    2.   
    3. "First.class"
     width="300" height="300">  




  •  




  •  




  •   

    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.
    1. //First.java  
    2. import java.applet.Applet;  
    3. import java.awt.Graphics;  
    4. public class First extends Applet{  
    5.   
    6. public void paint(Graphics g){  
    7. g.drawString("welcome to applet",150,150);  
    8. }  
    9.   
    10. }  
    11. /* 
    12.  
     

  • */  


  • 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:

    1. public abstract void drawString(String str, int x, int y): is used to draw the specified string.
    2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height.
    3. 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.
    4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and height.
    5. 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.
    6. 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).
    7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image.
    8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or elliptical arc.
    9. 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.
    10. public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
    11. public abstract void setFont(Font font): is used to set the graphics current font to the specified font.
    1. import java.applet.Applet;  
    2. import java.awt.*;  
    3.   
    4. public class GraphicsDemo extends Applet{  
    5.   
    6. public void paint(Graphics g){  
    7. g.setColor(Color.red);  
    8. g.drawString("Welcome",5050);  
    9. g.drawLine(20,30,20,300);  
    10. g.drawRect(70,100,30,30);  
    11. g.fillRect(170,100,30,30);  
    12. g.drawOval(70,200,30,30);  
    13.   
    14. g.setColor(Color.pink);  
    15. g.fillOval(170,200,30,30);  
    16. g.drawArc(90,150,30,30,30,270);  
    17. g.fillArc(270,150,30,30,0,180);  
    18.   
    19. }  
    20. }  

    myapplet.html

    1.   
    2.   
    3. "GraphicsDemo.class"
     width="300" height="300">  




  •  




  •  




  •   

    Example of animation in applet:

    1. import java.awt.*;  
    2. import java.applet.*;  
    3. public class AnimationExample extends Applet {  
    4.   
    5.   Image picture;  
    6.   
    7.   public void init() {  
    8.     picture =getImage(getDocumentBase(),"bike_1.gif");  
    9.   }  
    10.     
    11.   public void paint(Graphics g) {  
    12.     for(int i=0;i<500;i++){  
    13.       g.drawImage(picture, i,30this);  
    14.   
    15.       try{Thread.sleep(100);}catch(Exception e){}  
    16.     }  
    17.   }  
    18. }  

    myapplet.html

    1.   
    2.   
    3. "
    AnimationExample " width="300" height="300">  




  •  




  •  




  •   

    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.
    1. import java.applet.*;  
    2. import java.awt.*;  
    3. import java.awt.event.*;  
    4. public class EventApplet extends Applet implements ActionListener{  
    5. Button b;  
    6. TextField tf;  
    7.   
    8. public void init(){  
    9. tf=new TextField();  
    10. tf.setBounds(30,40,150,20);  
    11.   
    12. b=new Button("Click");  
    13. b.setBounds(80,150,60,50);  
    14.   
    15. add(b);add(tf);  
    16. b.addActionListener(this);  
    17.   
    18. setLayout(null);  
    19. }  
    20.   
    21.  public void actionPerformed(ActionEvent e){  
    22.   tf.setText("Welcome");  
    23.  }   
    24. }  
    In the above example, we have created all the controls in init() method because it is invoked only once.

    myapplet.html

    1.   
    2.   
    3. "EventApplet.class"
     width="300" height="300">  




  •  




  •  




  •   

    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.
    1. import java.applet.*;  
    2. import javax.swing.*;  
    3. import java.awt.event.*;  
    4. public class EventJApplet extends JApplet implements ActionListener{  
    5. JButton b;  
    6. JTextField tf;  
    7. public void init(){  
    8.   
    9. tf=new JTextField();  
    10. tf.setBounds(30,40,150,20);  
    11.   
    12. b=new JButton("Click");  
    13. b.setBounds(80,150,70,40);  
    14.   
    15. add(b);add(tf);  
    16. b.addActionListener(this);  
    17.   
    18. setLayout(null);  
    19. }  
    20.   
    21. public void actionPerformed(ActionEvent e){  
    22. tf.setText("Welcome");  
    23. }  
    24. }  
    In the above example, we have created all the controls in init() method because it is invoked only once.

    myapplet.html

    1.   
    2.   
    3. "EventJApplet.class"
     width="300" height="300">  




  •  




  •  




  •   

    Painting in Applet
    We can perform painting operation in applet by the mouseDragged() method of MouseMotionListener.
    1. import java.awt.*;  
    2. import java.awt.event.*;  
    3. import java.applet.*;  
    4. public class MouseDrag extends Applet implements MouseMotionListener{  
    5.   
    6. public void init(){  
    7. addMouseMotionListener(this);  
    8. setBackground(Color.red);  
    9. }  
    10.   
    11. public void mouseDragged(MouseEvent me){  
    12. Graphics g=getGraphics();  
    13. g.setColor(Color.white);  
    14. g.fillOval(me.getX(),me.getY(),5,5);  
    15. }  
    16. public void mouseMoved(MouseEvent me){}  
    17.   
    18. }  
    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

    1.   
    2.   
    3. "MouseDrag.class"
     width="300" height="300">  




  •  




  •  




  •   
    1. import java.applet.*;  
    2. import java.awt.*;  
    3. import java.util.*;  
    4. import java.text.*;  
    5.   
    6. public class DigitalClock extends Applet implements Runnable {  
    7.   
    8.    Thread t = null;  
    9.    int hours=0, minutes=0, seconds=0;  
    10.    String timeString = "";  
    11.   
    12.    public void init() {  
    13.       setBackground( Color.green);  
    14.    }  
    15.   
    16.    public void start() {  
    17.         t = new Thread( this );  
    18.         t.start();  
    19.    }  
    20.   
    21.     
    22.    public void run() {  
    23.       try {  
    24.          while (true) {  
    25.   
    26.             Calendar cal = Calendar.getInstance();  
    27.             hours = cal.get( Calendar.HOUR_OF_DAY );  
    28.             if ( hours > 12 ) hours -= 12;  
    29.             minutes = cal.get( Calendar.MINUTE );  
    30.             seconds = cal.get( Calendar.SECOND );  
    31.   
    32.             SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");  
    33.             Date date = cal.getTime();  
    34.             timeString = formatter.format( date );  
    35.   
    36.             repaint();  
    37.             t.sleep( 1000 );  // interval given in milliseconds  
    38.          }  
    39.       }  
    40.       catch (Exception e) { }  
    41.    }  
    42.   
    43.     
    44.   public void paint( Graphics g ) {  
    45.       g.setColor( Color.blue );  
    46.       g.drawString( timeString, 5050 );  
    47.    }  
    48. }  
    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

    1.   
    2.   
    3. "DigitalClock.class"
     width="300" height="300">  




  •  




  •  




  •   

    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:
    1. Runtime Environment
    2. 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:
    1. //save by .java only  
    2. class A{  
    3. public static void main(String args[]){  
    4. System.out.println("Hello java");  
    5. }  
    6. }  
    7. //compile by javac .java  
    8. //run by     java A  
    compile it by javac .java
    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.

    Can you have virtual functions in Java?

    Yes, all functions in Java are virtual by default.