The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Vinit Kapoor, 2020-07-10 11:58:41

Java Programming

Java Programming

13.16 Access modifier

Private access modifier

Role of private constructor

Default access modifier

Protected access modifier

Public access modifier

Access Modifier with Method Overriding

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.

There are four types of Java access modifiers:

Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.

Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.

Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.

Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native,
volatile, transient, etc. Here, we are going to learn the access modifiers only.

Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a simple table.

Access Modifier within class within package outside package outside package
by subclass only
Private YN
Default YY NN
Protected YY NN
Public YY YN
YY

1) Private
The private access modifier is accessible only within the class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
class, so there is a compile-time error.
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
}
}
Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){

A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
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
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.
It provides more accessibility than the default modifer.
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
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
13.17 Encapsulation
Encapsulation in Java is a process of wrapping code and data together into a single unit, for
example, a capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of a fully encapsulated class.
Advantage of Encapsulation in Java
By providing only a setter or getter method, you can make the class read-only or write-only.
In other words, you can skip the getter or setter methods.

It provides you the control over the data. Suppose you want to set the value of id which
should be greater than 100 only, you can write the logic inside the setter method. You can
write the logic not to store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the
data through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it is
easy and fast to create an encapsulated class in Java.
Simple Example of Encapsulation in Java
Let's see the simple example of encapsulation that has only one field with its setter and
getter methods.
File: Student.java
//A Java class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.
package com.javatpoint;
public class Student{
//private data member
private String name;
//getter method for name
public String getName(){
return name;
}
//setter method for name
public void setName(String name){
this.name=name
}
}
File: Test.java
//A Java class to test the encapsulated class.
package com.javatpoint;

class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
s.setName("vijay");
//getting value of the name member
System.out.println(s.getName());
}
}
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test
Output:
vijay
Read-Only class
//A Java class which has only getter methods.
public class Student{
//private data member
private String college="AKG";
//getter method for college
public String getCollege(){
return college;
}
}
Now, you can't change the value of the college data member which is "AKG".
s.setCollege("KITE");//will render compile time error
Write-Only class
//A Java class which has only setter methods.

public class Student{
//private data member
private String college;
//getter method for college
public void setCollege(String college){
this.college=college;
}
}
Now, you can't get the value of the college, you can only change the value of college data
member.
System.out.println(s.getCollege());//Compile Time Error, because there is no such method
System.out.println(s.college);//Compile Time Error, because the college data member is
private.
//So, it can't be accessed from outside the class
Another Example of Encapsulation in Java
Let's see another example of encapsulation that has only four fields with its setter and getter
methods.
File: Account.java
//A Account class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.
class Account {
//private data members
private long acc_no;
private String name,email;
private float amount;
//public getter and setter methods
public long getAcc_no() {

return acc_no;
}
public void setAcc_no(long acc_no) {

this.acc_no = acc_no;
}
public String getName() {

return name;
}
public void setName(String name) {

this.name = name;
}
public String getEmail() {

return email;
}
public void setEmail(String email) {

this.email = email;
}
public float getAmount() {

return amount;
}
public void setAmount(float amount) {

this.amount = amount;
}
}
File: TestAccount.java
//A Java class to test the encapsulated class Account.
public class TestEncapsulation {
public static void main(String[] args) {

//creating instance of Account class
Account acc=new Account();
//setting values through setter methods

acc.setAcc_no(7560504000L);
acc.setName("Sonoo Jaiswal");
acc.setEmail("[email protected]");
acc.setAmount(500000f);
//getting values through getter methods
System.out.println(acc.getAcc_no()+" "+acc.getName()+" "+acc.getEmail()+"
"+acc.getAmount());
}
}
Output:
7560504000 Sonoo Jaiswal [email protected] 500000.0

14.Multithreading

14.1 Introduction to Multithreading

Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a
single thread.
Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved in two ways:

1) Process-based Multitasking (Multiprocessing)

2) Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)

Each process has an address in memory. In other words, each process allocates a separate
memory area.

A process is heavyweight.

Cost of communication between the process is high.

Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)

Threads share the same address space.

A thread is lightweight.

Cost of communication between the thread is low.

Note: At least one process is required for each thread.

What is Thread in java

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.

Java Thread class

Java provides Thread class to achieve thread programming. Thread class provides
constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface.

Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a thread. Thread
class extends Object class and implements Runnable interface.

Java Thread Methods

S.N. Modifier and Method Description

Type

1) void start() It is used to start the execution of the thread.

2) void run() It is used to do an action for a thread.

3) static void sleep() It sleeps a thread for the specified amount of time.

4) static Thread currentThread( It returns a reference to the currently executing thread object.
)

5) void join() It waits for a thread to die.

6) int getPriority() It returns the priority of the thread.

7) void setPriority() It changes the priority of the thread.

8) String getName() It returns the name of the thread.

9) void setName() It changes the name of the thread.

10) long getId() It returns the id of the thread.

11) boolean isAlive() It tests if the thread is alive.

12) static void yield() It causes the currently executing thread object to pause and allow
threads to execute temporarily.

13) void suspend() It is used to suspend the thread.

14) void resume() It is used to resume the suspended thread.

15) void stop() It is used to stop the thread.

16) void destroy() It is used to destroy the thread group and all of its subgroups.

17) boolean isDaemon() It tests if the thread is a daemon thread.

18) void setDaemon() It marks the thread as daemon or user thread.

19) void interrupt() It interrupts the thread.

20) boolean isinterrupted() It tests whether the thread has been interrupted.

21) static boolean interrupted() It tests whether the current thread has been interrupted.

22) static int activeCount() It returns the number of active threads in the current thread's thre
group.

23) void checkAccess() It determines if the currently running thread has permission to mo
the thread.

24) static boolean holdLock() It returns true if and only if the current thread holds the monitor lo
the specified object.

25) static void dumpStack() It is used to print a stack trace of the current thread to the standa
error stream.

26) StackTraceEle getStackTrace It returns an array of stack trace elements representing the stack

ment[] () of the thread.

27) static int enumerate() It is used to copy every active thread's thread group and its subg
into the specified array.

28) Thread.State getState() It is used to return the state of the thread.

29) ThreadGroup getThreadGro It is used to return the thread group to which this thread belongs
up()

30) String toString() It is used to return a string representation of this thread, including
thread's name, priority, and thread group.

31) void notify() It is used to give the notification for only one thread which is wait
a particular object.

32) void notifyAll() It is used to give the notification to all waiting threads of a particu
object.

33) void setContextCla It sets the context ClassLoader for the Thread.
ssLoader()

34) ClassLoader getContextCla It returns the context ClassLoader for the thread.
ssLoader()

35) static getDefaultUnc It returns the default handler invoked when a thread abruptly term

Thread.Uncau aughtExceptio due to an uncaught exception.

ghtExceptionH nHandler()

andler

36) static void setDefaultUnc It sets the default handler invoked when a thread abruptly termin
aughtExceptio due to an uncaught exception.
nHandler()

14.2 Life cycle of thread

A thread can be in one of the five states. According to sun, there is only 4 states in thread
life cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.\
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
New
Runnable
Running
Non-Runnable (Blocked)

next →← prev
Life cycle of a Thread (Thread States)
Life cycle of a thread
New
Runnable
Running
Non-Runnable (Blocked)
Terminated
A thread can be in one of the five states. According to sun, there is only 4 states in thread
life cycle in java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:

New
Runnable
Running
Non-Runnable (Blocked)
Terminated
Java thread life cycle
1) New
The thread is in new state if you create an instance of Thread class but before the invocation
of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
14.3 Creating a Thread
There are two ways to create a thread:

1) By extending Thread class
2) By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
Thread()
Thread(String name)

Thread(Runnable r)
Thread(Runnable r,String name)
Commonly used methods of Thread class:
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
1) Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...
2) Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){
Multi3 m1=new Multi3();

Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread
object.So you need to explicitely create Thread class object.We are passing the object of
your class that implements Runnable so that your class run() method may execute.
14.4Sleeping a thread
The sleep() method of Thread class is used to sleep a thread for the specified amount of
time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:
public static void sleep(long miliseconds)throws InterruptedException
public static void sleep(long miliseconds, int nanos)throws InterruptedException
Example of sleep method in java
class TestSleepMethod1 extends Thread{
public void run(){

for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);

}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
t1.start();
t2.start();
}
}

Output:
1
1
2
2
3
3
4
4

As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.
14.5 Start a thread twice
No. After starting a thread, it can never be started again. If you does so, an
IllegalThreadStateException is thrown. In such case, thread will run once but for
second time, it will throw exception.
Let's understand it by the example given below:
public class TestThreadTwice1 extends Thread{
public void run(){

System.out.println("running...");
}
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
}
}
Test it Now

running
Exception in thread "main" java.lang.IllegalThreadStateException

14.6 Calling run method
Each thread starts in a separate call stack.
Invoking the run() method from main thread, the run() method goes onto the current
call stack rather than at the beginning of a new call stack.
class TestCallRun1 extends Thread{
public void run(){

System.out.println("running...");
}
public static void main(String args[]){
TestCallRun1 t1=new TestCallRun1();
t1.run();//fine, but does not start a separate call stack
}
}
Test it Now
Output:running...

class TestCallRun2 extends Thread{
public void run(){
for(int i=1;i<5;i++){

try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);

}
}
public static void main(String args[]){
TestCallRun2 t1=new TestCallRun2();
TestCallRun2 t2=new TestCallRun2();
t1.run();
t2.run();
}
}
Output:1

2
3
4
5
1
2
3
4
5
As you can see in the above program that there is no context-switching because
here t1 and t2 will be treated as normal object not thread object.
14.7 Joining a thread
The join() method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
Example of join() method

class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){

try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
Output:1

2
3
4
5
1

1
2
2
3
3
4
4
5
5
Example of join(long miliseconds) method
class TestJoinMethod2 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod2 t1=new TestJoinMethod2();
TestJoinMethod2 t2=new TestJoinMethod2();
TestJoinMethod2 t3=new TestJoinMethod2();
t1.start();
try{
t1.join(1500);
}catch(Exception e){System.out.println(e);}

t2.start();
t3.start();
}
}
Test it Now
Output:1

2
3
1
4
1
2
5
2
3
3
4
4
5
5
In the above example,when t1 is completes its task for 1500 miliseconds(3 times)
then t2 and t3 starts executing.
getName(),setName(String) and getId() method:
public String getName()
public void setName(String name)
public long getId()

class TestJoinMethod3 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestJoinMethod3 t1=new TestJoinMethod3();
TestJoinMethod3 t2=new TestJoinMethod3();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}

}
Test it Now
Output:Name of t1:Thread-0

Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...
14.8 Naming a thread
The Thread class provides methods to change and get the name of a thread. By
default, each thread has a name i.e. thread-0, thread-1 and so on. By we can
change the name of the thread by using setName() method. The syntax of
setName() and getName() methods are given below:

public String getName(): is used to return the name of a thread.
public void setName(String name): is used to change the name of a thread.
Example of naming a thread
class TestMultiNaming1 extends Thread{

public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Output:Name of t1:Thread-0

Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:Sonoo Jaiswal
running...

Current Thread
The currentThread() method returns a reference of currently executing thread.

public static Thread currentThread()
Example of currentThread() method
class TestMultiNaming2 extends Thread{
public void run(){

System.out.println(Thread.currentThread().getName());
}
public static void main(String args[]){
TestMultiNaming2 t1=new TestMultiNaming2();
TestMultiNaming2 t2=new TestMultiNaming2();
t1.start();
t2.start();
}
}
Test it Now
Output:Thread-0

Thread-1
14.9 Thread Priority
Each thread have a priority. Priorities are represented by a number between 1 and 10. In
most cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification
that which scheduling it chooses.
3 constants defined in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and
the value of MAX_PRIORITY is 10.
Example of priority of a Thread:
class TestMultiPriority1 extends Thread{
public void run(){

System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Test it Now
Output:running thread name is:Thread-0

running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
14.10 Daemon Thread
Daemon thread in java is a service provider thread that provides services to the user thread.
Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole in the command prompt. The jconsole tool
provides information about the loaded classes, memory usage, running threads etc.

Points to remember for Daemon Thread in Java

It provides services to user threads for background supporting tasks. It has no role in life
than to serve user threads.

Its life depends on user threads.

It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread?

The sole purpose of the daemon thread is that it provides services to user thread for
background supporting task. If there is no user thread, why should JVM keep running this
thread. That is why JVM terminates the daemon thread if there is no user thread.

Methods for Java Daemon thread by Thread class

The java.lang.Thread class provides two methods for java daemon thread.

No. Method Description

1) public void is used to mark the current thread as daemon
setDaemon(boolean status) thread or user thread.

2) public boolean isDaemon() is used to check that current is daemon.

File: MyThread.java
public class TestDaemonThread1 extends Thread{
public void run(){

if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread

TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
}
}
Test it Now
Output
daemon thread work
user thread work
user thread work
14.11 Performing multiple task
If you have to perform single task by many threads, have only one run() method.For
example:
Program of performing single task by multiple threads
class TestMultitasking1 extends Thread{
public void run(){
System.out.println("task one");
}
public static void main(String args[]){
TestMultitasking1 t1=new TestMultitasking1();
TestMultitasking1 t2=new TestMultitasking1();
TestMultitasking1 t3=new TestMultitasking1();

t1.start();
t2.start();
t3.start();

}
}
Test it Now
Output:task one

task one
task one
Program of performing single task by multiple threads
class TestMultitasking2 implements Runnable{
public void run(){
System.out.println("task one");
}
public static void main(String args[]){
Thread t1 =new Thread(new TestMultitasking2());//passing annonymous object of
TestMultitasking2 class
Thread t2 =new Thread(new TestMultitasking2());
t1.start();
t2.start();
}
}
Test it Now
Output:task one
task one
Note: Each thread run in a separate callstack.

How to perform multiple tasks by multiple threads (multitasking in multithreading)?
If you have to perform multiple tasks by multiple threads,have multiple run() methods.For
example:
Program of performing two tasks by two threads
class Simple1 extends Thread{
public void run(){

System.out.println("task one");
}
}
class Simple2 extends Thread{
public void run(){

System.out.println("task two");
}
}
class TestMultitasking3{
public static void main(String args[]){
Simple1 t1=new Simple1();

Simple2 t2=new Simple2();
t1.start();
t2.start();
}
}
Test it Now
Output:task one

task two
Same example as above by annonymous class that extends Thread class:
Program of performing two tasks by two threads
class TestMultitasking4{
public static void main(String args[]){

Thread t1=new Thread(){
public void run(){
System.out.println("task one");
}

};
Thread t2=new Thread(){

public void run(){
System.out.println("task two");

}
};
t1.start();
t2.start();
}
}
Test it Now
Output:task one

task two
Same example as above by annonymous class that implements Runnable interface:
Program of performing two tasks by two threads
class TestMultitasking5{
public static void main(String args[]){

Runnable r1=new Runnable(){
public void run(){
System.out.println("task one");
}

};
Runnable r2=new Runnable(){

public void run(){
System.out.println("task two");

}
};
Thread t1=new Thread(r1);
Thread t2=new Thread(r2);
t1.start();
t2.start();
}
}
Test it Now
Output:task one

task two

15 Date

15.1 Java 8 date time
Java LocalDate class
Java LocalDate class is an immutable class that represents Date with a default format of
yyyy-MM-dd. It inherits Object class and implements the ChronoLocalDate interface
Java LocalDate class declaration
Let's see the declaration of java.time.LocalDate class.
public final class LocalDate extends Object
implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable

Method Description

LocalDateTime atTime(int It is used to combine this date with a time to create a LocalDateTime.
hour, int minute) It is used to compares this date to another date.

int It is used to check if this date is equal to another date.
compareTo(ChronoLocalDate It is used to format this date using the specified formatter.
other)
It is used to get the value of the specified field from this date as an int.
boolean equals(Object obj) It is used to check if the year is a leap year, according to the ISO proleptic calen
It is used to return a copy of this LocalDate with the specified number of days su
String It is used to return a copy of this LocalDate with the specified number of months
format(DateTimeFormatter It is used to obtain the current date from the system clock in the default time-zon
formatter) It is used to return a copy of this LocalDate with the specified number of days ad

int get(TemporalField field)

boolean isLeapYear()

LocalDate minusDays(long
daysToSubtract)

LocalDate minusMonths(long
monthsToSubtract)

static LocalDate now()

LocalDate plusDays(long
daysToAdd)

LocalDate plusMonths(long It is used to return a copy of this LocalDate with the specified number of months
monthsToAdd)

ava LocalDate Example
import java.time.LocalDate;
public class LocalDateExample1 {

public static void main(String[] args) {
LocalDate date = LocalDate.now();
LocalDate yesterday = date.minusDays(1);
LocalDate tomorrow = yesterday.plusDays(2);
System.out.println("Today date: "+date);
System.out.println("Yesterday date: "+yesterday);
System.out.println("Tommorow date: "+tomorrow);

}
}
Output:
Today date: 2017-01-13
Yesterday date: 2017-01-12
Tommorow date: 2017-01-14
Java LocalDate Example: isLeapYear()
import java.time.LocalDate;
public class LocalDateExample2 {

public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2017, 1, 13);
System.out.println(date1.isLeapYear());
LocalDate date2 = LocalDate.of(2016, 9, 23);
System.out.println(date2.isLeapYear());

}

}
Output:
false
true
Java LocalDate Example: atTime()
import java.time.*;
public class LocalDateExample3 {

public static void main(String[] args) {
LocalDate date = LocalDate.of(2017, 1, 13);
LocalDateTime datetime = date.atTime(1,50,9);
System.out.println(datetime);

}
}
Test it Now
Output:
2017-01-13T01:50:09
Java LocalTime class
Java LocalTime class is an immutable class that represents time with a default format of
hour-minute-second. It inherits Object class and implements the Comparable interface.
Java LocalTime class declaration
Let's see the declaration of java.time.LocalTime class.
public final class LocalTime extends Object
implements Temporal, TemporalAdjuster, Comparable<LocalTime>, Serializable

Method Description

LocalDateTime It is used to combine this time with a date to create a LocalDateTime.
atDate(LocalDate date) It is used to compare this time to another time.

int compareTo(LocalTime
other)

String It is used to format this time using the specified formatter.
format(DateTimeFormatter
formatter) It is used to get the value of the specified field from this time as an int.
It is used to return a copy of this LocalTime with the specified number of hours subt
int get(TemporalField
field) It is used to return a copy of this LocalTime with the specified number of minutes su

LocalTime It is used to obtain the current time from the system clock in the default time-zone.
minusHours(long It is used to obtain an instance of LocalTime from an hour, minute and second.
hoursToSubtract)
It is used to return a copy of this LocalTime with the specified number of hours adde
LocalTime It is used to return a copy of this LocalTime with the specified number of minutes ad
minusMinutes(long
minutesToSubtract)

static LocalTime now()

static LocalTime of(int
hour, int minute, int
second)

LocalTime plusHours(long
hoursToAdd)

LocalTime
plusMinutes(long
minutesToAdd)

Java LocalTime Example: now()
import java.time.LocalTime;
public class LocalTimeExample1 {

public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println(time);

}
}

Output:
15:19:47.459
Java LocalTime Example: of()
import java.time.LocalTime;
public class LocalTimeExample2 {

public static void main(String[] args) {
LocalTime time = LocalTime.of(10,43,12);
System.out.println(time);

}
}
Test it Now
Output:
10:43:12
Java LocalTime Example: minusHours() and minusMinutes()
import java.time.LocalTime;
public class LocalTimeExample3 {

public static void main(String[] args) {
LocalTime time1 = LocalTime.of(10,43,12);
System.out.println(time1);
LocalTime time2=time1.minusHours(2);
LocalTime time3=time2.minusMinutes(34);
System.out.println(time3);

}
}
Test it Now
Output:
10:43:12
08:09:12

Java LocalTime Example: plusHours() and plusMinutes()
import java.time.LocalTime;
public class LocalTimeExample4 {

public static void main(String[] args) {
LocalTime time1 = LocalTime.of(10,43,12);
System.out.println(time1);
LocalTime time2=time1.plusHours(4);
LocalTime time3=time2.plusMinutes(18);
System.out.println(time3);

}
}
Test it Now
Output:
10:43:12
15:01:12
Java LocalTime Example
import java.time.*;
import java.time.temporal.ChronoUnit;
public class LocalTimeExample5 {

public static void main(String... args) {
ZoneId zone1 = ZoneId.of("Asia/Kolkata");
ZoneId zone2 = ZoneId.of("Asia/Tokyo");
LocalTime time1 = LocalTime.now(zone1);
System.out.println("India Time Zone: "+time1);
LocalTime time2 = LocalTime.now(zone2);
System.out.println("Japan Time Zone: "+time2);
long hours = ChronoUnit.HOURS.between(time1, time2);
System.out.println("Hours between two Time Zone: "+hours);

long minutes = ChronoUnit.MINUTES.between(time1, time2);
System.out.println("Minutes between two time zone: "+minutes);
}
}
Test it Now
Output:
India Time Zone: 14:56:43.087
Japan Time Zone: 18:26:43.103
Hours between two Time Zone: 3
Minutes between two time zone: 210
Java LocalDateTime class
Java LocalDateTime class is an immutable date-time object that represents a date-time, with
the default format as yyyy-MM-dd-HH-mm-ss.zzz. It inherits object class and implements the
ChronoLocalDateTime interface.
Java LocalDateTime class declaration
Let's see the declaration of java.time.LocalDateTime class.
public final class LocalDateTime extends Object
implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable

Method Description

String format(DateTimeFormatter It is used to format this date-time using the specified formatter.
formatter)
It is used to get the value of the specified field from this date-time as an in
int get(TemporalField field) It is used to return a copy of this LocalDateTime with the specified number

LocalDateTime minusDays(long It is used to obtain the current date-time from the system clock in the defa
days) It is used to obtain an instance of LocalDateTime from a date and time.

static LocalDateTime now() It is used to return a copy of this LocalDateTime with the specified number

static LocalDateTime of(LocalDate
date, LocalTime time)

LocalDateTime plusDays(long

days) It is used to check if this date-time is equal to another date-time.
boolean equals(Object obj)

Java LocalDateTime Example
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeExample1 {

public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("Before Formatting: " + now);
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formatDateTime = now.format(format);
System.out.println("After Formatting: " + formatDateTime);

}
}
Test it Now
Output:
Before Formatting: 2017-01-13T17:09:42.411
After Formatting: 13-01-2017 17:09:42
Java LocalDateTime Example: now()
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeExample2 {

public static void main(String[] args) {
LocalDateTime datetime1 = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formatDateTime = datetime1.format(format);
System.out.println(formatDateTime);

}
}
Test it Now
Output:
14-01-2017 11:42:32
Java LocalDateTime Example: get()
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
public class LocalDateTimeExample3 {

public static void main(String[] args) {
LocalDateTime a = LocalDateTime.of(2017, 2, 13, 15, 56);
System.out.println(a.get(ChronoField.DAY_OF_WEEK));
System.out.println(a.get(ChronoField.DAY_OF_YEAR));
System.out.println(a.get(ChronoField.DAY_OF_MONTH));
System.out.println(a.get(ChronoField.HOUR_OF_DAY));
System.out.println(a.get(ChronoField.MINUTE_OF_DAY));

}
}
Test it Now
Output:
1
44
13
15
956
Java LocalDateTime Example: minusDays()
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeExample4 {
public static void main(String[] args) {

LocalDateTime datetime1 = LocalDateTime.of(2017, 1, 14, 10, 34);
LocalDateTime datetime2 = datetime1.minusDays(100);
System.out.println("Before Formatting: " + datetime2);
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
String formatDateTime = datetime2.format(format);
System.out.println("After Formatting: " + formatDateTime );
}
}
Test it Now
Output:

Before Formatting: 2016-10-06T10:34
After Formatting: 06-10-2016 10:34
Java LocalDateTime Example: plusDays()
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeExample5 {
public static void main(String[] args) {

LocalDateTime datetime1 = LocalDateTime.of(2017, 1, 14, 10, 34);
LocalDateTime datetime2 = datetime1.plusDays(120);
System.out.println("Before Formatting: " + datetime2);
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
String formatDateTime = datetime2.format(format);
System.out.println("After Formatting: " + formatDateTime );
}
}

Test it Now
Output:
Before Formatting: 2017-05-14T10:34
After Formatting: 14-05-2017 10:34
15.2 Java date Classical
java.util.Date

The java.util.Date class represents date and time in java. It provides constructors and
methods to deal with date and time in java.
The java.util.Date class implements Serializable, Cloneable and Comparable<Date>
interface. It is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.
After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated. Here, we are not giving list of any deprecated constructor and method.

java.util.Date Constructors

No. Constructor Description

1) Date() Creates a date object representing current date and time.

2) Date(long Creates a date object for the given milliseconds since January 1, 1970, 00:00:0

milliseconds)

java.util.Date Methods Description
No. Method

1) boolean after(Date date) tests if current date is after the given date.
2) boolean before(Date date) tests if current date is before the given date.
3) Object clone() returns the clone object of current date.
4) int compareTo(Date date) compares current date with given date.

5) boolean equals(Date date) compares current date with given date for equality.
6) static Date from(Instant returns an instance of Date object from Instant date.

instant) returns the time represented by this date object.
7) long getTime() returns the hash code value for this date object.
8) int hashCode() changes the current date and time to given time.
9) void setTime(long time) converts current date into Instant object.
10) Instant toInstant() converts this date into Instant object.
11) String toString()

1st way:
java.util.Date date=new java.util.Date();
System.out.println(date);
Test it Now
Output:
Wed Mar 27 08:22:02 IST 2015
2nd way:
long millis=System.currentTimeMillis();
java.util.Date date=new java.util.Date(millis);
System.out.println(date);
Test it Now
Output:
Wed Mar 27 08:22:02 IST 2015
java.sql.Date
The java.sql.Date class represents only date in java. It inherits java.util.Date class.

The java.sql.Date instance is widely used in JDBC because it represents the date that can
be stored in database.

Some constructors and methods of java.sql.Date class has been deprecated. Here, we are
not giving list of any deprecated constructor and method.

java.sql.Date Constructor

No. Constructor Description

1) Date(long Creates a sql date object for the given milliseconds since January 1, 1970, 00:00
milliseconds)

java.sql.Date Methods

No. Method Description

1) void setTime(long time) changes the current sql date to given time.

2) Instant toInstant() converts current sql date into Instant object.

3) LocalDate toLocalDate() converts current sql date into LocalDate object.

4) String toString() converts this sql date object to a string.

5) static Date valueOf(LocalDate returns sql date object for the given LocalDate.

date)

6) static Date valueOf(String date) returns sql date object for the given String.

java.sql.Date Example: get current date
Let's see the example to print date in java using java.sql.Date class.
public class SQLDateExample {

public static void main(String[] args) {

long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
System.out.println(date);
}
}
Test it Now
Output:
2015-03-30
Java String to java.sql.Date Example
Let's see the example to convert string into java.sql.Date using valueOf() method.
import java.sql.Date;
public class StringToSQLDateExample {
public static void main(String[] args) {
String str="2015-03-31";
Date date=Date.valueOf(str);//converting string into sql date
System.out.println(date);
}
}
Test it Now
Output:
2015-03-31
15.3 Date format
There are two classes for formatting date in java: DateFormat and SimpleDateFormat.

The java.text.DateFormat class provides various methods to format and parse date and time
in java in language independent manner. The DateFormat class is an abstract class.
java.text.Format is the parent class and java.text.SimpleDateFormat is the subclass of
java.text.DateFormat class.
In java, converting date into string is called formatting and vice-versa parsing. In other
words, formatting means date to string and parsing means string to date.


Click to View FlipBook Version