Java Unit 2
Java Unit 2
Java Unit 2
UNIT-I
** Java Introduction
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:
1) Standalone Application
Standalone applications are also known as desktop applications or window-based
applications. These are traditional software that we need to install on every machine. Examples
of standalone application are 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 a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, 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. is called an
enterprise application. It has advantages like high-level security, load balancing, and clustering.
In Java, EJB is used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently,
Android and Java ME are used for creating mobile applications.
Syntax-
class class_name
** Features of OOPS
Class:- A class can be defined as a template/blueprint that describes the behavior/state that
the object of its type support.
Object:- Objects have states and behaviors. (Collection of object is a class) Example: A dog
has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An
object is an instance of a class.
Inheritance:- Inheritance means creating new classes based on existing ones. A class that
inherits from another class can reuse the methods and fields of that class. In addition, you can
add new fields and methods to your current class as well.
** Features of Java
Simple Object-Oriented Portable Platform independent
Object Oriented:- Java is an Object Oriented Programming Language, which means in Java
everything is written in terms of classes and objects. Now, what is an Object? The object is
nothing but a real-world entity that can represent any person, place, or thing and can be
distinguished from others. Every object near us has some state and behavior associated with it.
Platform independent:- Unlike other programming languages such as C, C++ etc which are
compiled into platform specific machines. Java is guaranteed to be write-once, run-anywhere
language. On compilation Java program is compiled into bytecode. This bytecode is platform
independent and can be run on any machine, plus this bytecode format also provide security.
Any machine with Java Runtime Environment can run Java Programs.
Secure:- When it comes to security, Java is always the first choice. With java secure features it
enable us to develop virus free, temper free system. Java program always runs in Java runtime
environment with almost null interaction with system OS, hence it is more secure.
Multi Threading:- Java multithreading feature makes it possible to write program that can do
many tasks simultaneously. Benefit of multithreading is that it utilizes same memory and other
resources to execute multiple threads at the same time, like While typing, grammatical errors
are checked along.
Portable:- Java Byte code can be carried to any platform. No implementation dependent
features. Everything related to storage is predefined, example: size of primitive data typesHigh
Performance
Simple:-Java is easy to learn and its syntax is quite simple, clean and easy to understand.The
confusing and ambiguous concepts of C++ are either left out in Java or they have been re-
implemented in a cleaner way.
**Variable
Types of Variables
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists. A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static. It is called an instance variable because its value is
instance-specific and is not shared among instances.
Syntax:- class A {
Int a;{
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create
a single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.
Example :- class A{
A r=new A();
System.out.println(a);
System.out.println(A.b);
System.out.println(r.c);
**Data Type
Data types in Java are of different sizes and values that can be stored in the variable that is
made as per convenience and circumstances to cover up all test cases. Java has two
categories in which data types are segregated
1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.
class Hello{
**Abstract Class
An abstract class is a class. That is declared abstract keyword. We can’t create object for
abstract class.( but create a reference variable).
It may or may not include abstract methods. Abstract class can’t be instantiated, but they can be
sub classed. When an abstract class is sub classes. The sub class usually provides
implementations for all of the abstract method in its parent class.
Abstract class purpose:– main purpose of the abstract class is to create a base
from which many other classes. can be derived.
Advantages:- an abstract class provides the provider of data hiding in java.
Syntax:- abstract class A
{
-------
-------}
Program:-
class demo{
Note- If the class is normal not abstract, than no one will give error
**Abstract Method
A method which contain abstract modifier at the time of declaration is called abstract method.
Syntax:- class A{
Program:-
public abstract class fruit
{
public abstract void taste();
}
class mango extends fruit
{
public void taste()
{
System.out.println(" Mango is Sweet");
}
}
class orange extends fruit
{
public void taste()
{
System.out.println("Orange is sour");
}
}
class display
{
public static void main(String []args)
{
mango m=new mango();
orange o=new orange();
m.taste(); o.taste();
}
}
Orange is sour
** Interface
Interface is a just like a class which contains only abstract method. (Collection of
abstract method called interface) to achieve interface java provides a keyword called
implements
Interface methods are by default public and abstract.
Ex- interface client
{
void M1 (); // (by default public, abstract)
}
.interface variable are by default public+static+final
Interface method must be override inside the implementing classes.
Interface nothing but deals between client and developer.
Input
Client Developer
Output
Interface
S.
No. Class Interface
Method
Pre-defined User-defined
Program:-
public class method
{
public static void add()
{
int a=10, b=20;
System.out.print("Sum= "+(a+b));
}
void disp()
{
System.out.println("Add two Numbers");
}
public static void main(String args[])
{
method r=new method();
r.disp();
method.add();
method.add();
method.add();
method.add();
method.add();
}
}
Output: - Add two Numbers
** Inheritance
When we construct a new class from existing class in such a way that the new class
access all the features and properties of existing class called inheritance.
Note:-
____+, -
____*,%
Types of Inheritance:-
1. Single Inheritance:- Simple inheritance nothing but which contain only one super
class and one sub class is called simple inheritance.
Syntax :- class super //
{ Super class
___
}
class sub extends super
{ Sub class
___
}
Program:-
class student
{
int roll, marks;
String name;
void input()
{
System.out.println("Enter Roll Name & Marks:");
}
}
class ankit extends student
{
void form()
{
roll=1; name="Ankit"; marks=90;
System.out.println(roll+" "+name+" "+marks);
}
public static void main(String[] args)
{
ankit r=new ankit();
r.input(); r.form();
}
}
Output:-
1 Ankit 90
2. Multi-level Inheritance:-In Multi-level inheritance we have only one super class and
multiple sub classes called multi-level inheritance.
}
super
class sub1 extends super{
} sub1
class sub2 extends sub1
{ sub2
Program:-
public class calculater
{
int a,b,c;
public void add()
{
a=10; b=20;
c=a+b;
System.out.println("Sum of two number:- "+c);
}
public void sub()
{
a=200; b=100;
c=a-b;
System.out.println("Sub of two number:- "+c);
}
}
class B extends calculater
{
public void multi()
{
a=10; b=20;
c=a*b;
System.out.println("Sultiplication of two number:- "+c);
}
public void divi()
{
a=10; b=2;
c=a/b;
System.out.println("Division of two no:- "+c);
}
}
class C extends B
{
public void rem()
{
a=10; b=3;
c=a%b;
System.out.println("Remainder of two number:- "+c);
}
}
class multilevel
{
public static void main(String args[])
{
C r= new C();
r.add();r.sub(); r.multi(); r.divi(); r.rem();
}
}
Output:-
Sum of two number:- 30
3. Hierarchical Inheritance:- A Inheritance which only one super class and multiple sub
class and all sub class directly extends super class called hierarchical inheritance.
Syntax:- class A{
}
super
class B extends A {
}
class C extends A{
sub sub sub
}
Program:-
public class inheri
{
void input()
{
System.out.println("Enter your name:- ");
}
}
class B extends inheri
{
void show()
{
System.out.println("My name is Ram");
}
}
class C extends inheri
{
void display()
{
System.out.println("My name is Shyam");
}
}
class Demo
{
public static void main(String args [])
{
B r=new B();
C r2=new C();
r.input(); r.show();
r2.input(); r2.display(); }
}
Output:- Enter your name:-
My name is Ram
My name is Shyam
** Overloading
Polymorphism
Compile Time:- A polymorphism which is exists at the time of compilation is called compile
time early binding or static polymorphism. Ex.
Method overloading: - Whenever a class contains more than one method with
same name and different type of parameters called method overloading.
Syntax: - reture_type_name(parameter);
Program:-
class overl
{
void add()
{
int a=10, b=20, c;
c=a+b;
System.out.println(c);
}
void add (int x, int y)
{
int c;
c=x+y;
System.out.println(c);
}
void add(int x, double y)
{
double c;
c=x+y;
System.out.println(c);
}
public static void main(String args [])
{
overl o=new overl();
o.add(); o.add(100,200); o.add(50,45.25);
}
}
Output: - 30
300
95.25
** Overriding
Run Time: - A polymorphism which exists at the time of execution of program is called
runtime polymorphism. Ex.
Method Overriding: - Whenever we writing method in super and sub classes in such a way
that method name and parameter must be same called method overriding.
System.out.println("Child's show()");
}
}
class Main
{
public static void main(String[] args)
{
// parent obj1 = new parent();
// obj1.show();
parent obj = new Child();
obj.show();
}
}
Output: -
Child's show()
**Package in Java
Types of package
Pre-defined User-defined
Pre-defined package: - The package which are already created by java developer peple are
called pre-defined package. Ex- java.lang
java.lang: - It is the default package also know as heart of the java, because with out using
this package we can’t write a even a single program and we need not to import this
package.
Example: - System, String, Object, Integer, etc (pre-defined class).
java.util: - This package is used to implement data structure of java (data structure related
pages) it contain utility classes also known as collection frameworks.
java.IO: - IO stand for input/output this package is very useful to perform input/output
operation on file.
java.applet: - This package mainly use to develop GUI related application. Applet program
are web related program. Created at server but executed at client machine.
Example: - applet.
java.awt:- awt stand for abstract window tool kit. It is also used to developed GUI
application. The only different between applet & awt program is awt program are stand
alone program & it contain main() unlike applet.
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.
4. Reusability.
5. Security.
6. Fast Searching.
7. Hiding
Ex- P1(____) P2
A A
Program: -
import java.System;
import java.lang.String;
import java.util.Scanner;
class MyClass {
public static void main(String[] args)
{
Scanner Obj = new Scanner(System.in);
System.out.println("Enter username");
Aaradhya
User-defined:- These are the packages that are defined by the user. First we create a
directory myPackage (name should be same as the name of the package). Then create
the MyClass inside the directory with the first statement being the package names.
**Exception
Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions
can be caught and handled by the program. When an exception occurs within a method, it
creates an object. This object is called the exception object. It contains information about the
exception, such as the name and description of the exception and the state of the program
when the exception occurred.
Types of Exceptions
Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations
.
Unchecked Exceptions: - The unchecked exceptions are just opposite to the checked
exceptions. The compiler will not check these exceptions at compile time. In simple words, if
a program throws an unchecked exception, and even if we didn’t handle or declare it, the
program would not give a compilation error.
User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
Advantages of Exception Handling: -
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
The object orientation mechanism has provided the following techniques to work with
exception.
try catch throw throws finally
Pre-defined User-defined
If you have such line of code. Whichever you want whether the exception is there or not but it is
compulsory to execute, then it will be done finally.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.
class Test
{
public static void main(String args[])
{
System.out.println("method is started");
int a=10,b=0,c;
try {
c=a/b ;
System.out.println(c);
}
catch(Exception e)//ArithmeticalException
{
//System.out.println("can't divide by zero");
System.out.println("Can't divided by zero");
}
System.out.println("method is ended");
}
}
Output: -
method is started
method is ended
Program: - Throw
Program: -Throws
Program: -Throws
Output: - 12345678910
**Thread
Thread class provide constructors and methods to create and perform operations on a
thread. Thread is a pre-defined class which is available in java.lang package.
Thread is a basic unit of CPU and it is well known for independent execution.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
1. New State(Born)
2. Active State(Ready)
3. Running State(Execution)
4. Waiting state(Blocked)
5. Dead state(Exit)