Static methods and variables

Download Report

Transcript Static methods and variables

Java workshop (Session 6)
Presented by Y.Srikanth
Objectives:
Static and instance members,
Exceptions,
Multithreading,
Garbage collection and
Collections
“static” keyword:
• “static” is used to maintain fixed values.
• “static” keyword is used to access a member
without the existence of the object. “static”
members can be accessed by using the class
name directly.
• Instance members should be accessed by the
object.
• While declaring a member(may be method or
variable), if we are not prefixing a member with
“static” keyword, that member is called instance
member.
• We can call the static variables as class variables
because those members can be shared by all the
objects of that class.
• Members of a class are:
– Methods and
– Variables.
Syntax for static methods:
[modifier] static return-type methodname([parameters])
{
Logic for the method;
}
Eg:
static int add(int a, int b)
{
return (a+b);
}
Syntax for instance methods:
[modifier] return-type method-name([parameters])
{
Logic for instance method;
}
Eg:
double mul(double d1, double d2)
{
return (d1*d2);
}
Syntax for class variables:
[modifier] static type variable-name[=value];
Eg:
static int i=25;
Syntax for instance variables:
[modifier] type variable-name[=value];
Eg:
int i=25;
• In terms of objects, for every instance
member, separate copy will be created.
• For static members, one copy will be created
and shared by all the objects.
• In the case of class and instance variables, if
we are not performing the initialization, JVM
will provide the default values.
Eg:
class Demo
{
int i;
static int j;
public static void main(String[] args)
{
System.out.println(j);
Demo d=new Demo();
System.out.println(d.i);
System.out.println(d.j);
}
}
Eg:
class Test
{
int i=10;
static int j=20;
public static void main(String[] args)
{
System.out.println(j);
Test t1=new Test();
t1.i=100;
t1.j=200;
System.out.println(t1.i+”…”+t1.j);
Test t2=new Test();
System.out.println(t2.i+”…”+t2.j);
}
}
i=100
j=
200
j =20
Static variable
Important note:
We can access instance members from
instance area only. We can’t access from static
area.
Static members are accessible from instance
as well as static areas.
Exercise:
I. int i=1;
II. static int i=2;
III. public static void main(String[] args)
{
System.out.println(i);
}
Which of the above code snippet combinations
are possible?
a). I and II,
b). I and III,
c). II and III
class Member
{
int i;
public static void main(String[] args)
{
System.out.println(i);
}
}
Eg:
class StatMethDemo
{
public static void add(int i, int j)
{
System.out.println(i+j);
}
public static void main(String[] args)
{
add(10,20);
}
}
Eg:
class InstMethDemo
{
public void add(int i, int j)
//instance method
{
System.out.println(i+j);
}
public static void main(String[] args)
{
add(10,20);
}
}
Exceptions:
• An abnormal event that disturbs the normal
flow of the program is called an exception (or)
simply it is an issue.
• Main objective of exception handling is
graceful termination of the program.
• Exception handling means providing alternate
way when an exception is raised. It doesn’t
mean repairing an exception.
Eg:
class Test
{
public static void main(String[] args)
{
System.out.println("Hi");
System.out.println(10/0);
System.out.println("Bye");
}
}
 When an exception is raised, JVM will provide the
details(default mechanism) of the exception as
follows:
 Name of the exception,
 Description, and
 Stack trace(Location).
Eg:
Exception in thread “main” java.lang.ArithmeticException
:
/ by zero
at Test.main(Test.java:6)
 Throwable
class is the root class for all
exception hierarchy. It contains 2 sub-classes:
• Exception(programmatic errors which are caused by
users, recoverable)
• Error(internal errors, non-recoverable)
• Exceptions are of 2 types:
Checked (Checked by the compiler for smooth
execution of the program at run-time)
Eg:
IOException, FileNotFoundException, etc.
Unchecked
(Not checked by the compiler)
Eg:
ArithmeticException, NullPointerException,
ArrayIndexOutofBoundsException, etc.
•
Object
Throwable
Exception
RuntimeException
Error
IOException
ArithmeticException
FileNotFoundException
NullPointerException
Unchecked
Exceptions
Checked
Exceptions
• Exception related keywords:
– try
– catch
– finally
– throw
– throws
(to maintain risky code)
(to catch the exceptions)
(to maintain clean-up code)
(to modify or create own exception
and handover it to the JVM)
(for handling checked exceptions)
Eg:
class ExcDemo
{
public static void main(String[] args)
{
try
{
System.out.println(“Hello”);
System.out.println(10/0);
System.out.println(“Bye”);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println(“Finally block”);
}
}
}
• “try” with multiple “catch” blocks combination is also
possible. The order of “catch” blocks should be from
child exception to parent exception.
Eg:
class ExcDemo
{
public static void main(String[] args)
{
try
{
System.out.println("Welcome");
System.out.println(15/0);
System.out.println("Good bye");
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
“throw” keyword:
• To handover our own created exception object to
the JVM explicitly.
Eg:
class ThrowDemo
{
public static void main(String[] args)
{
throw new ArithmeticException(“Arithmetic
exception”);
}
}
“throws” keyword:
• If there is any chance of occurring checked exception, we need to
handle it manually. This can be done in 2 ways:
– Using try-catch (or)
– Using “throws” keyword.
 The purpose of “throws” keyword is to delegate the
responsibility of exception handling to the caller.
Eg:
class ThrowsDemo
{
public static void main(String[] args)
{
Thread.sleep(2000);
System.out.println(“Slept happily”);
}
}
Customized exceptions:
Eg:
class LessMarksException extends RuntimeException
{
LessMarksException(String s)
{
super(s);
}
}
class GoodMarksException extends RuntimeException
{
GoodMarksException(String s)
{
super(s);
}
}
class CustExceptionDemo
{
public static void main(String[] args)
{
int marks=Integer.parseInt(args[0]);
if(marks<50)
{
throw new LessMarksException("Poor marks");
}
else if(marks>80)
{
throw new GoodMarksException("Good marks");
}
else
{
System.out.println("Average score");
}
}
}
•
Multithreading
• Performing several activities
simultaneously(multitasking).
• Thread based multitasking
• Each task is separate independent task of the same
program.
• Each task is called a thread.
• Applicable at programmatic level.
• Thread is a light weight process.
• The main objective of multitasking is to
reduce response time of the system.
• Java provides in-built support for
multithreading.
Runnable
Thread
MyThread
MyRunnable
• Implementation of multithreading can be done in 2
ways:
– By extending Thread class:
Eg:
Class MyThread extends Thread
{
public void run()
{
Defining a
for(int i=0;i<4;i++)
thread
{
System.out.println(“child thread”);
}
}
}
Job of
the
thread
Class ThreadDemo
{
public static void main(String[] args)
// Main
thread
{
MyThread t=new MyThread(); // Instatiation of
thread
t.start();
// Starting child thread
for(int i=0;i<4;i++)
{
System.out.println(“Main thread”);
}
}
}
• By implementing Runnable interface:
Class MyRunnable implements Runnable
{
public void run()
{
for(int i=0;i<4;i++)
Defining
{
System.out.println(“Child thread”);
}
}
}
Job
Class ThreadDemo
{
public static void main(String[] args)
{
MyRunnable r=new MyRunnable();
Thread t=new Thread(r);
Target
t.start();
runnable
for(int i=0;i<4;i++)
{
System.out.println(“Main thread”);
}
}
}
• The purpose of ThreadScheduler is to get the
opportunity for execution when multiple
threads are awaiting.
ThreadScheduler
Main thread
Child thread
Thread life cycle:
MyThread t=new MyThread();
New/
Born
t.start()
Ready/
Runnable
If ThreadScheduler
allocated CPU
Running
Dead
If run() completes
Waiting
state
Thread synchronization:
• This can be done by using “synchronized”
keyword.
• “synchronized” keyword is applicable for
methods and blocks.
• If a method (or) block is declared as
“synchronized”, then at a time only one
thread is allowed to execute.
• Advantage of “synchronized” is to avoid data
inconsistency problems.
Declaration:
[modifier] synchronized return-type methodname([parameters])
{
Logic for synchronized method;
}
Eg:
public synchronzied void access()
{
System.out.println(“Only one thread can be
accessed”);
}
Eg:
class TestSync implements Runnable
{
int balance;
public synchronized void run() //synchronized method
{
for(int i=0;i<5;i++)
{
increment();
System.out.println("Bal is:"+balance);
}
}
public void increment()
{
int i=balance;
balance=i+1;
}
}
class SyncDemo
{
public static void main(String[] args)
{
TestSync t=new TestSync();
Thread a=new Thread(t);
Thread b=new Thread(t);
a.start();
b.start();
}
}
Methods for preventing thread from execution:
 yield() (to cause current thread to pause
and to give chance for remaining
threads of same priority)
 join()
(to make the thread to wait for the
completion of other thread)
 sleep() (for making a thread to sleep for
specified number of milli-seconds)
Program for yield():
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
Thread.yield();
System.out.println("child");
}
}
}
class YieldDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
for(int i=0;i<5;i++)
{
System.out.println("main");
}
}
}
Thread interruption:
• One thread can interrupt another thread by using interrupt().
Eg:
class MyThread extends Thread
{
public void run()
{
try
{
for(int i=0;i<20;i++)
{
System.out.println("lazy");
}
Thread.sleep(5000);
}
catch(InterruptedException e)
{
System.out.println("got interrupted");
}
}
}
class InterruptDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
t.interrupt();
System.out.println("active");
}
}
•
Garbage collection
• In old languages like C++, the programmer is
responsible for the creation and destruction of
objects.
• In Java, programmer is only responsible for the
creation of objects. Object destruction is not
required.
• Sun introduced one assistant which is running in
background for the destruction of useless objects
which is called garbage collector.
• We can request JVM to run garbage collector in 2
ways:
– By System class
– By Runtime class
(using gc())
• In Runtime object, we can use the following
methods:
– freeMemory()  Returns free memory available
in the heap.
– totalMemory()  Returns total memory of the
heap
– gc()
 For requesting JVM to run
garbage collector
• Before destroying any object, GC always calls finalize()
which is present in Object class. The object which is
eligible for GC, the corresponding finalize() will be
executed.
• When calling gc(), it may not be impacted immediately.
Eg:
class RuntimeDemo
{
public static void main(String[] args)
{
Runtime r=Runtime.getRuntime();
System.out.println(r.totalMemory());
System.out.println(r.freeMemory());
for(int i=0;i<500;i++)
{
java.lang.String d=new java.lang.String();
d=null;
}
System.out.println(r.freeMemory());
r.gc();
System.out.println(r.freeMemory());
}
}
Eg:
class Test
{
public static void main(String[] args)
{
//String s=new String("hello");
//s=null;
Test t=new Test();
t=null;
System.gc();
System.out.println("End of main");
}
public void finalize()
{
System.out.println("Finalize called");
}
}
For String class
finalize()
•
Collections
• Array is indexed collection of fixed number of
homogeneous elements. Limitations of arrays are:
– Fixed in size,
– Can hold only homogeneous data elements.
– Underlying data structure not available.
• To overcome the above limitations, we can go for
Collection.
• To use the properties of Collection, we need to import a
package named with java.util
Collections are growable in nature.
Can hold homogeneous and heterogeneous elements.
Underlying data structures are available.
Collection hierarchy:
Collection
Set
List
ArrayList
LinkedList
HashSet
Map
HashMap
Hashtable
SortedSet
Collection interface:
• If we want to represent a group of individual
objects as single entity, then we can use Collection.
• Few methods available in Collection interface:
– boolean add(Object o);
– boolean addAll(Collection c);
– boolean remove(Object o);
– boolean isEmpty();
– int size();
ArrayList class:
• Underlying data structure is resizable (or) growable array.
• Insertion order is preserved.
• Duplicate objects are allowed.
• Heterogeneous objects are allowed.
• “null” insertion is possible.
 Best suitable if our frequent operation is retrieval.
 ArrayList implements RandomAccess interface.
Constructors:
ArrayList():
Creates empty ArrayList object with
default capacity 10. If max.
capacity is reached,
new capacity =currentcapacity*(3/2)+1
ArrayList(int size): Empty ArrayList object with specified
capacity will be created.
ArrayList(Collection c):
Creates an equivalent ArrayList
object for c.
Eg:
import java.util.*;
class ALDemo
{
public static void main(String[] args)
{
ArrayList sampleList=new ArrayList();
l.add("A");
l.add(10);
l.add("A");
l.add(null);
System.out.println(sampleList);
l.remove(2);
l.add(1,"B");
System.out.println(sampleList);
l.add(0);
System.out.println(sampleList);
}
}
HashSet class:
• Underlying data structure is Hashtable.
• Insertion order is not preserved.
• Duplicate objects are not allowed.
• Heterogeneous objects are allowed.
• “null” insertion is possible, but only once.
Best suitable if our frequent operation is
search.
HashSet implements Serializable and
Cloneable interfaces.
Eg:
import java.util.*;
class HSDemo
{
public static void main(String[] args)
{
HashSet sampleSet=new HashSet();
h.add("B");
h.add("A");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(sampleSet);
}
}
Hashtable class:
• Underlying data structure is Hashtable.
• Heterogeneous objects are allowed.
• Insertion order is not preserved and it is based
on hashCode.
• “null” insertion is not allowed.
Eg:
import java.util.*;
class HtDemo
{
public static void main(String[] args)
{
Hashtable h=new Hashtable();
h.put(new Temp(5),"A");
h.put(new Temp(2),"B");
h.put(new Temp(6),"C");
h.put(new Temp(15),"D");
h.put(new Temp(23),"E");
h.put(new Temp(16),"F");
System.out.println(h);
}
}
10
9
8
7
6=C
6
5=A, 16=F
5
15=D
4
3
2=B
2
23=E
1
0
class Temp
{
int i;
Temp(int i)
{
this.i=i;
}
public String toString()
{
return i+"";
}
public int hashCode()
{
return i;
}
}
Thank you