Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Java Notes Final

Degree notes

Uploaded by

Gopi Krishna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Java Notes Final

Degree notes

Uploaded by

Gopi Krishna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

1.

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

 Java is used in internet programming, mobile devices, games, e-business


solutions etc.
 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
 In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
 Java is an island of Indonesia where first coffee was produced (called java coffee).
 Originally developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
 In 1995, Time magazine called Java one of the Ten Best Products of 1995.
 DK 1.0 releasedJ in(January 23, 1996).

3.Types of Java Applications


There are mainly 4 types 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.

4. Java OOPs Concepts


 Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies the software development and maintenance by providing
some of the following concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

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

 Collection of objects is called class. It is a logical entity.

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

 Hiding internal details and showing functionality is known as abstraction. For


example: phone call, we don't know the internal processing.
 In java, we use abstract class and interface to achieve abstraction.

Encapsulation
 Binding (or wrapping) code and data together into a single unit 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.

method should start with lowercase letter and be a verb e.g.


name actionPerformed(), main(), print(), println() 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

constants should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY 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

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.

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

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

Simple Program of Java

class Simpledemo
{
public static void main(String args[])
{
System.out.println("Hello MVS");
}
}

 save this file as Simpledemo.java


 To compile: javac Simpledemo.java
 To execute: java Simpledemo
Output:Hello MVS

Key points of 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.
 Classloader: is the subsystem of JVM that is used to load class files.
 Bytecode Verifier: checks the code fragments for illegal code that can violate
access right to objects.

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

JVM provides definitions for the

 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

JRE (Java Runtime Environment)


 Java Runtime Environment. It is used to provide runtime environment.
 It is the implementation of JVM.
 It physically exists.
 It contains set of libraries and other files that JVM uses at runtime.

JDK( Development Kit)


 JDK is an acronym for Java Development Kit.
 It physically exists.
 It contains JRE and development tools.

6.Variable and Data type in Java


Variable

 The value change during the programmme execution is called variable.


 Variable is name of reserved area allocated in memory.

Example: int data=50; //Here data is variable

Types of Variable
There are three types of variables in java

 local variable
 instance variable
 static 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

class A
{
int data=50; //instance variable
static int m=100; //static variable
void method()
{
int n=90; //local variable
}
} //end of class

Data Types in Java


In java, there are two types of data types

 primitive data types


 non-primitive data types

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 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

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 = += -= *= /= %= &= ^= |= <<= >>= >>>=

8.Class and object 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:

class <class_name>
{
data member;
method;
}
Example Program

class Student1
{
int id;
//data member (also instance variable)
String name; //data member(also instance variable)

public static void main(String args[])


{
Student1 s1=new Student1(); //creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}

Example program

class Rectangle
{
int length;
int width;

void insert(int l,int w)


{
length=l;
width=w;
}

void calculateArea(){System.out.println(length*width);}

public static void main(String args[])


{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();

r1.insert(11,5);
r2.insert(3,15);

r1.calculateArea();
r2.calculateArea();
}
}

Difference between object and class

There are many differences between object and class.

No. Object Class

1) Object is an instance of a class. Class is a blueprint or template from


which objects are created.

2) Object is a real world entity such as Class is a group of similar objects.


pen, laptop, mobile, bed, keyboard,
mouse, chair etc.

3) Object is a physical entity. Class is a logical entity.

4) Object is created through new keyword Class is declared using class keyword
mainly e.g. e.g.
Student s1=new Student(); class Student{}

5) Object is created many times as per Class is declared once.


requirement.

6) Object allocates memory when it is Class doesn't allocated memory when


created. it is created.

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.

9.Method Overloading in Java


 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.
 Method overloading increases the readability of the program.
 There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

1. Example of Method Overloading by changing the no. of arguments

 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);
}
}

2.Example of Method Overloading by changing data type of argument

 we have created two overloaded methods that differs in data type. The first sum
method receives two integer arguments and second sum method receives two
double arguments.

class Calculation2
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}

public static void main(String args[])


{
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}

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.

 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

1.default constructor

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


 Default constructor provides the default values to the object like 0, null etc.
depending on the type.
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Example of default constructor that displays the default values

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

Example of parameterized constructor


class Student4
{
int id;
String name;

Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[])


{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
11. 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


class Student5
{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}

public static void main(String args[])


{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

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);
}

public static void main(String args[])


{
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}

Difference between constructor and method in java

Java Constructor Java Method

Constructor is used to initialize the state of an Method is used to expose


object. 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 Method is not provided by


you don't have any constructor. compiler in any case.

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 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 variable

If you declare any variable as static, it is known static variable.

 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).

Program of counter by static variable

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

Program of counter without static variable


class Counter
{
int count=0;//will get memory when instance is created
Counter()
{
count++;
System.out.println(count);
}

public static void main(String args[])


{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();

}
}

Output:1
1
1
Java static method

 If we use 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.

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.

Example of static method


class Student9
{
int rollno;
String name;
static String college = "NTR";
static void change()
{
college = "MVS";
}
Student9(int r, String n)
{
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}

13.this keyword in java


 Many usage of java this keyword

 this is a reference variable that refers to the current object.


 this keyword can be used to refer current class instance variable.
 this() can be used to invoke current class constructor.
 this keyword can be used to invoke current class method (implicitly)
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this keyword can also be used to return the current class instance.
 Call to this() must be the first statement in constructor.

Example program with this keyword

class Student11{
int id;
String name;

Student11(int id,String name){


this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}
Output111 Karan
222 Aryan

Example program without this keyword

class Student10{
int id;
String name;

Student10(int id,String name){


id = id;
name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();
}
}

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.

Inheritance represents the IS-A relationship, also known as parent-child


relationship.

For Method Overriding (so runtime polymorphism can be achieved).

For Code Reusability.

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.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name


{

//methods and fields

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

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

4. static method cannot be overridden. It can be proved by runtime polymorphism,

Example of method overriding


class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike2 extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
obj.run();
}

Output: Bike is running safely


class Bank{
int getRateOfInterest(){return 0;}
}

class SBI extends Bank{


int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}

class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

Output:

SBI Rate of Interest: 8

ICICI Rate of Interest: 7

AXIS Rate of Interest: 9


16.Java super keyword
 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.
 super is used to refer immediate parent class instance variable.
 super() is used to invoke immediate parent class constructor.
 super is used to invoke immediate parent class method.

//example of super keyword

class Vehicle
{
int speed=50;
}

class Bike4 extends Vehicle


{
int speed=100;

void display()
{
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[])
{
Bike4 b=new Bike4();
b.display();

}
}

Output:50
2.super is used to invoke parent class constructor.

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

4.super can be used to invoke parent class method

class Person
{
void message()
{
System.out.println("welcome");
}
}

class Student16 extends Person


{
void message()
{
System.out.println("welcome to java");
}

void display()
{
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}

public static void main(String args[])


{
Student16 s=new Student16();
s.display();
}
}

Output:welcome to java
welcome
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

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

1. Java final variable

class Bike9
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output:Compile Time Error


2.Java final method

class Bike
{
final void run(){System.out.println("running");}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda honda= new Honda();
honda.run();
}
} Output:Compile Time Error

3.Java final class


final class Bike
{
}
class Honda1 extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda1 honda= new Honda();
honda.run();
}
}

Output:Compile Time Error


18. 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:


1. compile time polymorphism and
2. runtime polymorphism.
 We can perform polymorphism in java by method overloading and method
overriding.

Runtime Polymorphism in Java

 Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to


an overridden method is resolved at runtime rather than compile-time.
 In this process, an overridden method is called through the reference variable of a
superclass.
 The determination of the method to be called is based on the object being
referred to by the reference variable.

Example of Java Runtime Polymorphism

 Since method invocation is determined by the JVM not compiler, it is known as


runtime polymorphism.

class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splender();//upcasting
b.run();
}
}

Output:running safely with 60km.


abstract class and method in Java
 A class that is declared with abstract keyword, is known as abstract class in java.
 It can have abstract and non-abstract methods (method with body).
 Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
 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.
There are two ways to achieve abstraction in java
1. Abstract class
2. Interface

Example abstract class

abstract class A{}

abstract method
 A method that is declared as abstract and does not have implementation is known
as abstract method.

Example abstract method

abstract void printStatus(); //no body and abstract

Example of abstract class that has abstract method


abstract class Bike{
abstract void run();
}
class Honda4 extends Bike
{
void run(){System.out.println("running safely..");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

running safely..
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");}
}

class Circle1 extends Shape{


void draw(){System.out.println("drawing circle");}
}

//In real scenario, method is called by programmer or user


class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In real scenario, object is provided through method e.g. getSha
pe() method
s.draw();
}
}

drawing circle
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.

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.

Understanding relationship between classes and interfaces

 a class extends another class


 an interface extends another interface but a class implements an interface.

Simple example of Java interface

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}

Output:Hello
Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.


known as multiple inheritance.

interface Printable{
void print();
}

interface Showable{
void show();
}

class A7 implements Printable,Showable{

public void print(){System.out.println("Hello");}


public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}

Output:Hello
Welcome
Interface inheritance

A class implements interface but one interface extends another interface

interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{

public void print(){System.out.println("Hello");}


public void show(){System.out.println("Welcome");}

public static void main(String args[]){


Testinterface2 obj = new Testinterface2();
obj.print();
obj.show();
}
}

Hello
Welcome

Difference between abstract class and interface

Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract
non-abstract methods. methods.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

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.

5) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

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

 A java package is a group of similar types of classes, interfaces and sub-


packages.
 Package in java can be categorized in two form
 The package keyword is used to create a package in java.

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) Java package provides access protection.

3) Java package removes naming collision.

2.User-defined packages

Example of java package

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Compile java package

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

Run java package program

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

Example of package that import the packagename.*

//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Output:Hello

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

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
}
}

2. default access modifier


 If you don't use any modifier, it is treated as default bydefault. The default
modifier is accessible only within package.

Example of default access modifier


 In this example, we have created two packages pack and mypack. We are
accessing the A class from outside its package, since A class is not public, so it
cannot be accessed from outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

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

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}

Output:Hello

4.public access modifier


 The public access modifier is accessible everywhere.
 It has the widest scope among all other modifiers.

Example of public access modifier


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Output:Hello
Understanding all java access modifiers

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

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.

class CommandLine
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}

compile by > javac CommandLineExample.java


run by > java CommandLineExample sonoo Output: Your first argument is: sonoo
Java Array
 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.
 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.
 Size Limit: We can store only fixed size of elements in the array. It doesn't grow
its size at runtime.

Array in java is index based, first element of the array is stored at 0 index.

Types of Array in java

There are two types of array.

 One Dimensional Array


 Two Dimensional Array
 Multidimensional Array

One Dimensional Array in java


Syantax:

1. dataType arr[];

Example of single dimensional java array


class Testarray
{
public static void main(String args[])
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)
{ //length is the property of array
System.out.println(a[i]);
}
}
}

Two Dimensional Array

Syntax: dataType arrayRefVar[][];

Example:
int[][] arr=new int[3][3]; //3 row and 3 column

Example of Multidimensional java array


class Testarray3
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
}
25.Wrapper class in Java

 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

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Example: Primitive to Wrapper

public class WrapperExample1{


public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}}

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

System.out.println(a+" "+i+" "+j);


}}

Output:

333

26.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.
 You can pass number of arguments from the command prompt

Example of command-line argument in java

class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}

compile by > javac CommandLineExample.java


run by > java CommandLineExample sonoo

Output: Your first argument is: sonoo

Example of command-line argument


class A
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
}

compile by > javac A.java


run by > java A sonoo jaiswal 1 3 abc

Output: sonoo
jaiswal
1
3
abc

Difference between method overloading and method overriding in java

No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to


readability of the program. provide the specific
implementation of the method
that is already provided by its
super class.

2) Method overloading is performed within Method overriding occurs in two


classes that have IS-A
class. (inheritance) relationship.

3) In case of method overloading, parameter In case of method overriding,


must be different. parameter must be same.

4) Method overloading is the example of Method overriding is the


compile time polymorphism. example of run time
polymorphism.

5) In java, method overloading can't be Return type must be same or


performed by changing return type of the covariant in method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.

27.Java String

 String is a sequence of characters. But in java, string is an object that represents


a sequence of characters. String class is used to create string object.
 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.

Example 1:

char[] ch={'m','v','s','c','o','l','l','e','g','e'};

String s=new String(ch);

Example 2:

1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance

String s=new String("Welcome");//creates two objects and one reference variable


Example
public class StringExample
{
public static void main(String args[])
{
String s1="java";//creating string by java string literal

char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword

System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}

java
strings
example

Java String class methods


The java.lang.String class provides many useful methods to perform operations on
sequence of char values.

No. Method Description

1 char charAt(int index) returns char value for the particular index

2 int length() returns string length

3 static String format(String format, Object... returns formatted string


args)

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

7 boolean contains(CharSequence s) returns true or false after matching the


sequence of char value

8 static String join(CharSequence delimiter, returns a joined string


CharSequence... elements)

9 static String join(CharSequence delimiter, returns a joined string


Iterable<? extends CharSequence>
elements)

10 boolean equals(Object another) checks the equality of string with object

11 boolean isEmpty() checks if string is empty

12 String concat(String str) concatinates specified string

13 String replace(char old, char new) replaces all occurrences of specified char
value

14 String replace(CharSequence old, replaces all occurrences of specified


CharSequence new) CharSequence

15 String trim() returns trimmed string omitting leading and


trailing spaces

16 String split(String regex) returns splitted string matching regex

17 String split(String regex, int limit) returns splitted string matching regex and
limit

18 String intern() returns interned string


19 int indexOf(int ch) returns specified char value index

20 int indexOf(int ch, int fromIndex) returns specified char value index starting
with given index

21 int indexOf(String substring) returns specified substring index

22 int indexOf(String substring, int fromIndex) returns specified substring index starting
with given index

23 String toLowerCase() returns string in lowercase.

24 String toLowerCase(Locale l) returns string in lowercase using specified


locale.

25 String toUpperCase() returns string in uppercase.

26 String toUpperCase(Locale l) returns string in uppercase using specified


locale.

28.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.
 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.

Exception classes Hierarchy in Java


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

//code that may throw exception

}catch(Exception_class_Name ref)
{
}

Syntax of try-finally block

try
{

//code that may throw exception

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

Example by exception handling

public class Testtrycatch2


{
public static void main(String args[])
{
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}

Output:

rest of the code...

Multi catch block


public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}

System.out.println("rest of the code...");


}
}

Output:task1 completed
rest of the code...

finally block

 Java finally block is always executed whether exception is handled or not.


 Java finally block must be followed by try or catch block.
 Finally block in java can be used to put "cleanup" code such as closing a file,
closing connection etc.

Exception doesn't occur.

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

Exception occurs and not handled.


class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}

Output:finally block is always executed


Exception in thread main java.lang.ArithmeticException:/ by zero

Exception occurs and handled.

public class TestFinallyBlock2{


public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}

Output:Exception in thread main java.lang.ArithmeticException:/ by zero


finally block is always executed
rest of the code...

Java throw keyword

 The Java throw keyword is used to explicitly throw an exception.


 We can throw either checked or uncheked exception in java by throw keyword.
 The throw keyword is mainly used to throw custom exception.

The syntax of java throw keyword is given below.


throw exception;

throw new IOException("sorry device error);

Example

public class TestThrow1{


static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}

Java throws keyword

 The Java throws keyword is used to declare an exception.


 It gives an information to the programmer that there may occur an exception so it
is better for the programmer to provide the exception handling code so that
normal flow can be maintained.
 Exception Handling is mainly used to handle the checked exceptions.
 If there occurs any unchecked exception such as NullPointerException, it is
programmers fault that he is not performing check up before the code being used.
 unchecked Exception: under your control so correct your code.
 error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Syntax

return_type method_name() throws exception_class_name


{
//method code
}

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

Difference between throw and throws in Java

No. throw throws

1) Java throw keyword is used to Java throws keyword is used to declare


explicitly throw an exception. an exception.

2) Checked exception cannot be Checked exception can be propagated


propagated using throw only. with throws.

3) Throw is followed by an instance. Throws is followed by class.

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.

Difference between final, finally and finalize

No. final finally finalize

1) Final is used to apply Finally is used to Finalize is used to


restrictions on class, method place important perform clean up
and variable. Final class can't code, it will be processing just
be inherited, final method can't executed whether before object is
be overridden and final variable exception is handled garbage collected.
value can't be changed. or not.

2) Final is a keyword. Finally is a block. Finalize is a method.

You might also like