Java Notes Final
Java Notes Final
What is Java
Java is a programming language and a platform.
Java is a high level, robust, secured and object-oriented programming language.
Any hardware or software environment in which a program runs, Since Java has
its own runtime environment (JRE) and API, it is called platform independent.
3 billion devices run java.
There are many devices where java is currently used of the following:
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.
2.History of Java
Java history is interesting to know. The history of java starts from Green Team.
Java team members (also known as Green Team), initiated a revolutionary task to
develop a language for digital devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by
Netscape.
James Gosling
1) Standalone Application
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
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME
are used for creating mobile applications.
Object
Any entity that has state and behavior is known as an object. For example: chair,
pen, table, keyboard, bike etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For
example: to convense the customer differently, to draw something e.g. shape or
rectangle etc.
In java, we use method overloading and method overriding to achieve
polymorphism.
Abstraction
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.
Name Convention
class name should start with uppercase letter and be a noun e.g. String, Color,
Button, System, Thread etc.
interface should start with uppercase letter and be an adjective e.g. Runnable,
name Remote, ActionListener etc.
variable should start with lowercase letter e.g. firstName, orderNumber etc.
name
package should be in lowercase letter e.g. java, lang, sql, util etc.
name
5.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
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.
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++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any
machine on the internet.
Multi-threaded
class Simpledemo
{
public static void main(String args[])
{
System.out.println("Hello MVS");
}
}
Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
Loads code
Verifies code
Executes code
Provides runtime environment
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
Types of Variable
There are three types of variables in java
local variable
instance variable
static variable
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
class A
{
int data=50; //instance variable
static int m=100; //static variable
void method()
{
int n=90; //local variable
}
} //end of class
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Note: because java uses unicode system rather than ASCII code system. \u0000 is the
lowest range of unicode system.To get detail about Unicode see below.
7.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
multiplicative */%
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
ternary ?:
data member
method
constructor
block
class and interface
class <class_name>
{
data member;
method;
}
Example Program
class Student1
{
int id;
//data member (also instance variable)
String name; //data member(also instance variable)
Example program
class Rectangle
{
int length;
int width;
void calculateArea(){System.out.println(length*width);}
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
4) Object is created through new keyword Class is declared using class keyword
mainly e.g. e.g.
Student s1=new Student(); class Student{}
7) There are many ways to create object There is only one way to define class
in java such as new keyword, in java using class keyword.
newInstance() method, clone() method,
factory method and deserialization.
If we have to perform only one operation, having same name of the methods
increases the readability of the program.
Method overloading increases the readability of the program.
There are two ways to overload the method in java
we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.
class Calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
we have created two overloaded methods that differs in data type. The first sum
method receives two integer arguments and second sum method receives two
double arguments.
class Calculation2
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}
10.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.
1.default constructor
class Student3
{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
2. Parameterized constructor
A constructor that have parameters is known as parameterized constructor
Parameterized constructor is used to provide different values to the distinct objects
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
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
we are going to copy the values of one object into another using java constructor
class Student6
{
int id;
String name;
Student6(int i,String n)
{
id = i;
name = n;
}
Student6(Student6 s)
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}
Constructor must not have return type. Method must have return type.
Constructor name must be same as the class Method name may or may not be
name. same as class name.
12. Java static keyword
The static variable can be used to refer the common property of all objects (that
is not unique for each object) e.g. company name of employees, college name of
students etc.
The static variable gets memory only once in class area at the time of class
loading.
It makes your program memory efficient (i.e it saves memory).
class Counter
{
static int count=0;//will get memory only once and retain its value
Counter()
{
count++;
System.out.println(count);
}
public static void main(String args[])
{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:1
2
3
}
}
Output:1
1
1
Java 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.
3. 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.
class Student11{
int id;
String name;
class Student10{
int id;
String name;
Output:0 null
0 null
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.
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
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.
Multiple inheritance is not supported in java through class
Single Inheritance
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
15. 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.
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.
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
class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
class Vehicle
{
int speed=50;
}
void display()
{
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[])
{
Bike4 b=new Bike4();
b.display();
}
}
Output:50
2.super is used to invoke parent class constructor.
class Vehicle
{
Vehicle()
{
System.out.println("Vehicle is created");
}
}
class Bike5 extends Vehicle
{
Bike5()
{
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike5 b=new Bike5();
}
}
Output:Vehicle is created
Bike is created
class Person
{
void message()
{
System.out.println("welcome");
}
}
void display()
{
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
Output:welcome to java
welcome
Java Final Keyword
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
class Bike9
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
class Bike
{
final void run(){System.out.println("running");}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}
abstract method
A method that is declared as abstract and does not have implementation is known
as abstract method.
running safely..
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
drawing circle
Interface in Java
There are mainly three reasons to use interface. They are given below.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:Hello
Multiple inheritance in Java by interface
interface Printable{
void print();
}
interface Showable{
void show();
}
Output:Hello
Welcome
Interface inheritance
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{
Hello
Welcome
1) Abstract class can have abstract and Interface can have only abstract
non-abstract methods. methods.
3) Abstract class can have final, non-final, Interface has only static and final
static and non-static variables. variables.
4) Abstract class can have static methods, Interface can't have static methods,
main method and constructor. main method or constructor.
6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
22.Java Package
1. built-in package
2. user-defined package.
1.Built in package
There are many built-in packages such as java, lang, awt, javax, swing, net, io,
util, sql etc.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2.User-defined packages
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Compile java package
For example
1. javac -d . Simple.java
Output:Welcome to package
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
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.
1. private
2. default
3. protected
4. public
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it
cannot be accessed from outside the package.
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.
In this example, we have created the two packages pack and mypack.
The A class of pack package is public, so can be accessed from outside the
package.
But msg method of this package is declared as protected, so it can be accessed
from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Understanding all java access modifiers
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
The arguments passed from the console can be received in the java program and it can
be used as an input.
class CommandLine
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Array in java is index based, first element of the array is stored at 0 index.
1. dataType arr[];
Example:
int[][] arr=new int[3][3]; //3 row and 3 column
Wrapper class in java provides the mechanism to convert primitive into object and
object into primitive.
The automatic conversion of primitive into object is known and autoboxing and
vice-versa unboxing.
One of the eight classes of java.lang package are known as wrapper class in java.
The list of eight wrapper classes are given below
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Output:
20 20 20
Example: Wrapper to Primitive
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int
int j=a;//unboxing, now compiler will write a.intValue() internally
Output:
333
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
}
}
Output: sonoo
jaiswal
1
3
abc
27.Java String
Example 1:
char[] ch={'m','v','s','c','o','l','l','e','g','e'};
Example 2:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
java
strings
example
1 char charAt(int index) returns char value for the particular index
4 static String format(Locale l, String format, returns formatted string with given locale
Object... args)
5 String substring(int beginIndex) returns substring for given begin index
6 String substring(int beginIndex, int returns substring for given begin index and
endIndex) end index
13 String replace(char old, char new) replaces all occurrences of specified char
value
17 String split(String regex, int limit) returns splitted string matching regex and
limit
20 int indexOf(int ch, int fromIndex) returns specified char value index starting
with given index
22 int indexOf(String substring, int fromIndex) returns specified substring index starting
with given index
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.
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFound, IO, SQL, Remote etc.
Dictionary Meaning: Exception is an abnormal condition.
Exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
The 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.
1. try
2. catch
3. finally
4. throw
5. throws
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
}catch(Exception_class_Name ref)
{
}
try
{
}finally
{
catch block
Java catch block is used to handle the Exception. It must be used after the try
block only.
You can use multiple catch block with a single try.
Output:
Output:task1 completed
rest of the code...
finally block
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
Example
Syntax
Example
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
4) Throw is used within the method. Throws is used with the method
signature.
5) You cannot throw multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws
IOException,SQLException.