Java Notes
Java Notes
Born
This language was developed at SUN Microsystems in the year 1995 under the guidance
of James Gosling and there team.
Overview of Java
Java is one of the programming language or technology used for developing web
applications. Java language developed at SUN Micro Systems in the year 1995 under the
guidance of James Gosling and there team. Originally SUN Micro Systems is one of the
Academic University (Stanford University Network)
Whatever the software developed in the year 1990, SUN Micro Systems has released on
the name of oak, which is original name of java (scientifically oak is one of the tree
name). The OAK has taken 18 months to develop.
The oak is unable to fulfill all requirements of the industry. So James Gosling again
reviews this oak and released with the name of java in the year 1995. Scientifically java
is one of the coffee seed name.
Java divided into three categories, they are
J2SE (Java 2 Standard Edition)
J2EE (Java 2 Enterprise Edition)
J2ME (Java 2 Micro or Mobile Edition)
J2SE
J2SE is used for developing client side applications.
J2EE
J2EE is used for developing server side applications.
J2ME
J2ME is used for developing mobile or wireless application by making use of a
predefined protocol called WAP (wireless Access / Application protocol).
Features of Java
Features of a language are nothing but the set of services or facilities provided by the
language vendors to the industry programmers. Some important features of java are;
Important Features of Java
Simple
Platform Independent
Architectural Neutral
Portable
Multi Threading
Distributed
Networked
Robust
Dynamic
Secured
High Performance
Interpreted
Object Oriented
1. Simple
It is simple because of the following factors:
It is free from pointer due to this execution time of application is improve. [Whenever we
write a Java program without pointers then internally it is converted into the equivalent
pointer program].
It has Rich set of API (application protocol interface).
It has Garbage Collector which is always used to collect un-Referenced (unused) Memory
location for improving performance of a Java program.
It contains user friendly syntax for developing any applications.
2. Platform Independent
A program or technology is said to be platform independent if and only if which can run
on all available operating systems with respect to its development and compilation.
(Platform represents O.S).
3. Architectural Neutral
Architecture represents processor.
A Language or Technology is said to be Architectural neutral which can run on any
available processors in the real world without considering there architecture and vendor
(providers) irrespective to its development and compilation.
The languages like C, CPP are treated as architectural dependent.
4. Portable
If any language supports platform independent and architectural neutral feature known
as portable. The languages like C, CPP, and Pascal are treated as non-portable language.
It is a portable language.
According to SUN Microsystems.
5. Multithreaded
A flow of control is known as thread. When any Language executes multiple threads at a
time that language is known as multithreaded Language. It is multithreaded Language.
6. Distributed
Using this language we can create distributed application. RMI and EJB are used for
creating distributed applications. In distributed application multiple client system are
depends on multiple server systems so that even problem occurred in one server will
never be reflected on any client system.
Datatype is a special keyword used to allocate sufficient memory space for the data, in
other words Data type is used for representing the data in main memory (RAM) of the
computer.
In general every programming language is containing three categories of data types. They
are
Fundamental or primitive data types
Derived data types
User defined data types.
Syntax
Variable_name = value;
Rules to declare a Variable
Every variable name should start with either alphabets or underscore (_) or dollar
($) symbol.
No space is allowed in the variable declarations.
Except underscore ( _ ) no special symbol are allowed in the middle of variable
declaration
Variable name always should exist in the left hand side of assignment operators.
Maximum length of variable is 64 characters.
No keywords should access variable name.
Note: Actually a variable also can start with ¥, ¢, or any other currency sign.
Example of Variable Declaration
class Sum
{
public static void main(String[] args)
{
int _a, ¢b, ¥c, $d, result;
_a=10;
¢b=20;
¥c=30;
$d=40;
result=_a+¢b+¥c+$d;
System.out.println("Sum is :" +result);
}
}
Output
Sum is : 100
Variable declarations
In which sufficient memory will be allocated and holds default values.
Syntax
Datatype variable_name;
byte b1;
Variable initialization
It is the process of storing user defined values at the time of allocation of memory space.
Variable assignment
Value is assigned to a variable if that is already declared or initialized.
Syntax
Variable_Name = value
int a = 100;
Syntax
int a= 100;
int b;
b = 25; // ------> direct assigned variable
b = a; // ------> assigned value in term of variable
b = a+15; // ------> assigned value as term of expression
Operators in Java
Operator is a special symbol that tells the compiler to perform specific mathematical or
logical Operation. Java supports following lists of operators.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Ternary or Conditional Operators
Arithmetic Operators
Given table shows the entire Arithmetic operator supported by Java Language. Let’s
suppose variable A hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
Relational Operators
Which can be used to check the Condition, it always returns true or false. Let’s suppose
variable A hold 8 and B hold 3.
Operators Example (int A=8, B=3) Result
< A<B False
<= A<=10 True
> A>B True
>= A<=B False
== A== B False
!= A!=(-4) True
Logical Operators
Which can be used to combine more than one Condition? Suppose you want to
combined two conditions A<B and B>C, then you need to use Logical Operator like
(A<B) && (B>C). Here && is Logical Operator.
Operator Example (int A=8, B=3, C=-10) Result
&& (A<B) && (B>C) False
|| (B!=-C) || (A==B) True
! !(B<=-A) True
Truth table of Logical Operator
C1 C2 C1 && C2 C1 || C2 !C1 !C2
T T T T F F
T F F T F T
F T F T T F
F F F F T T
Assignment operators
Which can be used to assign a value to a variable? Let’s suppose variable A hold 8 and B
hold 3.
Operator Example (int A=8, B=3) Result
+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
=a=b Value of b will be assigned to a
Ternary operator
If any operator is used on three operands or variable is known as ternary operator. It can
be represented with “?:”
Array in java
Array is a collection of similar type of data. It is fixed in size that means you can't
increase the size of array at run time. It is collection of homogeneous data elements. It
store the value on the basis of index value.
Advantage of Array
One variable can store multiple value: The main advantage of array is we can
represent multiple value under the same name.
Code Optimization: No, need to declare a lot of variable of same type data, We can
retrieve and short data easily.
Random access: We can retrieve any data from array with the help of index value.
Disadvantage of Array
The main limitation of array is Size Limit when once we declare array there is no
chance to increase and decrease the size of array according to our requirement, Hence
memory point of view array concept is not recommended to use. To over come this
limitation in java introduce collection concept.
Types of Array
There are two types of array in java.
Single Dimensional Array
Multidimensional Array
Array Declaration
Single dimension array declaration.
Syntax
1. int[] a;
2. int a[];
3. int []a;
Note: At the time of array declaration we can not specify the size of array. For Example
int[5] a; this is wrong.
2D Array declaration.
Syntax
1. int[][] a;
2. int a[][];
3. int [][]a;
4. int[] a[];
5. int[] []a;
6. int []a[];
Array creation
Every array in a java is an object, hence we can create array by using new keyword.
Syntax
int[] arr = new int[10]; // The size of array is 10.
or
int[] arr = {10,20,30,40,50};
Accessing array elements
Access the elements of array by using index value of an elements.
Syntax
arrayname[n-1];
Access Array Elements
int[] arr={10,20,30,40};
System.out.println("Element at 4th place"+arr[2]);
Example of Array
public class ArrayEx
{
public static void main(String []args)
{
int arr[] = {10,20,30};
for (int i=0; i < arr.length; i++)
{
System.out.println(arr[i]);
}
}
}
Output
10
20
39
Note:
1) At the time of array creation we must be specify the size of array otherwise get an
compile time error. For Example
int[] a=new int[]; Invalid.
int[] a=new int[5]; Valid
2) If we specify array size as negative int value, then we will get run-time error,
NegativeArraySizeException.
3) To specify array size the allowed data types are byte, short, int, char If we use other
data type then we will get an Compile time error.
4) The maximum allowed size of array in java is 2147483647 (It is maximum value of int
data type)
Difference Between Length and Length() in Java
length: It is a final variable and only applicable for array. It represent size of array.
Example
int[] a=new int[10];
System.out.println(a.length); // 10
System.out.println(a.length()); // Compile time error
length(): It is final method applicable only for String objects. It represent number of
character present in String.
Example
String s="Java";
System.out.println(s.length()); // 4
System.out.println(s.length); // Compile time error
Syntax
if(condition)
{
Statement(s)
}
Example if statement
class Hello
{
int a=10;
public static void main(String[] args)
{
if(a<15)
{
System.out.println("Hello good morning!");
}
}
}
Output
Hello good morning
if-else statement
In general it can be used to execute one block of statement among two blocks, in java
language if and else are the keyword in java.
Syntax
if(condition)
{
Statement(s)
}
else
{
Statement(s)
}
........
In the above syntax whenever condition is true all the if block statement are executed,
remaining statement of the program by neglecting. If the condition is false else block
statement executed and neglecting if block statements.
Example if else
import java.util.Scanner;
class Oddeven
{
public static void main(String[] args)
{
int no;
Scanner s=new Scanner(System.in);
System.out.println("Enter any number :");
no=s.nextInt();
if(no%2==0)
{
System.out.println("Even number");
}
else
{
System.out.println("Odd number");
}
}
}
Output
Enter any number :
10
Even number
Switch Statement
The switch statement in java language is used to execute the code from multiple
conditions or case. It is same like if else-if ladder statement.
A switch statement work with byte, short, char and int primitive data type, it also works
with enumerated types and string.
Syntax
switch(expression/variable)
{
case value:
//statements
// any number of case statements
break; //optional
default: //optional
//statements
}
Rules for apply switch statement
With switch statement use only byte, short, int, char data type (float data type is not
allowed). You can use any number of case statements within a switch. Value for a case
must be same as the variable in switch.
Limitations of switch statement
Logical operators cannot be used with switch statement. For instance
Example
case k>=20: // not allowed
Example of switch case
import java.util.*;
class switchCase
{
public static void main(String arg[])
{
int ch;
System.out.println("Enter any number (1 to 7) :");
Scanner s=new Scanner(System.in);
ch=s.nextInt();
switch(ch)
{
case 1:
System.out.println("Today is Monday");
break;
case 2:
System.out.println("Today is Tuesday");
break;
case 3:
System.out.println("Today is Wednesday");
break;
case 4:
System.out.println("Today is Thursday");
break;
case 5:
System.out.println("Today is Friday");
break;
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
default:
System.out.println("Only enter value 1 to 7");
}
}
}
Output
Enter any number (1 to 7) :
5
Today is Friday
Looping statement
Looping statements are the statements execute one or more statement repeatedly
several number of times. In java programming language there are three types of loops;
while, for and do-while.
Why use loop?
When you need to execute a block of code several number of times then you need to use
looping concept in Java language.
Advantage with looping statement
Reduce length of Code
Take less memory space.
Burden on the developer is reducing.
Time consuming process to execute the program is reduced.
Difference between conditional and looping statement
Conditional statement executes only once in the program where as looping statements
executes repeatedly several number of time.
While loop
In while loop first check the condition if condition is true then control goes inside the
loop body otherwise goes outside of the body. while loop will be repeats in clock wise
direction.
Syntax
while(condition)
{
Statement(s)
Increment / decrements (++ or --);
}
Example while loop
class whileDemo
{
public static void main(String args[])
{
int i=0;
while(i<5)
{
System.out.println(+i);
i++;
}
Output
1
2
3
4
5
for loop
for loop is a statement which allows code to be repeatedly executed. For loop contains 3
parts Initialization, Condition and Increment or Decrements
Syntax
for ( initialization; condition; increment )
{
statement(s);
}
Initialization: This step is executed first and this is executed only once when we are
entering into the loop first time. This step is allowed to declare and initialize any loop
control variables.
Condition: This is next step after initialization step, if it is true, the body of the loop is
executed, if it is false then the body of the loop does not execute and flow of control goes
outside of the for loop.
Increment or Decrements: After completion of Initialization and Condition steps loop
body code is executed and then Increment or Decrements steps is execute. This statement
allows updating any loop control variables.
Flow Diagram
The path is required to be set for using tools such as javac, java etc.
If you are saving the java source file inside the jdk/bin directory, path is not required to be set because all the
tools will be available in the current directory.
But If you are having your java file outside the jdk/bin folder, it is necessary to set path of JDK.
There are 2 ways to set java path:
1. temporary
2. permanent
1) How to set Temporary Path of JDK in Windows
To set the temporary path of JDK, you need to follow following steps:
Open command prompt
copy the path of jdk/bin directory
write in command prompt: set path=copied_path
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
Let's see it in the figure given below:
2) How to set Permanent Path of JDK in Windows
For setting the permanent path of JDK, you need to follow these steps:
Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user variable -> write
path in variable name -> write path of bin folder in variable value -> ok -> ok -> ok
For Example:
1)Go to MyComputer properties
8)click on ok button
9)click on ok button
Now your permanent path is set. You can now execute any program of java from any drive.
Understanding the difference between JDK, JRE and JVM is important in Java.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment
in which java byte code 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 is 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.
1) Classloader:
Classloader is a subsystem of JVM that is used to load class files.
2) Class(Method) Area:
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the
code for methods.
3) Heap:
It is the runtime data area in which objects are allocated.
4) Stack:
Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
5) Program Counter Register:
PC (program counter) register. It contains the address of the Java virtual machine instruction currently being
executed.
6) Native Method Stack:
It contains all the native methods used in the application.
7) Execution Engine:
It contains:
1) A virtual processor
2) Interpreter: Read byte code stream then execute the instructions.
3) 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.
Naming Conversion of Java
Sun micro system was given following conversions by declaring class, variable, method
etc. So that it is highly recommended to follow this conversion while writing real time
code.
Why Using naming Conversion
Different Java programmers can have different styles and approaches to write program.
By using standard Java naming conventions they make their code easier to read for
themselves and for other programmers. Readability of Java code is important because it
means less time is spent trying to figure out what the code does, and leaving more time
to fix or modify it.
1. Every package name should exist a lower case latter.
Example
package student; // creating package
Java follows camelcase syntax for naming the class, interface, method and variable.
According to CamelCase if name is combined with two words, second word will start with
uppercase letter always. General Example studentName, customerAccount. In term of
java programming e.g. actionPerformed(), firstName, ActionEvent, ActionListener etc.
Object is the physical as well as logical entity where as class is the only logical entity.
Class: Class is a blue print which is containing only list of variables and method and no
memory is allocated for them. A class is a group of objects that has common properties.
A class in java contains:
Data Member
Method
Constructor
Block
Class and Interface
Object: Object is a instance of class, object has state and behaviors.
An Object in java has three characteristics:
State
Behavior
Identity
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.
Class is also can be used to achieve user defined data types.
Real life example of object and class
In real world many examples of object and class like dog, cat, and cow are belong to
animal's class. Each object has state and behaviors. For example a dog has state:- color,
name, height, age as well as behaviors:- barking, eating, and sleeping.
Vehicle class
Car, bike, truck these all are belongs to vehicle class. These Objects have also different
different states and behaviors. For Example car has state - color, name, model, speed,
Mileage. as we;; as behaviors - distance travel
Access modifiers are those which are applied before data members or methods of a
class. These are used to where to access and where not to access the data members or
methods. In java programming these are classified into four types:
Private
Default (not a keyword)
Protected
Public
Note: Default is not a keyword (like public, private, protected are keywords)
If we are not using private protected and public keywords then JVM is by default taking
as default access modifiers.
Access modifiers are always used for how to reuse the features within the package and
access the package between class to class, interface to interface and interface to class.
Access modifiers provide features accessing and controlling mechanism among the
classes and interfaces.
Note: A protected member of class is accessible within the same class and other class of
same package and also accessible in inherited class of other package.
Rules for access modifiers:
The following diagram gives rules for Access modifiers.
Private: private members of class in not accessible anywhere in program these are only
accessible within the class. Private are also called class level access modifiers.
Example
class Hello
{
private int a=20;
private void show()
{
System.out.println("Hello java");
}
}
class B extends A
{
public static void main(String args[]){
B obj = new B();
obj.show();
}
}
Output
Hello Java
default: default members of class is accessible only within same class and other class of
same package. default are also called package level access modifiers.
Example
//save by A.java
package pack;
class A
{
void show()
{
System.out.println("Hello Java");
}
}
//save by B.java
package pack2;
import pack1.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error, can't access outside the package
obj.show(); //Compile Time Error, can't access outside the package
}
}
Output
Hello Java
Note: private access modifiers is also known as native access modifiers, default access
modifiers is also known as package access modifiers, protected access modifiers is also
known as inherited access modifiers, public access modifiers is also known as universal
access modifiers.
Encapsulation in Java
Benefits of encapsulation
Provides abstraction between an object and its clients.
Protects an object from unwanted access by clients.
Example: A bank application forbids (restrict) a client to change an Account's balance.
Let's see the Example of Encapsulation in java
Example
class Employee
{
private String name;
class Demo
{
public static void main(String[] args)
{
Employee e=new Employee();
e.setName("Harry");
System.out.println(e.getName());
}
}
Output
Harry
Constructor in Java
Example
class Sum
{
int a,b;
Sum()
{
a=10;
b=20;
}
public static void main(String s[])
{
Sum s=new Sum();
c=a+b;
System.out.println("Sum: "+c);
}
}
Output
Sum: 30
In above example when we create an object of "Sum" class then constructor of this class
call and initialize user defined value in a=10 and b=20. If we cannot create constructor
of Sum class then it print " Sum: 0 " because default values of integer is zero.
Rules or properties of a constructor
Constructor will be called automatically when the object is created.
Constructor name must be similar to name of the class.
Constructor should not return any value even void also. If we write the return type for the
constructor then that constructor will be treated as ordinary method.
Constructor definitions should not be static. Because constructors will be called each and
every time, whenever an object is created.
Constructor should not be private provided an object of one class is created in another
class (Constructor can be private provided an object of one class created in the same
class).
Constructors will not be inherited from one class to another class (Because every class
constructor is created for initializing its own data members).
The access specifier of the constructor may or may not be private.
1. If the access specifier of the constructor is private then an object of corresponding class
can be created in the context of the same class but not in the context of some other
classes.
2. If the access specifier of the constructor is not private then an object of corresponding
class can be created both in the same class context and in other class context.
Difference between Method and Constructor
Method Constructor
1 Method can be any user defined name Constructor must be class name
2 Method should have return type It should not have any return type (even void)
Method should be called explicitly either It will be called automatically whenever object is
3
with object reference or class reference created
Method is not provided by compiler in any The java compiler provides a default constructor
4
case. if we do not have any constructor.
Types of constructors
Based on creating objects in Java constructor are classified in two types. They are
Default or no argument Constructor
Parameterized constructor.
Default Constructor
A constructor is said to be default constructor if and only if it never take any
parameters.
If any class does not contain at least one user defined constructor than the system will
create a default constructor at the time of compilation it is known as system defined
default constructor.
Syntax
class className
{
..... // Call default constructor
clsname ()
{
Block of statements; // Initialization
}
.....
}
Note: System defined default constructor is created by java compiler and does not have
any statement in the body part. This constructor will be executed every time whenever
an object is created if that class does not contain any user defined constructor.
Example of default constructor.
In below example, we are creating the no argument constructor in the Test class. It will
be invoked at the time of object creation.
Example
//TestDemo.java
class Test
{
int a, b;
Test ()
{
System.out.println("I am from default Constructor...");
a=10;
b=20;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}
}
class TestDemo
{
public static void main(String [] args)
{
Test t1=new Test ();
}
}
Output
I am from default Constructor...
Value of a: 10
Value of b: 20
Rule-1:
Whenever we create an object only with default constructor, defining the default
constructor is optional. If we are not defining default constructor of a class, then JVM
will call automatically system defined default constructor. If we define, JVM will call user
defined default constructor.
Purpose of default constructor?
Default constructor provides the default values to the object like 0, 0.0, null etc.
depending on their type (for integer 0, for string null).
Example of default constructor that displays the default values
class Student
{
int roll;
float marks;
String name;
void show()
{
System.out.println("Roll: "+roll);
System.out.println("Marks: "+marks);
System.out.println("Name: "+name);
}
}
class TestDemo
{
public static void main(String [] args)
{
Student s1=new Student();
s1.show();
}
}
Output
Roll: 0
Marks: 0.0
Name: null
Explanation: In the above class, we are not creating any constructor so compiler
provides a default constructor. Here 0, 0.0 and null values are provided by default
constructor.
Parameterized constructor
If any constructor contain list of variable in its signature is known as paremetrized
constructor. A parameterized constructor is one which takes some parameters.
Syntax
class ClassName
{
.......
ClassName(list of parameters) //parameterized constructor
{
.......
}
.......
}
Syntax to call parameterized constructor
ClassName objref=new ClassName(value1, value2,.....);
OR
new ClassName(value1, value2,.....);
Example of Parameterized Constructor
class Test
{
int a, b;
Test(int n1, int n2)
{
System.out.println("I am from Parameterized Constructor...");
a=n1;
b=n2;
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
}
class TestDemo1
{
public static void main(String k [])
{
Test t1=new Test(10, 20);
}
}
Important points Related to Parameterized Constructor
Whenever we create an object using parameterized constructor, it must define
parameterized constructor otherwise we will get compile time error. Whenever we define
the objects with respect to both parameterized constructor and default constructor, it
must define both the constructors.
In any class maximum one default constructor but 'n' number of parameterized
constructors.
Example of default constructor, parameterized constructor and overloaded constructor
Example
class Test
{
int a, b;
Test ()
{
System.out.println("I am from default Constructor...");
a=1;
b=2;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
Test (int x, int y)
{
System.out.println("I am from double Paraceterized Constructor");
a=x;
b=y;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
Test (int x)
{
System.out.println("I am from single Parameterized Constructor");
a=x;
b=x;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
Test (Test T)
{
System.out.println("I am from Object Parameterized Constructor...");
a=T.a;
b=T.b;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
}
class TestDemo2
{
public static void main (String k [])
{
Test t1=new Test ();
Test t2=new Test (10, 20);
Test t3=new Test (1000);
Test t4=new Test (t1);
}
}
Note By default the parameter passing mechanism is call by reference.
Constructor Overloading
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 the number of parameters, and their type.
In other words whenever same constructor is existing multiple times in the same
class with different number of parameters or order of parameters or type of parameters
is known as Constructor overloading.
Syntax
class ClassName
{
ClassName()
{
..........
..........
}
ClassName(datatype1 value1)
{.......}
ClassName(datatype1 value1, datatype2 value2)
{.......}
ClassName(datatype2 variable2)
{.......}
ClassName(datatype2 value2, datatype1 value1)
{.......}
........
}
Why overriding is not possible at constructor level.
The scope of constructor is within the class so that it is not possible to achieved
overriding at constructor level.
main() method is starting execution block of a java program or any java program start
their execution from main method. If any class contain main() method known as main
class.
Syntax of main() method:
Syntax
public static void main(String args[])
{
.......
.......
}
Public
public is a keyword in a java language whenever if it is preceded by main() method the
scope is available anywhere in the java environment that means main() method can be
executed from anywhere. main() method must be accessed by every java programmer
and hence whose access specifier must be public.
Static
static is a keyword in java if it is preceded by any class properties for that memory is
allocated only once in the program. Static method are executed only once in the
program. main() method of java executes only once throughout the java program
execution and hence it declare must be static.
Void
void is a special datatype also known as no return type, whenever it is preceded by
main() method that will be never return any value to the operating system. main()
method of java is not returning any value and hence its return type must be void.
String args[]
String args[] is a String array used to hold command line arguments in the form of
String values.
In case of main() method following changes are acceptable
1. We can declare String[] in any valid form.
String[] args
String args[]
String []args
2. Instance of String[] we can take var-arg String parameter is String...
Syntax
main(String[] args) --> main(String... args)
3. We can change the order of modifiers i.e Instead of
Syntax
public static we can take static public
4. Instead of args we can take any valid java identifier.
Syntax
public static void main(String a[])
We can overload main() method ?
Yes, We can overload main() method. A Java class can have any number of main()
methods. But run the java program, which class should have main() method with
signature as "public static void main(String[] args). If you do any modification to this
signature, compilation will be successful. But, not run the java program. we will get the
run time error as main method not found.
Example of override main () method
Example
public class mainclass
{
public static void main(String[] args)
{
System.out.println("Execution starts from Main()");
}
void main(int args)
{
System.out.println("Override main()");
}
double main(int i, double d)
{
System.out.println("Override main()");
return d;
}
}
Output
Execution starts from Main()
Whenever same method name is exiting multiple times in the same class with different
number of parameter or different order of parameters or different types of parameters is
known as method overloading.
Why use method Overloading in Java?
Suppose we have to perform addition of given number but there can be any number of
arguments, if we write method such as a(int, int)for two arguments, b(int, int, int) for
three arguments then it is very difficult for you and other programmer to understand
purpose or behaviors of method they can not identify purpose of method. So we use
method overloading to easily figure out the program. For example above two methods we
can write sum(int, int) and sum(int, int, int) using method overloading concept.
Syntax
class class_Name
{
Returntype method()
{.........}
Returntype method(datatype1 variable1)
{.........}
Returntype method(datatype1 variable1, datatype2 variable2)
{.........}
Returntype method(datatype2 variable2)
{.........}
Returntype method(datatype2 variable2, datatype1 variable1)
{.........}
}
Different ways to overload the method
There are two ways to overload the method in java
By changing number of arguments or parameters
By changing the data type
By changing number 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.
Example Method Overloading in Java
class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10, 20, 30);
}
}
Output
30
60
By changing the data type
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
float arguments.
Example Method Overloading in Java
class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(float a, float b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10.05, 15.20);
}
}
Output
30
25.25
Why Method Overloading 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:
Example of Method Overloading
class Addition
{
int sum(int a, int b)
{
System.out.println(a+b);
}
double sum(int a, int b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Addition obj=new Addition();
int result=obj.sum(20,20); //Compile Time Error
}
}
Explanation of Code
Example
int result=obj.sum(20,20);
Here how can java determine which sum() method should be called
Note: The scope of overloading is within the class.
Any object reference of class can call any of overloaded method.
Can we overload main() method ?
Yes, We can overload main () method. A Java class can have any number of main ()
methods. But run the java program, which class should have main () method with
signature as "public static void main(String[] args). If you do any modification to this
signature, compilation will be successful. But, not run the java program. we will get the
run time error as main method not found.
Example of override main() method
Example
public class mainclass
{
public static void main(String[] args)
{
System.out.println("Execution starts from Main()");
}
void main(int args)
{
System.out.println("Override main()");
}
double main(int i, double d)
{
System.out.println("Override main()");
return d;
}
}
Output
Execution starts from Main()
finalize () method
The finalize () method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object class as:
1. protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So
if you have created any object without new, you can use finalize method to perform cleanup
processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
1. public static void gc(){}
Note: Garbage collection is performed by a daemon thread called Garbage Collector (GC). This
thread calls the finalize () method before object is garbage collected.
this is a reference variable that refers to the current object. It is a keyword in java
language represents current class object
Usage of this keyword
It can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
It can be used to invoke current class method (implicitly)
It can be passed as an argument in the method call.
It can be passed as argument in the constructor call.
It can also be used to return the current class instance.
Why use this keyword in java ?
The main purpose of using this keyword is to differentiate the formal parameter and
data members of class, whenever the formal parameter and data members of the class
are similar then jvm get ambiguity (no clarity between formal parameter and member of
the class)
To differentiate between formal parameter and data member of the class, the data
member of the class must be preceded by "this".
"this" keyword can be use in two ways.
this . (this dot)
this() (this off)
this . (this dot)
which can be used to differentiate variable of class and formal parameters of method or
constructor.
"this" keyword are used for two purpose, they are
It always points to current class object.
Whenever the formal parameter and data member of the class are similar and JVM gets
an ambiguity (no clarity between formal parameter and data members of the class).
To differentiate between formal parameter and data member of the class, the data
members of the class must be preceded by "this".
Syntax
this.data member of current class.
Note: If any variable is preceded by "this" JVM treated that variable as class variable.
Example without using this keyword
class Employee
{
int id;
String name;
Employee(int i,String n)
{
id = i;
name = n;
}
void show()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Employee e1 = new Employee(111,"Harry");
Employee e2 = new Employee(112,"Jacy");
e1.show();
e2.show();
}
}
Output
111 Harry
112 Jacy
In the above example, no need of use this keyword because parameter (formal
arguments) and instance variables are different. This keyword is only use when
parameter (formal arguments) and instance variables are same.
this ()
which can be used to call one constructor within the another constructor without
creation of objects multiple time for the same class.
Syntax
this(); // call no parametrized or default constructor
this(value1,value2,.....) //call parametrize constructor
this keyword used to invoke current class method (implicitly)
By using this keyword you can invoke the method of the current class. If you do not use
the this keyword, compiler automatically adds this keyword at time of invoking of the
method.
Example of this keyword
class Student
{
void show()
{
System.out.println("You got A+");
}
void marks()
{
this.show(); //no need to use this here because compiler does it.
}
void display()
{
show(); //compiler act marks() as this.marks()
}
public static void main(String args[])
{
Student s = new Student();
s.display();
}
}
Syntax
You got A+
Rules to use this()
this() always should be the first statement of the constructor. One constructor can call
only other single constructor at a time by using this().
.
Type Conversion in Java with Examples
1.7
When you assign value of one data type to another, the two types might not be compatible with each other.
If the data types are compatible, then Java will perform the conversion automatically known as Automatic
Type Conversion and if not then they need to be casted or converted explicitly. For example, assigning an
int value to a long variable.
Widening or Automatic Type Conversion
Widening conversion takes place when two data types are automatically converted. This happens when:
The two data types are compatible.
When we assign value of a smaller data type to a bigger data type.
For Example, in java the numeric data types are compatible with each other but no automatic conversion is
supported from numeric type to char or boolean. Also, char and boolean are not compatible with each
other
Example:
class Test
{
public static void main(String[] args)
{
int i = 100;
Output:
Error:
Example:
//Java program to illustrate explicit type conversion
class Test
{
public static void main(String[] args)
{
double d = 100.04;
Output:
Double value 100.04
Long value 100
Int value 100
While assigning value to byte type the fractional part is lost and is reduced to modulo 256(range of byte).
Example:
//Java program to illustrate Conversion of int and double to byte
class Test
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
System.out.println("Conversion of int to byte.");
//i%256
b = (byte) i;
System.out.println("i = b " + i + " b = " + b);
System.out.println("\nConversion of double to byte.");
//d%256
b = (byte) d;
System.out.println("d = " + d + " b= " + b);
}
}
Output:
// The Expression
double result = (f * b) + (i / c) - (d * s);
Output:
Result = 626.7784146484375
Output
100
NOTE- In case of single operands the result gets converted to int and then it is type casted accordingly.
Example:
//Java program to illustrate type casting int to byte
class Test
{
public static void main(String args[])
{
byte b = 50;
100