Professional Documents
Culture Documents
JAVA
JAVA
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]+" ");
}
System.out.println();
} } }
Java modifiers
Access
non –access modifiers
Access modifiers:
Public –access within its own and other
package
Private-access with in the class
Protected-access within a package and
subclasses
Default-with in a package
Non access modifiers
• final -we can use class, variable, method ,object.
• static-we can use class, variable ,method ,object.
• abstract - we can use class, variable, method.
• Synchronized -it is used in threads
Variables
• Variables are memory locations which are
reserved to store values.
1.Local variable – inside the method.static
keyword(cant)
2.Instance variable – inside the class outside the
method.
3.static variable – using static keyword
Constructor
• Constructor is used in the creation of an object
• It is the block of code used to initialize an
object
• Constructor gets executed when an object of a
class is being created
• A constructor always has the same name as the
class name
• Constructor doesn’t have any return type
constructor method
Types:
1.Compile time polymorphism(overloading)
2.Run time polymorphism(overriding)
Types of overloading:
1.Constructor overloading
2.Method overloading
Method overloading
method name same for all and different parameter
Example:
class testadd{
void sum(int a,int b){
System.out.println(a+b);}
void sum(int c,int d,int e){
System.out.println(c+d+e);
}}
public class JavaApplication5{
public static void main(String args[]){
testadd obj=new testadd();
obj.sum(10, 10);
obj.sum(10, 20, 30); } }
Constructor overloading
Class s{
s(){
s.o.p(“default”);}
s(int x,float y);{
s.o.p(“x= “+x);
s.o.p(“y= “+y);
}
s(float a,int b){
s.o.p(“a =“+a);
s.o.p(“b= ”+b);
}}
Public class java{
p.s.v.m(){
s obj1=new s();
s obj2=new s(5,10.5f);
s obj3=new s(10.5f,3);
Method overriding
• Method overriding must be used in case of
inheritance.
• Method must have the same name as in
parent class
• Method must have the same parameters as in
parent class.
Over riding
Same name with same parameter
Class A{
Void msg(){
System.out.println(“hello”);}
Class B{
Void msg(){
System.out.println(“welcome”);}
Class C extends B{
Public static void main(String args[]){
C obj=new C();
Obj.msg();//now which msg()method would be invoked?
Super keyword
• It is a reference variable that is used to refer
parent class objects
• parent class instance variable
• Used to invoke parent class method
• Used to invoke parent class constructor
class tree1{
String fruits="I have 2 fruits";
}
class tree2 extends tree1{
String fruits="I have 2 leaves";
void printfruits(){
System.out.println(fruits);//prints fruits of tree2
System.out.println(super.fruits);//prints fruits of tree1}}
public class JavaApplication5 {
public static void main(String args[]){
tree2 obj=new tree2();
obj.printfruits();}}
Java final keyword
class Bike9{
final int speedlimit=90
void run(){
speedlimit=400; }
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
} }
This keyword
In Java, this is a reference variable
that refers to the current object.
• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call
• public class example{
• int a=12;
• void display() {
• int a=34;
• System.out.println(this.a);
• }
• public static void main(String args[]) {
• example obj=new example();
• obj.display();
• }
• }
binding in java
• Connecting a method call to the method
body is known as binding.
• Static Binding (also known as Early
• Binding) – when type of the object is
determined at compiled time
• Dynamic Binding (also known as Late Binding)
– when type of the object is determined at run
time
Static binding
If there is any private, final or static method in a
class, there is static binding.
Example:
class Dog{
private void eat()
{System.out.println("dog is eating...");}
public static void main(String args[]){
Dog d1=new Dog();
d1.eat(); } }
Dynamic binding
class Animal{
void eat()
{System.out.println("animal is eating...");} }
class Dog extends Animal{
void eat()
{System.out.println("dog is eating...");}
public static void main(String args[]){
Animal a=new Dog();
a.eat(); } } //dog is eating
Abstraction
• Hiding implementation details .only providing
the functionality to the user.
• Abstraction lets you focus on what the object
does instead of how it does it.
• There are two ways to achieve abstraction in
java
• Abstract class(0 to 100% abstraction)
• Interface(100% abstraction)
Abstract class
• A class which is declared as abstract is known as an abstract
class.
• It can have abstract and non-abstract methods.
• It needs to be extended and its method implemented. It
cannot be instantiated
Syntax:
abstract class a{
Abstract method();}
Class b extends class a{
Public method(){ }}
Abstract method
• A method which is declared as abstract and
does not have implementation is known as an
abstract method.
abstract class a{
abstract void fun();
void display(){
System.out.println("abstract a");}
}
class b extends a{
public void fun(){
System.out.println("functions");}}
public class example{
public static void main(String args[]){
b obj=new b();
obj.display();
obj.fun();
}}
Encapsulation
• Encapsulation is the methodology of binding
code and data together into single unit.
• To achieve encapsulation in java:
• Declare the variables of a class as private
• Abstraction+datahiding
Interface
The interface in Java is a mechanism to
achieve abstraction.
There can be only abstract methods in the Java
interface, not method body.
Uses of interface:
• It is used to achieve abstraction.
• By interface, we can support the functionality
of multiple inheritance.
• Class to class extends
• class to interface implements
• Interface to interface extends
Interface transactionl{
Void withdrawamt(int amtTowithdraw);}
Class Transactionlmpl implements transactional{
Void withdrawamt(int amtTowithdraw){
//logic of withdraw
}}
//Amazon side
Transactionl ti=new transactionlmpl();
Ti.withdrawamt(500);
• Syntax
Interface interface-name
{
Method declaration;
}
Class classname implements interfacename{ }
Example-1
interface a{
void setdata(int x);}
interface b{
void getdata();}
public class sbi implements a,b{
static int c;
public void setdata(int x){
c=x;
System.out.println(c);
}
public void getdata(){
System.out.println(c); }
public static void main(String args[]){
sbi s=new sbi();
s.setdata(12);
s.getdata();}}
interface a{
void display1();}
interface b extends a{
void display2();}
public class sbi implements b {
public void display1(){
System.out.println("interface a");}
public void display2(){
System.out.println("interface b");}
void display(){
System.out.println("sbi class ");}
public static void main(String[] args) {
sbi s=new sbi();
s.display1();
s.display2();
s.display(); }}
Assertion
Assertion is a statement in java. It can be used to
test your assumptions about the program.
While executing assertion, it is believed to be
true. If it fails, JVM will throw an error named
Assertion Error. It is mainly used for testing
purpose
Syntax:
1. assert expression;
2. assert expression1 : expression2;
import java.util.Scanner;
class AssertionExample{
public static void main( String args[] ){
Scanner scanner = new Scanner( System.in );
System.out.print("Enter your age ");
int value = scanner.nextInt();
assert value>=18:" Not valid";
System.out.println("value is "+value); } }
Exception
Handling
1
Exception
Handling
Exceptionisaproblemthatarise during the execution time
Anabnormaleventwhichstopstheprogram abruptly.
Errors:
• unpredictable
• Errors are of unchecked type
• Happen at run time
• Caused by the environment on which application is running
• Eg : out of memory error.
Exception:
• Predictable
• It can be of checked or unchecked
• Can happen at compile time & runtime
• Caused by application
Checked exception:
• An exception that is checked by the compiler at compilation
time.
• These exceptions cannot simply be ignored , the programmer
should handle these exceptions.
Unchecked exceptions:
• Runtime exception is the superclass of those exceptions that
can be thrown during the normal operation of the jvm.
• Runtime exception and its subclasses are unchecked
exceptions.
Exception handling
• Exception handling is a mechanism to handle errors in the
runtime
• So that the normal flow of the application is maintained
Keywords for Exception Handling
1.Try 2.Catch 3.Finally 4.Throw 5.Throws
Throw:
• Used to explicitly throw an exception
• Checked exceptions cannot be propagated using throw only.
• Followed by an instance
• Cannot throw multiple exceptions
Throws:
• Used to declare an exception
• Checked exceptions can be propagated
• Followed by a class
• Used with a method signature
• Can declare multiple exceptions
• Final –keyword
• Applies restrictions on class , methods and variable.
• Final class cant be inherited , method cant be overridden &the
variable value cant be changed
• Finally-block
• Used to place an important code
• It will be executed whether the exception is handled or not
• Finalize-method
• Used to perform clean up processing just before the object is
garbage collected
Exception Handling using throw
class Test{
static void avg() {
int a=10,b=0,c;
try {
c=a/b;
System.out.println(c);
throw new
ArithmeticException("d
emo");}
catch(ArithmeticException e)
{ System.out.println("Exception caught");
}}
public static void main(String args[]) {
avg(); }}
Exception Handling using try ,catch, finally
class ExceptionTest{
public static void main(String …as){ try{
Int a=10,b=0,c;
C=a/b;
System.out.println(c);}
catch(Exception e)
{ System.out.println(e);}
finally{
System.out.println(“am from
finally”);
}}}
Exception Handling using throws
class Test1{
static void check() throws Exception {
int a=10,b=0,c;
c=a/b; System.out.println(c);
System.out.println("Inside check
function");
}
public static void main(String args[]) {
try {
check();
}
catch(ArithmeticException e)
{ System.out.println("caught" + e); } }}
Types of exceptions
• Built in exception
• User defined exception
• Built in exceptions:
• Arithmetic exception
• Array index out of bound exception
• Class not found exception
• Io exception
• Interrupt exception
• No such field exception
• No such method exception
• Number format exception
• Runtime exception
• String index out of bounds exception
User defined
9
THREAD AND MULTITHREADING
Thread: Definition
• A Thread is similar to a Sequential program. Collection of thread
is called as process.
• It is a part of execution
• A thread is not a program on its own but runs within a
program.
• Every program has at least one thread that is called the Primary
Thread.
• We can create more threads when necessary.
• Threads are very useful when you have large computations that
take several seconds to complete, and the user should not
perceive the delay.
• Animation is another area where threads are used.
• A thread is also known as a lightweight process or execution
context.
Example
• Most computer games use graphics and sound.
• The graphics and audio go on simultaneously.
• A single game has all these elements being processed at the same
time.
• In other words, the program has been divided into three sub units,
each sub units handled by a thread. The microprocessor allocates
memory to the processes that
you execute.
• Each process occupies its own address space (memory).
• However, all the threads in a process share the same address
space.
• Resources like memory, devices, data of a program, and
environment of a program are
available to all the threads of that program.
Multitasking
Process based
Thread based
Process based
Collection of
thread is
known Tas
process.
T Process
T
T
Thread based
init->start->Runnable->Not Runnable->Dead
• The second way to create a thread is to create a new class that extends
Thread class using the following two simple steps.
• This approach provides more flexibility in handling multiple threads created
using available methods in Thread class.
Step 1:
• You will need to override run( ) method available in Thread class.
• This method provides entry point for the thread and you will put your
complete
business logic inside this method. Following is the simple syntax of run()
method: public void run( )
Step 2:
• Once Thread object is created, you can start it by calling start( ) method,
which executes a call to run( ) method. Following is the simple syntax of
start() method:
SYNTAX
void start( );
join method
• package javaapplication;
• public class javaapplication extends Thread{
• public void run() {
• System.out.println("running "+Thread.currentThread().getName());
• System.out.println("priority "+Thread.currentThread().getPriority());
• }
• public static void main(String[] args) {
• javaapplication obj1=new javaapplication();
• javaapplication obj2 =new javaapplication();
• obj1.setPriority(Thread.MAX_PRIORITY);
• obj2.setPriority(Thread.MIN_PRIORITY);
• obj1.start();
• obj2.start();
• }}
Daemon Thread
• Daemon thread is a low priority thread that runs in background to perform tasks
such as garbage collection.
• package javaapplication;
• public class example extends Thread{
• public void run() {
• if(Thread.currentThread().isDaemon()) {
• System.out.println("daemonThread "+Thread.currentThread().getName());}
• else {
• System.out.println("user Thread "+Thread.currentThread().getName());}}
• public static void main(String[] args) {
• example t1=new example();
• example t2=new example();
• t1.setDaemon(true);
• t1.start();
• t2.start();}}
Garbage collection
• Garbage collection is a process of reclaiming the runtime unused
memory automatically.
• Its way to destroy unused objects
• Advantages : memory is efficient because garbage collector removes
the unrefferd object for, heap memory.
• It is automatically done so we don’t need to take extra efforts
• It contains finalize method by default
• Garbage collector removes the object which is created by “new”
keyword
• Finalize method is used to remove the object which is not created by
“new” keyword.
• Finalize method is automatically invoked each time before the object
is garbage collector.
• Garbage collector is a daemon thread
Garbage collection
• package javaapplication;
• public class example {
• void print() {
• System.out.println("hello");
• }
• public void finalize() {
• System.out.println("garbage collection");
• }
• public static void main(String args[]) {
• example e1=new example();
• example e2=new example();
• e1.print();
• e2=null;
• System.gc();}}
synchronization
• Synchronization block
• Synchronization method
• Static synchronization no need for object creation
• package javaapplication;
• class example extends Thread{
• synchronized public void run() {
• for(int i=0;i<5;i++) {
• int a=2;
• System.out.println(a+" "+i+" "+a*i);
• }}
• public static void main(String args[]) {
• example e=new example();
• example e1=new example();
• e.start();
• e1.start();}}
Packages