by Jesmin Akther | Jun 17, 2021 | JAVA
Java Keywords
Java keywords are also known as reserved words. They are particular words that acts as a key to a code. These are predefined words by Java so it cannot be used as a variable or object name.
Let’s know the list of Java Keywords. A list of Java keywords or reserved words are given below:
abstract:
This keyword is used to declare abstract class. Abstract class can provide the implementation of interface. It can have abstract and non-abstract methods.
boolean:
The Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False values only.
break:
Java break keyword is used to break loop or switch statement. It breaks the current flow of the program at specified condition.
byte:
The byte keyword is used to declare a variable that can hold an 8-bit data values.
case:
The java case keyword is used to with the switch statements to mark blocks of text.
catch:
Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the try block only.
char:
The char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters
class:
In Java, the class keyword is used to declare a class.
continue:
In Java, the continue keyword is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
default:
The default keyword in java is used to specify the default block of code in a switch statement.
do:
The Java do keyword is used in control statement to declare a loop. It can iterate a part of the program several times.
double:
The Java double keyword is used to declare a variable that can hold a 64-bit floating-point numbers.
else:
The default Java else keyword is used to indicate the alternative branches in an if statement.
enum:
The Java enum keyword is used to define a fixed set of constants. Enum constructors are always private or default.
extends:
The default Java extends keyword is used to indicate that a class is derived from another class or interface.
final: The default Java final keyword is used to indicate that a variable holds a constant value. It is applied with a variable. It is used to restrict the user.
finally: The default Java finally keyword indicates a block of code in a try-catch structure. This block is always executed whether exception is handled or not.
float: The Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions repeatedly when some conditions become true. If the number of iteration is fixed, it is recommended to use for loop.
if: The default Java if keyword tests the condition. It executes the if block if condition is true.
implements: The default Java implements keyword is used to implement an interface.
import: The Java import keyword makes classes and interfaces available and accessible to the current source code.
instanceof: The default Java instanceof keyword is used to test whether the object is an instance of the specified class or implements an interface.
int: The default Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
interface:
The default Java interface keyword is used to declare an interface. It can have only abstract methods.
long: The default Java long keyword is used to declare a variable that can hold a 64-bit integer.
native: The default Java native keyword is used to specify that a method is implemented in native code using JNI (Java Native Interface).
new: The default Java new keyword is used to create new objects.
null:
The default Java null keyword is used to indicate that a reference does not refer to anything. It removes the garbage value.
package:
The default Java package keyword is used to declare a Java package that includes the classes.
private:
The default Java private keyword is an access modifier. It is used to indicate that a method or variable may be accessed only in the class in which it is declared.
protected:
The default Java protected keyword is an access modifier. It can be accessible within package and outside the package but through inheritance only. It can’t be applied on the class.
public:
The default Java public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It has the widest scope among all other modifiers.
return:
The default Java return keyword is used to return from a method when its execution is complete.
short:
The default Java short keyword is used to declare a variable that can hold a 16-bit integer.
static:
The default Java static keyword is used to indicate that a variable or method is a class method. The static keyword in Java is used for memory management mainly.
strictfp:
The default Java strictfp is used to restrict the floating-point calculations to ensure portability.
super:
The default Java super keyword is a reference variable that is used to refer parent class object. It can be used to invoke immediate parent class method.
switch:
The Java switch keyword contains a switch statement that executes code based on test value. The switch statement tests the equality of a variable against multiple values.
synchronized:
Java synchronized keyword is used to specify the critical sections or methods in multithreaded code.
this:
In Java this keyword can be used to refer the current object in a method or constructor.
throw:
The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to throw custom exception. It is followed by an instance.
throws:
The Java throws keyword is used to declare an exception. Checked exception can be propagated with throws.
transient:
In Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.
try:
In Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be followed by either catch or finally block.
void:
In Java void keyword is used to specify that a method does not have a return value.
volatile:
In Java volatile keyword is used to indicate that a variable may change asynchronously.
while:
In Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop.
Here is a few example with keywords:
public abstract class AbstractClass {
// This method is abstract ; it does not have a body
public abstract void abstractMethod();
// it is implemented in the abstract class and gives a default behavior.
public void concreteMethod() {
System.out.println("Already coded.");
}
}
The above code abstract keyword use here first method has no body as it is a abstract.
AbstractClass myObject = new AbstractClass() {
public void abstractMethod() {
System.out.println("Implementation.");
}
};
Above example code uses keyword new and the code has implemented method which has body.
by Jesmin Akther | Jun 17, 2021 | JAVA
File handling create a File
To create a file in Java, the createNewFile() method is used. This method returns a boolean value true if the file was successfully created, and false if the file already exists. The method is enclosed in a try…catch block. This is necessary because it throws an IOException if an error occurs :
Example
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
File created: filename.txt
To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the “\” character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt
Example
File myObj = new File(“C:\\Users\\MyName\\filename.txt”);
Write To a File
In the following example, FileWriter class together with its write() method to write some text to the file created in the example above. Note that when done writing to the file, should close it with the close() method:
Example
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
System.out.println("An error occurred.");} catch (IOException e) {
e.printStackTrace();
}
}
}
The output will be:
Successfully wrote to the file.
Read a File
In the following example, the Scanner class to read the contents of the text file created in the previous chapter:
Example
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
Files in Java might be tricky, but it is fun enough!
Get File Information
To get more information about a file, use any of the File methods:
Example
import java.io.File; // Import the File class
public class GetFileInfo {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}
The output will be:
File name: filename.txt
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0
Delete a File
To delete a file in Java, use the delete() method:
Example
import java.io.File; // Import the File class
public class DeleteFile {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
The output will be:
Deleted the file: filename.txt
Delete a Folder
You can also delete a folder. However, it must be empty:
Example
import java.io.File;
public class DeleteFolder {
public static void main(String[] args) {
File myObj = new File("C:\\Users\\MyName\\Test");
if (myObj.delete()) {
System.out.println("Deleted the folder: " + myObj.getName());
} else {
System.out.println("Failed to delete the folder.");
}
}
}
The output will be:
Deleted the folder: Test
by Jesmin Akther | Jun 17, 2021 | JAVA
Java Lambda Expressions
Lambda Expressions in java were added in Java 8. When you implemented an anonymous simple class, such as an interface which contains only one method, then the syntax of anonymous classes may seem vogue and unclear. In these scenario, trying to pass an argument to another method, In this time when someone clicks a button Lambda expressions enable to do the action, to act as functionality as method argument, or code as data.
In short saying, A lambda expression is a short block of code which takes in parameters and returns a value. This expressions are alike to methods, though they do not need a name and they can be implemented right in the body of a method.
Syntax
The simplest lambda expression contains a single parameter and an expression:
parameter -> expression
To use more than one parameter, wrap them in parentheses:
(parameter1, parameter2) -> expression
Expressions are limited to use. They have to immediately return a value, and they cannot contain variables, assignments or statements for example if or for. To do more complex operations, a code block can be used with curly braces. If the lambda expression needs to return a value, then the code block should have a return statement.
(parameter1, parameter2) -> { code block }
Using Lambda Expressions
Lambda expressions are usually passed as parameters to a function:
Example
Use a lamba expression in the ArrayList’s forEach() method to print every item in the list:
import java.util.ArrayList;
public class Example{
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}
OUTPUT:
9
8
1
Lambda expressions can be stored in variables(if variable type is an interface) which has only one method. The lambda expression should have the similar number of parameters and the same return type as that method. Java has many of these kinds of interfaces built in, such as the Consumer interface (found in the java.util package) used by lists.
Example
Use Java’s Consumer interface to store a lambda expression in a variable:
import java.util.ArrayList;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
Consumer<Integer> method = (n) -> { System.out.println(n); };
numbers.forEach( method );
}
}
OUTPUT:
9
8
1
To use a lambda expression in a method, the method should have a parameter with a single-method interface as its type. Calling the interface’s method will run the lambda expression:
Example
Create a method which takes a lambda expression as a parameter:
interface StringFunction {
String run(String str);
}
public class Example{
public static void main(String[] args) {
StringFunction exclaim = (s) -> s + "!";
StringFunction ask = (s) -> s + "?";
printFormatted("Hello", exclaim);
printFormatted("Hello", ask);
}
public static void printFormatted(String str, StringFunction format) {
String result = format.run(str);
System.out.println(result);
}
}
Lambdas expressions and the Single Method Interface
As Functional programming is frequently used to implement event listeners. Event listeners in Java are often defined as Java interfaces with a single method. Here is a single method interface example:
public interface StateChangeListener {
public void onStateChange(State oldState, State newState);
}
This Java interface defines a single method which is called when the state changes or whatever is being observed.
In Java 7 you would have to implement this interface due to listen for state changes. Suppose, a class called StateOwner which can register state event listeners. Here is an example:
public class StateOwner {
public void addStateListener(StateChangeListener listener) { ... }
}
In Java 7 could add an event listener using an anonymous interface implementation, like this:
StateOwner stateOwner = new StateOwner();
stateOwner.addStateListener(new StateChangeListener() {
public void onStateChange(State oldState, State newState) {
// do something with old and new state.
}
});
First a StateOwner instance is created. Next an anonymous implementation of the StateChangeListener interface is added as listener on the StateOwner instance.
In Java 8, can add an event listener using a Java lambda expression, like this:
StateOwner stateOwner = new StateOwner();
stateOwner.addStateListener(
(oldState, newState) -> System.out.println("State changed")
);
Here the lambda expressions is this part:(oldState, newState) -> System.out.println(“State changed”)
The lambda expression is matched against the parameter type of the addStateListener() method parameter. If the matches the parameter type (in this case the StateChangeListener interface) , then the lambda expression is turned into a function that implements the same interface as that parameter.
by Jesmin Akther | Jun 16, 2021 | JAVA
Java Threads
Threads in javapermits a program to operate more creatively at the same time multiple things. It can be used to perform complex tasks in the background without disturbing the main program.
How to create a thread: There are two ways to create a thread,
- Extend Thread class
- Implement Runnable interface.
Thread can be created by extending the Thread class and overriding its run () method:
Thread class: Thread class deliver constructors and methods to extends Object class and implements Runnable interface.
Frequently used Constructors of Thread class:
- Thread()
- Thread(String name)
- Thread(Runnable r)
- Thread(Runnable r, String name)
Frequently used methods of Thread class:
- public void run()This method 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(): This method is the priority of the thread.
- public int setPriority(int priority): changes the priority of the thread.
- public String getName(): This method is the name of the thread.
- public void setName(String name): changes the name of the thread.
- public Thread currentThread(): This method is the reference of currently executing thread.
- public int getId(): This method is the id of the thread.
- public Thread.State getState(): This method is the state of the thread.
- public boolean isAlive(): tests if the thread is alive.
- public void yield():It causes the currently executing thread object to temporarily pause and allow other threads to execute.
- public void suspend(): This method used to suspend the thread(depricated).
- public void resume(): This method used to resume the suspended thread(depricated).
- public void stop(): This method used to stop the thread(depricated).
- public boolean isDaemon():It tests if the thread is a daemon thread.
- public void setDaemon(boolean b):It marks the thread as daemon or user thread.
- public void interrupt(): This interrupts the thread.
- public boolean isInterrupted():It tests if the thread has been interrupted.
- public static boolean interrupted(): It tests if the current thread has been interrupted.
Syntax for Extend
public class ExMain extends Thread {
public void run() {
System.out.println("This code is running in a thread");
}
}
Another way: To implement the Runnable interface. Syntax for Implement:
public class ExMain implements Runnable {
public void run() {
System.out.println("This code is running in a thread");
}
}
Running Threads
To extends a Thread class, thread can be run creating an instance or object of the class and call its start() method:
Extends Example
public class ExMain extends Thread {
public static void main(String[] args) {
ExMain thread = new ExMain ();
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
This code is outside of the thread
This code is running in a thread.
If the class implements the Runnable interface, the thread can be run by passing an instance of the class to a Thread object’s constructor and then calling the thread’s start() method:
Implement Example
public class Main implements Runnable {
public static void main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
OUTPUT
This code is outside of the thread
This code is running in a thread.
F&Q (Frequently ask questions)
What is Extending and implementing?
The major difference is that when a class extends the Thread class cannot extend any other class, but by implementing the Runnable interface, it is possible to extend from another class as well, like: class ExClass extends NextClass implements Runnable.
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()This method 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 that is 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 multipleThread extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
multipleThread t1=new multipleThread ();
t1.start();
}
}
Output:
thread is running…
2) Java Thread Example by implementing Runnable interface
class multiThread3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
multiThread3 m3=new multiThread3();
Thread t1 =new Thread(m3);
t1.start();
}
}
Output:thread is running…
If not extending the Thread class, object would not be preserved as a thread object. So need to explicitely create Thread class object. Passing the object of class that implements Runnable so that class run() method may execute.
Thread Scheduler in Java:
This is the part of the JVM Java virtual Machine that decides which thread should run. There is no promise that which runnable thread will be chosen to run by the thread scheduler. Only one thread at a time can run in a single process. The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.
Difference between preemptive scheduling and time slicing
Preemptive scheduling allows the highest priority task executes until it pass in the waiting or dead states or a higher priority task comes into existence. Time slicing is a task executes for a predefined slice of time and then returns the pool of ready tasks. The scheduler then governs which task should execute next, based on priority and other factors.
Sleep method:
In java the sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Syntax of sleep() method: 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 testSleep1 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[]){
testSleep1 t1=new testSleep1 ();
testSleep1 t2=new testSleep1 ();
t1.start();
t2.start();
}
}
Output:
1
1
2
2
3
3
4
4
As at a time only one thread is executed. If the sleep method in a thread for the specified time, the thread scheduler choices another thread and so on.
Does start a thread twice? This is definitely no. After starting a thread, it can never be started again. If 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 runThreadTwice extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
runThreadTwice t1=new runThreadTwice ();
t1.start();
t1.start();
}
}
OUTPUT:
running
Exception in thread “main” java.lang.IllegalThreadStateException
Does run() method call directly instead start() 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 runCall extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
runCall t1=new runCall ();
t1.run();//fine, but does not start a separate call stack
}
}
Output:running…
MainThreadStack Problem if direct call run() method
class runCall1 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[]){
runCall1 t1=new runCall1 ();
runCall1 t2=new runCall1 ();
t1.run();
t2.run();
}
}
Output:
1
2
3
4
5
1
2
3
4
5
In the above program, there is no context-switching because here t1 and t2 will be treated as normal object not thread object.
The join() method:
The join() method waits for a thread to die. On the other hand, it origins 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 runJoin1 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[]){
runJoin1 t1=new runJoin1 ();
runJoin1 t2=new runJoin1 ();
runJoin1 t3=new runJoin1 ();
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
As in the above example, when t1 completes its task then t2 and t3 starts executing.
Example of join(long miliseconds) method
class runJoin2 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[]){
runJoin2 t1=new runJoin2 ();
runJoin2 t2=new runJoin2 ();
runJoin2 t3=new runJoin2 ();
t1.start();
try{
t1.join(1500);
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
Output:
1
2
3
1
4
1
2
5
2
3
3
4
4
5
5
In the example, when t1 is completes its task for 1500 miliseconds that is 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 runJoin3 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
runJoin3 t1=new runJoin3();
runJoin3 t2=new runJoin3();
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("Md Harun");
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 changling name of t1:Md Harun
running…
The currentThread() method: The method is a reference to the presently executing thread object.
Syntax:
public static Thread presentThread()
Example of presentThread () method
class runJoin4 extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[]){
runJoin4 t1=new runJoin4 ();
runJoin4 t2=new runJoin4 ();
t1.start();
t2.start();
}
}
Output:
Thread-0
Thread-1
Naming a Thread:
The Thread class delivers methods to modification and get the name of the thread. Each thread has a name that is thread-0, thread-1 and more on. By change the name of the thread by using setName() method. The syntax of setName() and getName() methods are given below:
public String getName(): This method used to return the name of a thread.
public void setName(String name) : This method used to change the name of a thread.
Example of naming a thread
class RunMultiName1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
RunMultiName1 t1=new RunMultiName1 ();
RunMultiName1 t2=new RunMultiName1 ();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
t1.setName("Md Harun");
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: Md Harun
running…
Current Thread: The currentThread() method is a reference of currently executing thread.Example
public static Thread presentThread()
Example of presentThread() method
class RunMultiName2 extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
public static void main(String args[]){
RunMultiName2 t1=new RunMultiName2 ();
RunMultiName2 t2=new RunMultiName2 ();
t1.start();
t2.start();
}
}
Output:
Thread-0
Thread-1
Priority of a Thread Or Thread Priority:
Each thread have a priority and are represented by a number between 1 and 10. In most cases, thread schedular are schedules the threads according to their priority known as preemptive scheduling. Though it is not guaranteed cause 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 is NORM_PRIORITY. The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Example of priority of a Thread:
class RunMultiPriority1 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[]){
RunMultiPriority1 m1=new RunMultiPriority1();
RunMultiPriority1 m2=new RunMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
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 that is when all the user threads dies, JVM terminates this thread repeatedly.There are many java daemon threads running automatically for example gc, finalizer etc.
Key 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 only purpose of the daemon thread is 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.
- public void setDaemon(boolean status) method is used to mark the current thread as daemon thread or user thread.
- public boolean isDaemon() method is used to check that current is daemon.
Simple example of Daemon thread in java
public class RunDaemonThread extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){ //check daemon thread
System.out.println("daemon thread work");
}
else
{
System.out.println("user thread work");
}
}
public static void main(String[] args){
RunDaemonThread t1=new RunDaemonThread ();//creating thread
RunDaemonThread t2=new RunDaemonThread ();
RunDaemonThread t3=new RunDaemonThread ();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
}
}
Output
daemon thread work
user thread work
user thread work
If want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.
class RunDaemonThread2 extends Thread{
public void run(){
System.out.println("Name: "+Thread.currentThread().getName());
System.out.println("Daemon: "+Thread.currentThread().isDaemon());
}
public static void main(String[] args){
RunDaemonThread2 t1=new RunDaemonThread2 ();
RunDaemonThread2 t2=new RunDaemonThread2 ();
t1.start();
t1.setDaemon(true);//will throw exception here
t2.start();
}
}
Output:
exception in thread main: java.lang.IllegalThreadStateException
Java Thread Pool:
It is represents a group of worker threads that are waiting for the job and reprocess many times.In thread pool group of static size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.
Advantage of Java Thread Pool
- Better performance and saves time because there is no need to create new thread.
- Real time usage
- It is recycled in Servlet and JSP where container creates a thread pool to process the request.
Example of Java Thread Pool
Let’s see a simple example of java thread pool using ExecutorService and Executors.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class workersThread implements Runnable {
private String message;
public workersThread (String s){
this.message=s;
}
public void run() {
System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
processmessage();//call processmessage method that sleeps the thread for 2 seconds
System.out.println(Thread.currentThread().getName()+" (End)");//prints thread name
}
private void processmessage() {
try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
AnotherExample.java
public class RunThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of 5 threads
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);//calling execute method of ExecutorService
}
executor.shutdown();
while (!executor.isTerminated()) { }
System.out.println("Finished all threads");
}
}
Output:
pool-1-thread-1 (Start) message = 0
pool-1-thread-2 (Start) message = 1
pool-1-thread-3 (Start) message = 2
pool-1-thread-5 (Start) message = 4
pool-1-thread-4 (Start) message = 3
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 5
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 6
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = 7
pool-1-thread-4 (End)
pool-1-thread-4 (Start) message = 8
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads
ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such way, we can suspend, resume or interrupt group of threads by a single method call. Now suspend(), resume() and stop() methods are deprecated. Java thread group is implemented by java.lang.ThreadGroup class. A ThreadGroup represents a set of threads. A thread group can also include the other thread group. The thread group creates a tree in which every thread group except the initial thread group has a parent. A thread is allowed to access information about its own thread group, but it cannot access the information about its thread group’s parent thread group or any other thread groups.
Constructors of ThreadGroup class
There are only two constructors of ThreadGroup class.
- ThreadGroup(String name) creates a thread group with given name.
- ThreadGroup(ThreadGroup parent, String name) creates a thread group with given parent group and name.
How to perform single task by multiple threads?
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 RunMultitask1 extends Thread{
public void run(){
System.out.println("task one");
}
public static void main(String args[]){
RunMultitask1 t1=new RunMultitask1 ();
RunMultitask1 t2=new RunMultitask1 ();
RunMultitask1 t3=new RunMultitask1 ();
t1.start();
t2.start();
t3.start();
}
}
Output:
task one
task one
task one
Program of performing single task by multiple threads
class RunMultitask2 implements Runnable{
public void run(){
System.out.println("task one");
}
public static void main(String args[]){
Thread t1 =new Thread(new RunMultitask2());//passing annonymous object of TestMultitasking2 class
Thread t2 =new Thread(new RunMultitask2());
t1.start();
t2.start();
}
}
Output:
task one
task one
Here in the above example, each thread run in a separate callstack.
MultipleThreadsStack
How to perform multiple tasks by multiple threads or multitasking in multithreading?
If perform multiple tasks by multiple threads,have multiple run() methods. For example:
Program of performing two tasks by two threads
class run2Task2Thread extends Thread{
public void run(){
System.out.println("task one");
}
}
class run2Task2Thread extends Thread{
public void run(){
System.out.println("task two");
}
}
class RunMultitask3{
public static void main(String args[]){
Simple1 t1=new Simple1();
Simple2 t2=new Simple2();
t1.start();
t2.start();
}
}
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 RunMultitask4{
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();
}
}
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 RunMultitask5{
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();
}
}
Output:
task one
task two
by Jesmin Akther | Jun 14, 2021 | JAVA
Java Exceptions
An exception or exceptional event is a problem. This is getting up during the execution of a program. When an Exception happens the normal flow of the program is disrupted and the program terminates unusually. This is not recommended, consequently, these exceptions are to be handled.An exception can occur for many different reasons. where an exception occurs?
- A user has entered an invalid data.
- A file that needs to be opened cannot be found.
- A network connection has been lost in the middle of communications or the JVM has run out of memory.
- Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.
- Based on these, we have three categories of Exceptions. You need to understand them to know how exception handling works in Java.
Checked exceptions:
A checked exception is checked or notified by the compiler at compilation-time. These are also called as compile time exceptions. These exceptions cannot simply be ignored. The programmer should take care of (handle) these exceptions. For instance, if use FileReader class in your program to read data from a file, if the file specified in its constructor doesn’t exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception.
Example:
import java.io.File;
import java.io.FileReader;
public class Example {
public static void main(String args[]) {
File file = new File("C://file.txt");
FileReader fr = new FileReader(file);
}
}
Output
C:\>javac Example.java
Example.java:8: error: unreported exception Example; must be caught or declared to be thrown
FileReader fr = new FileReader(file); ^
1 error
Note: Since the methods read() and close() of FileReader class throws IOException, detect the compiler informs to handle IOException, along with FileNotFoundException.
Unchecked exceptions:
An unchecked exception is an exception occurs at the time of execution. These are also called as Runtime Exceptions comprise programming bugs example as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. For sample, if declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
Example
public class Example
{
public static void main(String args[]) {
int number[] = {1, 2, 3, 4};
System.out.println(number[5]);
}
}
Output
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 5
at Example.main(Unchecked_Demo.java:8)
Errors:
These are not exceptions at all though problems that stand up beyond the control of the user or the programmer. Errors are typically ignored in code because programmer can rarely do anything about an error. For case, if a stack overflow occurs, an error will ascend. They are also ignored at the time of compilation.
Exception Hierarchy
All kind of exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors are irregular conditions that happen in case of severe failures, these are not handled by the Java programs. Errors are generated to indicate errors generated by the runtime environment. Example: JVM is out of memory. Normally, programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class. A list of most common checked and unchecked Java’s Built-in Exceptions. Exceptions Methods:
Following is the list of important methods available in the Throwable class.
- getMessage(): Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
- Throwable getCause():Returns the cause of the exception as represented by a Throwable object.
- toString():Returns the name of the class concatenated with the result of getMessage().
- printStackTrace():Prints the result of toString() along with the stack trace to System.err, the error output stream.
- StackTraceElement [] getStackTrace(): Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
- Throwable fillInStackTrace(): Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.
Catching Exceptions
A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
The code which is likely to to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
Example
// File Name : ExcepTest.java
import java.io.*;
public class ExcepExample
{
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Multiple Catch Blocks
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
The previous statements demonstrate three catch blocks, though can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.
Example
Here is code segment showing how to use multiple try/catch statements.
try {
file = new FileInputStream(fileName);
x = (byte) file.read();
} catch (IOException i) {
i.printStackTrace();
return -1;
} catch (FileNotFoundException f) // Not valid! {
f.printStackTrace();
return -1;
}
Catching Multiple Type of Exceptions
Since Java 7, you can handle more than one exception using a single catch block, this feature simplifies the code.
catch (IOException|FileNotFoundException example) {
logger.log(example);
throw example;
The Throws/Throw Keywords
If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature. To throw an exception, either a newly instantiated one or an exception that just caught, by using the throw keyword. There is some key to understand the difference between throws and throw keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly.
The following method declares that it throws a RemoteException :
Example
import java.io.*;
public class classExample {
public void deposit(double amount) throws RemoteException {
// Method implementation
throw new RemoteException();
}
// Rest of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For illustration, the following method declares that it throws a RemoteException and an InsufficientFundsException:
Example
import java.io.*;
public class classExample {
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException {
// Method implementation
}
// Rest of class definition
}
The Finally Block
The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.By means of a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of the catch blocks and has the following syntax:
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Example
public class classExample{
public static void main(String args[]) {
int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
This will produce the following result −
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Note : A catch clause cannot exist without a try statement.
- It is not obligatory to have finally clauses whenever a try/catch block is present.
- The try block cannot be present without either catch clause or finally clause.
- Any code cannot be present in between the try, catch, finally blocks.
try-with-resources
To use any resources alike streams, connections, etc. need to close them explicitly using finally block. In the following program, reading data from a file using FileReader and closing it using finally block.
Example
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadDataExample {
public static void main(String args[]) {
FileReader fr = null;
try {
File file = new File("file.txt");
fr = new FileReader(file); char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); // prints the characters one by one
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Try with resources mentioned as automatic resource management, is a new exception handling mechanism was introduced in Java 7. It is an automatically closes the resources used within the try catch block. To use this statement need to declare the required resources within the parenthesis, and the created resource will be closed automatically at the end of the block. Following is the syntax of Try with resources statement.
Syntax
try(FileReader fr = new FileReader("file path")) {
// use the resource
} catch () {
// body of catch
}
}
Following is the program that reads the data in a file using Try with resources statement.
Example
import java.io.FileReader;
import java.io.IOException;
public class TryExample {
public static void main(String args[]) {
try(FileReader fr = new FileReader("E://file.txt")) {
char [] a = new char[50];
fr.read(a); // reads the contentto the array
for(char c : a)
System.out.print(c); // prints the characters one by one
} catch (IOException e) {
e.printStackTrace();
}
}
}
Following points are to be kept in mind while working with try with resources statement. In order to use a class with try statement it should implement AutoCloseable interface and the close() method of it gets invoked automatically at runtime.It allows or can declare more than one class in try-with-resources statement.
While declare multiple classes in the try block of try with resources statement these classes are closed in reverse order. Except the declaration of resources within the parenthesis everything is the same as normal try/catch block of a try block. The resource declared in try gets instantiated just before the start of the try-block. The resource declared at the try block is implicitly declared as final.
User-defined Exceptions
To create your own exceptions in Java. All exceptions must be a child of Throwable. To write a checked exception that is automatically enforced by the Handle or Declare Rule, need to extend the Exception class. If want to write a runtime exception, need to extend the RuntimeException class.
define own Exception class as below :
class MyException extends Exception {
}
In order to extend the predefined Exception class to create your own Exception. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.
Example
// File Name ExceptionExample.java
import java.io.*;
public class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
}
To demonstrate using own user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException.
// File Name CheckAccount.java
import java.io.*;
public class CheckAccount {
private double balance;
private int number;
public CheckAccount (int number) {
this.number = number;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) throws InsufficientFundsException {
if(amount <= balance) {
balance -= amount;
}else {
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance() {
return balance;
}
public int getNumber() {
return number;
}
}
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckAccount.
// File Name BankDemo.java
public class BankExample {
public static void main(String [] args) {
CheckingAccount cA = new CheckingAccount(101);
System.out.println("Depositing $500...");
cA.deposit(500.00);
try {
System.out.println("\n Withdrawing $100...");
c.withdraw(100.00);
System.out.println("\n Withdrawing $600...");
c.withdraw(600.00);
} catch (InsufficientFundsException e) {
System.out.println(" Sorry !, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}
Output
Depositing $500…
Withdrawing $100…
Withdrawing $600…
Sorry!, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckAccount.java:25)
at BankExample.main(BankDemo.java:13)
Common Exceptions: In Java, it is possible to define two catergories of Exceptions and Errors. Apart them, JVM Exceptions are exceptions/errors exclusively or logically thrown by the JVM. For Instances: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException. Another exceptions namely programmatic Exceptions. These exceptions are thrown explicitly by the application or the API programmers. Examples: IllegalArgumentException, IllegalStateException.
by Jesmin Akther | Jun 13, 2021 | JAVA
Wrapper classes in Java
The wrapper class in Java offers the mechanism to translate primitive into object and object into primitive. This feature has obtained from Java J2SE 5.0, autoboxing and unboxing. Actually, these feature convert primitives into objects and objects into primitives automatically. The automatic conversion of primitive into an object is known as autoboxing and unboxing. Wrapper class is a class whose object wraps or contains primitive data types.
In more details:
When create an object to a wrapper class, it contains a field and, in this field, there can store primitive data types. In other words, wrap a primitive value into a wrapper class object.
Necessity of Wrapper Classes,
- These classes convert primitive data types into objects.
- Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).
- The classes in java.util package handles only objects and hence wrapper classes help in this scenario.
- Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types.
- An object is needed to support synchronization in multithreading.
Use of Wrapper classes in Java
As Java is an object-oriented programming language(OOP), need to deal with objects many times such as in Collections, Serialization, Synchronization, etc. To use the wrapper classes need
- Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not change the original value. But, if we convert the primitive value in an object, it will change the original value.
- Serialization: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in objects through the wrapper classes.
- Synchronization: Java synchronization works with objects in Multithreading.
- util package: The java.util package provides the utility classes to deal with objects.
- Collection Framework: Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight wrapper classes are given below:
Primitive Type |
Wrapper class |
boolean |
Boolean |
char |
Character |
byte |
Byte |
short |
Short |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
Autoboxing
The automatic alteration of primitive data type into its equivalent wrapper class is known as autoboxing, for instance, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.
Wrapper class Example: Primitive to Wrapper
//Java program to convert primitive into objects
//Autoboxing example of int to Integer
public class WrapperExample{
public static void main(String args[]){
//Converting int into Integer
int a=10;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}
}
Output:
20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of wrapper classes to convert the wrapper type into primitives. Wrapper class Example: Wrapper to Primitive
//Java program to convert primitive into objects (Autoboxing example of int to Integer)
public class WrapperExample{
public static void main(String args[])
{
//Converting int into Integer
int a=10;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}
}
Output:
3 3 3
Java Wrapper classes Example
//Java Program to convert all primitives into its corresponding wrapper objects
public class WrapperExample{
public static void main(String args[]){
byte b=100;
short s=200;
int i=300;
long l=400;
float f=500.0F;
double d=600.0D;
char c='a';
boolean b2=true;
//Autoboxing: Converting primitives into objects
Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;
//Printing objects
System.out.println("Show values");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);
//Unboxing: Converting Objects to Primitives
byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;
//Printing primitives
System.out.println(" Show primitive values");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}}
Output:
Show object values
Byte object: 100
Short object: 200
Integer object: 300
Long object: 400
Float object: 500.0
Double object: 600.0
Character object: a
Boolean object: true
Show primitive values
byte value: 100
short value: 200
int value: 300
long value: 400
float value: 500.0
double value: 600.0
char value: a
boolean value: true
Custom Wrapper class in Java
Java Wrapper classes wrap the primitive data types, that is why it is known as wrapper classes. We can also create a class which wraps a primitive data type. So, we can create a custom wrapper class in Java.
//Creating the custom wrapper class
class WrapperExample {
private int i;
WrapperExample (){}
WrapperExample (int i){
this.i=i;
}
public int getValue(){
return i;
}
public void setValue(int i){
this.i=i;
}
@Override
public String toString() {
return Integer.toString(i);
}
}
//Test the custom wrapper class
public class TestWrapperExample {
public static void main(String[] args){
WrapperExample j=new WrapperExample (10);
System.out.println(j);
}
Output:
10
by Jesmin Akther | Jun 13, 2021 | JAVA
Iterator in java
Iterator in java allows to cycle through a collection can be added or removing elements. To access a collection over an iterator, must attain one. Each of the collection classes offers an iterator () method that returns an iterator to the start of the collection. By using this iterator object can access each element in the collection at a time each element. Class ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements. In general, to use an iterator to cycle through the contents of a collection steps are:
- Obtain an iterator to the start of the collection by calling the collection’s iterator() method.
- Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
- Within the loop, obtain each element by calling next( ).
The Methods Declared by Iterator
Method with Description mention below
- hasNext( ) returns true if there are more elements. Otherwise, returns false.
- Object next( ) returns the next element. Throws NoSuchElementException if there is not a next element.
- remove( ) method is used to removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).
The Methods Declared by ListIterator
- add(Object obj): It is used to Inserts obj into the list in front of the element that will be returned by the next call to next( ).
- hasNext( ): It returns true if there is a next element. Otherwise, returns false.
- hasPrevious( ):It returns true if there is a previous element. Otherwise, returns false.
- Object next( ): It returns the next element. A NoSuchElementException is thrown if there is not a next element.
- nextIndex( ):It returns the index of the next element. If there is not a next element, returns the size of the list.
- Object previous( ): This is returns the previous element. A NoSuchElementException is thrown if there is not a previous element.
- previousIndex( ):This is returns the index of the previous element. If there is not a previous element, returns -1.
- remove( ): It is removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.
- set(Object obj): This is used to assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).
Example
import java.util.*;
public class Main {
public static void main(String args[]) {
ArrayList letters = new ArrayList();// Create an array list
// add elements to the array list
letters.add("C");
letters.add("A");
letters.add("E");
letters.add("B");
letters.add("D");
letters.add("F");
// Use iterator to display contents of letters
System.out.print("Original contents of letters: ");
Iterator itr_1 = letters.iterator();
while(itr_1.hasNext()) {
Object object = itr_1.next();
System.out.print(object + " ");
}
System.out.println();
// Modify objects being iterated
ListIterator itr_2 = letters.listIterator();
while(itr_2.hasNext()) {
Object object1 = itr_2.next();
itr_2.set(object1 + "+");
}
System.out.print("Modified contents of letters: ");
itr_1 = letters.iterator();
while(itr_1.hasNext()) {
Object object = itr_1.next();
System.out.print(object + " ");
}
System.out.println();
// Now, display the list backwards
System.out.print("Modified list backwards: ");
while(itr_2.hasPrevious()) {
Object object = itr_2.previous();
System.out.print(object + " ");
}
System.out.println();
}
}
This will produce the following result −
Output
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+
by Jesmin Akther | Jun 13, 2021 | JAVA
Java HashSet
In a HashSet, every item is unique which is known as collection. It is found in the java.util packages. This collection uses a hash table for storage. It inherits the AbstractSet class and implements Set interface. A list can contain duplicate elements whereas Set contains unique elements only.
The importantfeatures about Java HashSet class are:
- It stores the elements by using a mechanism called hashing.
- It contains unique elements only.
- It allows null value.
- It class is none synchronized.
- It doesn’t maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
- It is the best approach for search operations.
Java HashSet Declaration:
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
Constructors of Java HashSet
- HashSet():It is used to construct a default HashSet.
- HashSet(int capacity):It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.
- HashSet(int capacity, float loadFactor):It is used to initialize the capacity of the hash set to the given integer value capacity and the specified load factor.
- HashSet(Collection<? extends E> c):It is used to initialize the hash set by using the elements of the collection c.
Methods of Java HashSet class
- add(E e):It is used to add the specified element to this set if it is not already present.
- clear():It is used to remove all of the elements from the set.
- object clone(): It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
- contains(Object o):It is used to return true if this set contains the specified element.
- isEmpty():It is used to return true if this set contains no elements.
- iterator():It is used to return an iterator over the elements in this set.
- remove(Object o):It is used to remove the specified element from this set if it is present.
- int size():It is used to return the number of elements in the set.
Example
//Create a HashSet object called letters that will store strings:
import java.util.HashSet; // Import the HashSet class
HashSet<String> lettes = new HashSet<String>();
Add Items: The HashSet class has many useful methods. For example, to add items to it, use the add() method:
Example
// Import the HashSet class
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> lettes = new HashSet<String>();
lettes.add("A");
lettes.add("B");
lettes.add("C");
lettes.add("B");
lettes.add("E");
System.out.println(lettes);
}
}
OUTPUT:
A B C E
In the example above, even though Bis added twice it only appears once in the set because every item in a set has to be unique.
- Check If an Item Exists: In order to check whether an item exists in a HashSet, use the contains() method:
Example
lettes.contains(“B”);
- Remove an Item: In order to remove an item, use the remove() method:
Example
lettes.remove(“A”);
To remove all items, use the clear() method:
Example
lettes.clear();
HashSet Size
In order to find out how many items there are, use the size method:
Example
lettes.size();
HashSet Loop: Loop through the items of an HashSet with a for-each loop:
Example
for (String i : letters) {
System.out.println(i);
}
Other Types:
In order To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:
Example
Use a HashSet that stores Integer objects:
import java.util.HashSet;
public class ExMain {
public static void main(String[] args) {
// Create a HashSet object called numbers
HashSet<Integer> numbers = new HashSet<Integer>();
// Add values to the set
numbers.add(4);
numbers.add(7);
numbers.add(8);
// Show which numbers between 1 and 10 are in the set
for(int i = 1; i <= 10; i++) {
if(numbers.contains(i)) {
System.out.println(i + " was found!");
} else {
System.out.println(i + " was not found!");
}
}
}
}
OUTPUT
1 was not found!
2 was not found!
3 was not found!
4 was found!
5 was not found!
6 was not found!
7 was found!
8 was found!
9 was not found!
10 was not found!
by Jesmin Akther | Jun 12, 2021 | JAVA
LinkedList in Java
Linked List is almost similar ArrayList features. It is a part of the collection framework present in java.util package. The class is an implementation of the linear LinkedList data structure. Here the elements are not stored in adjoining locations and every element is an isolated object with a data part and address part. Here the elements are linked or connected using pointers and addresses. Each element is known as a node but these nodes are not directly used. In case the dynamicity and ease of insertions and deletions, they are preferred over the arrays.
Example: The following implementation demonstrates how to create and use a linked list. The LinkedList class is almost identical to the ArrayList:
Example 1
import java.util.LinkedList; // Import the LinkedList class
public class Main {
public static void main(String[] args) {
LinkedList<String> letters= new LinkedList<String>();
letters.add("A");
letters.add("B");
letters.add("C");
letters.add("D");
System.out.println(letters);
// Adding elements to the linked list
letters.add("AA");
letters.add("BB");
letters.addLast("CC");
letters.addFirst("DD");
letters.add(2, "EE");
System.out.println(letters);
letters.remove("B");
letters.remove(3);
letters.removeFirst();
letters.removeLast();
System.out.println(letters);
}
}
OUTPUT
A,B,C,D
[DD, AA, EE, BB, CC]
[AA]
In the example 1 java code we use Add, Remove etc. Operations on the code and these operation details given below: linkedList
- Add Elements: In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters.
- addFirst():Adds an item to the beginning of the list.
- addLast():Add an item to the end of the list.
- removeFirst():Remove an item from the beginning of the list.
- removeLast():Remove an item from the end of the list.
- getFirst():Get the item at the beginning of the list.
- getLast():Get the item at the end of the list.
- add(Object): It is used to add an element at the end of the LinkedList.
- add(int index, Object): This method is used to add an element at a definite index in the LinkedList.
- Changing Elements: After adding the elements, if we wish to change the element, it can be done by the set() method. Since a LinkedList is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element needs to be inserted at that index.
- Removing Elements: In order to remove an element from a LinkedList, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are:
- remove(Object): This method is used to remove an object from the LinkedList. If there are multiple such objects, then the first incidence of the object is removed.
- remove(int index): LinkedList is indexed, the method takes an integer value simply removes the element present at that specific index in the LinkedList. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated.
- Iterating the LinkedList: There are multiple ways to iterate through the LinkedList. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for loop.
A Java program to iterate the elements in an LinkedList given below:
import java.util.*;
public class ExMain {
public static void main(String args[])
{
LinkedList<String> letters = new LinkedList<>();
letters.add("Md");
letters.add("Harun");
letters.add(1, "is");
// Using the Get method and the for loop
for (int i = 0; i < letters.size(); i++) {
System.out.print(letters.get(i) + " ");
}
System.out.println();
// Using the for each loop
for (String str : letters)
System.out.print(str + " ");
}
}
Output:
Md is Harun
Md is Harun
How LinkedList work?
LinkedList pretend as a dynamic array and no need to specify the size while creating it, the size of the list auto increases when dynamically add and remove the items. In addition to, the elements are not stored in a constantly. So, there is no need to increase the size. Internally, the LinkedList is implemented using the doubly linked list data structure. The main difference between a normal linked list and a doubly LinkedList is that a doubly linked list contains an extra pointer, typically called the previous pointer, together with the next pointer and data which are there in the singly linked list.
LinkedList Constructors :
To create a LinkedList create an object of the LinkedList class. The LinkedList class consists of various constructors that allow the possible creation of the list. The following are the constructors available in this class:
LinkedList(): This is for creating an empty linked list. If create an empty LinkedList with the name letters, then, it can be created as:
LinkedList letters = new LinkedList();
LinkedList(Collection C): This constructor is used to create an ordered list which contains all the elements of a specified collection, as returned by the collection’s iterator. If we wish to create a linkedlist with the name letters, then, it can be created as:
LinkedList letters = new LinkedList(C);
Java LinkedList class hierarchy:
The Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data structure. It inherits the AbstractList class and implements List and Deque interfaces.
The important points about Java LinkedList are:
- It can contain duplicate elements.
- LinkedList class maintains insertion order.
- The clss is non synchronized.
- The class manipulation is fast because no shifting needs to occur.
- This class can be used as a list, stack or queue.
Hierarchy of LinkedList class:
Doubly Linked List: In the case of a doubly linked list, we can add or remove elements from both sides. java LinkedList class using doubly linked list
LinkedList class declaration with java.util.LinkedList class.
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable
Constructors of Java LinkedList
LinkedList(): It is used to construct an empty list.
LinkedList(Collection<? extends E> c): It is used to construct a list containing the elements of the specified collection, in the order, they are returned by the collection’s iterator.
Methods of Java LinkedList
boolean add(E e):This method is used to append the specified element to the end of a list.
void add(int index, E element):This methodis used to insert the specified element at the specified position index in a list.
boolean addAll(Collection<? extends E> c):This method is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.
boolean addAll(Collection<? extends E> c):This method is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.
boolean addAll(int index, Collection<? extends E> c):This method is used to append all the elements in the specified collection, starting at the specified position of the list.
void addFirst(E e):This method is used to insert the given element at the beginning of a list.
void addLast(E e):This method is used to append the given element to the end of a list.
void clear():This methodis used to remove all the elements from a list.
Object clone():This method is used to return a shallow copy of an ArrayList.
boolean contains(Object o):This method is used to return true if a list contains a specified element.
Iterator<E> descendingIterator():This method is used to return an iterator over the elements in a deque in reverse sequential order.
E element():This method is used to retrieve the first element of a list.
E get(int index): This method is used to return the element at the specified position in a list.
E getFirst(): This method is used to return the first element in a list.
E getLast(): This method is used to return the last element in a list.
int indexOf(Object o): This method is used to return the index in a list of the first occurrence of the specified element, or -1 if the list does not contain any element.
int lastIndexOf(Object o):This method is used to return the index in a list of the last occurrence of the specified element, or -1 if the list does not contain any element.
ListIterator<E> listIterator(int index):This method is used to return a list-iterator of the elements in proper sequence, starting at the specified position in the list.
boolean offerFirst(E e): This method inserts the specified element at the front of a list.
boolean offerLast(E e): This method inserts the specified element at the end of a list.
E peek(): This method is retrieves the first element of a list
E peekFirst(): It retrieves the first element of a list or returns null if a list is empty.
E peekLast(): It retrieves the last element of a list or returns null if a list is empty.
int size(): This method is used to return the number of elements in a list.
A common topic on ArrayList vs. LinkedList
- The LinkedList class is a collection which can contain many objects of the same type, just like the ArrayList.
- The LinkedList class has all of the same methods as the ArrayList class because they both implement the List interface. This means that you can add items, change items, remove items and clear the list in the same way. While, the ArrayList class and the LinkedList class can be used in the same way, they are built very differently.
How the ArrayList AND LinkedListworks:
The ArrayList class has a regular array inside it. When an element is added, it is placed into the array. If the array is not big enough, a new, larger array is created to replace the old one and the old one is removed. on the other hand, how the LinkedList works: Previously we have discussed about it. The LinkedList stores its items in “containers.” The list has a link to the first container and each container has a link to the next container in the list. To add an element to the list, the element is placed into a new container and that container is linked to one of the other containers in the list.
When To Use
When you want to access random items frequently use an ArrayList. You only need to add or remove elements at the end of the list. Besides, It is best to use a LinkedList when only use the list by looping through it instead of accessing random items. when frequently need to add and remove items from the beginning, middle or end of the list.
by Jesmin Akther | Jun 8, 2021 | JAVA
Java ArrayList
The ArrayList class is a resizable array in the java.util package. There is a difference between a built-in array and an ArrayList in Java. The size of an array cannot be modified to add or remove elements to/from an array to create a new one. While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different:
Example
Create an ArrayList object called cars that will store strings:
import java.util.ArrayList; // This is import the ArrayList class
ArrayList<String> cars = new ArrayList<String>(); // This is create an ArrayList object
If you are not gather much knowlodge what a package is, read our Java Packages Tutorial.
Add Items
To add an items, the ArrayList class has many useful methods. For example, to add elements to the ArrayList, use the add() method:
Example
import java.util.ArrayList;
public class Main {
public static void main (String[] args) {
ArrayList<String> names = new ArrayList<String>();
names.add("Babita");
names.add("Mamita");
names.add("Kabita");
names.add("Cabita");
names.add("Rabita");
System.out.println(names);
}
}
Access an Item
To access an element in the ArrayList need to use the get() method and refer to the index number:
Example
names.get(0);
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Change an Item
In order to modify an element, use the set() method and refer to the index number:
Example
names.set(0, “Jarite”);
Remove an Item
In order to remove an element, use the remove() method and refer to the index number:
Example
names.remove(0);
To remove all the elements in the ArrayList, use the clear() method:
Example
names.clear();
ArrayList Size
In order to find out how many elements an ArrayList have, use the size method:
Example
names.size();
Loop Through an ArrayList
Loop through the elements of an ArrayList with a for loop, and use the size() method to specify how many times the loop should run:
Example
public class ExampleMain {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
names.add("Babita");
names.add("Mamita");
names.add("Kabita");
names.add("Cabita");
names.add("Rabita");
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
}
}
You can also loop through an ArrayList with the for-each loop:
Example
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
names.add("Babita");
names.add("Mamita");
names.add("Kabita");
names.add("Cabita");
names.add("Rabita");
for (String i : names) {
System.out.println(i);
}
}
}
Other Types
Elements in an ArrayList are actually objects. In the examples above, we created elements (objects) of type “String”. Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:
Example
Create an ArrayList to store numbers (add elements of type Integer):
import java.util.ArrayList;
public class ExampleMain {
public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(10);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(25);
for (int i : myNumbers) {
System.out.println(i);
}
}
}
Sort an ArrayList
Another useful class in the java.util package is the Collections class, which include the sort() method for sorting lists alphabetically or numerically:
Example: Sort an ArrayList of Strings:
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
names.add("Babita");
names.add("Mamita");
names.add("Kabita");
names.add("Cabita");
names.add("Rabita");
Collections.sort(names); // Sort cars
for (String i : names) {
System.out.println(i);
}
}
}
Example
Sort an ArrayList of Integers:
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(33);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(34);
myNumbers.add(8);
myNumbers.add(12);
Collections.sort(myNumbers); // Sort myNumbers
for (int i : myNumbers) {
System.out.println(i);
}
}
}
Java ArrayList class hierarchy:
Java ArrayList class uses a dynamic array for storing the elements. It is simila to an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package. The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all the methods of List interface here. The ArrayList maintains the insertion order internally. It inherits the AbstractList class and implements List interface.
The important points about ArrayList are:
- Java ArrayList class can contain duplicate elements.
- Java ArrayList class maintains insertion order.
- Java ArrayList class is non synchronized.
- Java ArrayList allows random access because array works at the index basis.
In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list.
Hierarchy of ArrayList class
As shown in the above diagram, Java ArrayList class extends AbstractList class which implements List interface. The List interface extends the Collection and Iterable interfaces in hierarchical order.
ArrayList class declaration
Let’s see the declaration for java.util.ArrayList class.
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
Constructors of ArrayList, Constructor with Description BELOW
- ArrayList() : It is used to build an empty array list.
- ArrayList(Collection<? extends E> c): It is used to build an array list that is initialized with the elements of the collection c.
- ArrayList(int capacity): It is used to build an array list that has the specified initial capacity.
Methods of ArrayList |
Method Description |
void add(int index, E element) |
It is used to insert the specified element at the specified position in a list. |
boolean add(E e) |
It is used to append the specified element at the end of a list. |
boolean addAll(Collection<? extends E> c) |
It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator. |
boolean addAll(int index, Collection<? extends E> c) |
It is used to append all the elements in the specified collection, starting at the specified position of the list. |
void clear() |
It is used to remove all of the elements from this list. |
void ensureCapacity(int requiredCapacity) |
It is used to enhance the capacity of an ArrayList instance. |
E get(int index) |
It is used to fetch the element from the particular position of the list. |
boolean isEmpty() |
It returns true if the list is empty, otherwise false. |
Iterator() |
It works to traverse collection. |
listIterator() |
It works to traverse collection or list. |
int lastIndexOf(Object o) |
It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. |
Object[] toArray() |
It is used to return an array containing all of the elements in this list in the correct order. |
<T> T[] toArray(T[] a) |
It is used to return an array containing all of the elements in this list in the correct order. |
Object clone() |
It is used to return a shallow copy of an ArrayList. |
boolean contains(Object o) |
It returns true if the list contains the specified element |
int indexOf(Object o) |
It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. |
E remove(int index) |
It is used to remove the element present at the specified position in the list. |
boolean remove(Object o) |
It is used to remove the first occurrence of the specified element. |
boolean removeAll(Collection<?> c) |
It is used to remove all the elements from the list. |
boolean removeIf(Predicate<? super E> filter) |
It is used to remove all the elements from the list that satisfies the given predicate. |
protected void removeRange(int fromIndex, int toIndex) |
It is used to remove all the elements lies within the given range. |
void replaceAll(UnaryOperator<E> operator) |
It is used to replace all the elements from the list with the specified element. |
void retainAll(Collection<?> c) |
It is used to retain all the elements in the list that are present in the specified collection. |
E set(int index, E element) |
It is used to replace the specified element in the list, present at the specified position. |
void sort(Comparator<? super E> c) |
It is used to sort the elements of the list on the basis of specified comparator. |
Spliterator<E> spliterator() |
It is used to create spliterator over the elements in a list. |
List<E> subList(int fromIndex, int toIndex) |
It is used to fetch all the elements lies within the given range. |
int size() |
It is used to return the number of elements present in the list. |
void trimToSize() |
It is used to trim the capacity of this ArrayList instance to be the list’s current size. |
void add(int index, E element) |
It is used to insert the specified element at the specified position in a list. |
Java Non-generic Vs. Generic Collection
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic. Java new generic collection allows you to have only one type of object in a collection. Now it is type safe so typecasting is not required at runtime.
Old non-generic example of creating java collection.
ArrayList list=new ArrayList();//creating old non-generic arraylist. New generic example of creating java collection.
ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist
In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have the only specified type of objects in it. If you try to add another type of object, it gives compile time error.
Java ArrayList Example
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Man");//Adding object in arraylist
list.add("Cat");
list.add("Banana");
list.add("Cow"); //Printing the arraylist object
System.out.println(list);
}
}
Test it Now
Output:
[Man, Cat, Banana, Cow]
Iterating ArrayList using Iterator
Let’s see another example to traverse ArrayList elements using the Iterator interface.
import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Man");//Adding object in arraylist
list.add("Cat");
list.add("Banana");
list.add("Cow"); //Traversing list through Iterator
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and move to next
}
}
}
Output:
Man
Cat
Banana
Cow
Iterating ArrayList using For-each loop
Let’s see another example to traverse the ArrayList elements using the for-each loop
import java.util.*;
public class ArrayListExample3{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Man");//Adding object in arraylist
list.add("Cat");
list.add("Banana");
list.add("Cow"); //Traversing list through for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}
Output:
Man
Cat
Banana
Cow
Get and Set ArrayList
The get() method returns the element at the specified index, whereas the set() method changes the element.
import java.util.*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("Man");//Adding object in arraylist
list.add("Cat");
list.add("Banana");
list.add("Cow"); //accessing the element
System.out.println("Returning element: "+list.get(1));//it will return the 2nd element, because index starts from 0
//changing the element
list.set(1,"Dates");
//Traversing list
for(String lives:list)
System.out.println(lives);
}
}
Output:
Returning element:
Man
Cat
Banana
Cow
How to Sort ArrayList
The java.util package provides a utility class Collections which has the static method sort(). Using the Collections.sort() method, we can easily sort the ArrayList.
import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list.add("Man");//Adding object in arraylist
list.add("Cat");
list.add("Banana");
list.add("Cow"); //Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String lives:list1)
System.out.println(lives);
System.out.println("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
list2.add(12);
list2.add(11);
list2.add(10);
list2.add(9);
//Sorting the list
Collections.sort(list2);
//Traversing list through the for-each loop
for(Integer number:list2)
System.out.println(number);
}
}
Output:
Man
Cat
Banana
Cow
Sorting numbers…
9
10
11
12
Ways to iterate the elements of the collection in Java:
There are various ways to traverse the collection elements. By Iterator interface, for-each loop, ListIterator interface, for loop,forEach() and forEachRemaining() method. Let’s see an example to traverse the ArrayList elements through other ways
import java.util.*;
class ArrayList4{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Man");//Adding object in arraylist
list.add("Cat");
list.add("Banana");
list.add("Cow");
System.out.println("Traversing list through List Iterator:");
//Here, element iterates in reverse order
ListIterator<String> list1=list.listIterator(list.size());
while(list1.hasPrevious())
{
String str=list1.previous();
System.out.println(str);
}
System.out.println("Traversing list through for loop:");
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
System.out.println("Traversing list through forEach() method:");
//The forEach() method is a new feature, introduced in Java 8.
list.forEach(a->{ //Here, we are using lambda expression
System.out.println(a);
});
System.out.println("Traversing list through forEachRemaining() method:");
Iterator<String> itr=list.iterator();
itr.forEachRemaining(a-> //Here, we are using lambda expression
{
System.out.println(a);
});
}
}
Output:
Traversing list through List Iterator:
Man
Cat
Banana
Cow
Traversing list through for loop:
Cow
Banana
Cat
Man
Traversing list through forEach() method:
Cow
Banana
Cat
Man
Traversing list through forEachRemaining() method:
Cow
Banana
Cat
Man
User-defined class objects in Java ArrayList
Let’s see an example where we are storing Student class object in an array list.
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
import java.util.*;
class ArrayList5{
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Harun",20);
Student s2=new Student(102,"Md",21);
Student s2=new Student(103,"Paru",22);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);//adding Student class object
al.add(s2);
al.add(s3);
//Getting Iterator
Iterator itr=al.iterator();
//traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output:
101 Harun 20
102 Md 21
103 Paru 22
Java ArrayList Serialization and Deserialization Example
Let’s see an example to serialize an ArrayList object and then deserialize it.
import java.io.*;
import java.util.*;
class ArrayList6 {
public static void main(String [] args)
{
ArrayList<String> list=new ArrayList<String>();
list.add("R");
list.add("V");
list.add("A");
try
{
//Serialization
FileOutputStream foslist=new FileOutputStream("file");
ObjectOutputStream ooslist =new ObjectOutputStream(fos);
ooslist.writeObject(list);
foslist.close();
ooslist.close();
//Deserialization
FileInputStream fislist=new FileInputStream("file");
ObjectInputStream oislist=new ObjectInputStream(fislist);
ArrayList alist=(ArrayList)oislist.readObject();
System.out.println(alist);
}catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
[R, V, A]
Java ArrayList example to add elements
Here, example code of different ways to add an element.
import java.util.*;
class ArrayList7{
public static void main(String args[]){
ArrayList<String> list =new ArrayList<String>();
System.out.println("Initial list of elements: "+ list);
//Adding elements to the end of the list
list.add("R");
list.add("V");
list.add("A");
System.out.println("After invoking add(E e) method: "+ list);
//Adding an element at the specific position
list.add(1, "G");
System.out.println("After invoking add(int index, E element) method: "+al);
ArrayList<String> list2=new ArrayList<String>();
list2.add("S");
list2.add("H");
//Adding second list elements to the first list
list2.addAll(list2);
System.out.println("After invoking addAll(Collection<? extends E> c) method: "+ list);
ArrayList<String> list3=new ArrayList<String>();
list3.add("J");
list3.add("R");
//Adding second list elements to the first list at specific position
list.addAll(1, list3);
System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+ list);
}
}
Output:
Initial list of elements: []
After invoking add(E e) method: [R, V, A]
After invoking add(int index, E element) method: [R, G, V, A]
After invoking addAll(Collection<? extends E> c) method:
[R, G, V, A, S, H]
After invoking addAll(int index, Collection<? extends E> c) method:
[R, J, R, G, V, A, S, H]
Java ArrayList example to remove elements
Here, we see different ways to remove an element.
import java.util.*;
class ArrayList8 {
public static void main(String [] args)
{
ArrayList<String> list=new ArrayList<String>();
list.add("R");
list.add("V");
list.add("A");
list.add("A");
list.add("G");
System.out.println("An initial list of elements: "+ list);
//Removing specific element from arraylist
list.remove("V");
System.out.println("After invoking remove(object) method: "+ list);
//Removing element on the basis of specific position
list.remove(0);
System.out.println("After invoking remove(index) method: "+ list);
//Creating another arraylist
ArrayList<String> list2=new ArrayList<String>();
list2.add("R");
list2.add("H");
//Adding new elements to arraylist
list2.addAll(list2);
System.out.println("Updated list : "+ list);
//Removing all the new elements from arraylist
list.removeAll(list2);
System.out.println("After invoking removeAll() method: "+ list);
//Removing elements on the basis of specified condition
list.removeIf(str -> str.contains("A")); //This is Lambda expression
System.out.println("After invoking removeIf() method: "+ list);
//Removing all the elements available in the list
list.clear();
System.out.println("After invoking clear() method: "+ list);
}
}
Output:
An initial list of elements: [R, V, A, A, G]
After invoking remove(object) method: [R, A, A, G]
After invoking remove(index) method: [A, A, G]
Updated list : [A, A, G, R, H]
After invoking removeAll() method: [A, A, G]
After invoking removeIf() method: [A, G]
After invoking clear() method: []
by Jesmin Akther | Jun 7, 2021 | JAVA
Date and Time in Java
Example of Constructor
- Date( ) this constructor initializes the object with the current date and time.
- Date(long millisec) this constructor accepts an argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970.
Following are the some methods of the date class.
Method |
Description |
boolean after(Date date) |
Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false. |
boolean before(Date date) |
Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false. |
Object clone( ) |
Duplicates the invoking Date object. |
int compareTo(Date date) |
Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date. |
int compareTo(Object obj) |
Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException. |
boolean equals(Object date) |
Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false. |
long getTime( ) |
Returns the number of milliseconds that have elapsed since May 1, 2020. |
int hashCode( ) |
Returns a hash code for the invoking object. |
void setTime(long time) |
Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, May 1, 2020. |
String toString( ) |
Converts the invoking Date object into a string and returns the result. |
Getting Current Date and Time
This is a very easy method to get current date and time in Java. You can use a simple Date object with toString() method to print the current date and time as follows:
Example
import java.util.Date;
public class ExampleDateDemo {
public static void main(String args[]) {
Date date = new Date(); // This statement Instantiate a Date object
System.out.println(date.toString()); // display time and date using toString()
}
}
This will produce the following result:
Output
Mon Jun 07 11:55:32 UTC 2021
Date Comparison
Following are the three ways to compare two dates:
- Method getTime( ) to obtain the number of milliseconds that have passed since midnight, June 1, 2021, for both objects and then compare these two values.
- methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 21).before(new Date (99, 2, 21)) returns true.
- Method compareTo( ) method, which is defined by the Comparable interface and implemented by Date.
Date Format Using SimpleDateFormat class:
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. This class allows you to start by choosing any user-defined patterns for date-time formatting.
Example
import java.util.*;
import java.text.*;
public class ExampleDateDemo {
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current Date: " + ft.format(dNow));
}
}
This will produce the following result:
Output
Current Date: Mon 2021.06.07 at 01:04:15 PM UTC
Simple DateFormat Format Codes
In order to specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following:
Character Description
G Era designator, Example: AD
y Year in four digits, Example: 2001
M Month in year, Example: July or 07
d Day in month, Example: 10
h Hour in A.M./P.M. (1~12) Example:12
H Hour in day (0~23), Example:22
m Minute in hour 30, Example:
s Second in minute, Example:55
S Millisecond Example:234
E Day in week Example:Tuesday
D Day in year Example:360
F Day of week in month Example:2 (second Wed. in July)
w Week in year Example:40
W Week in month Example:1
a A.M./P.M. marker Example:PM
k Hour in day (1~24) Example:24
K Hour in A.M./P.M. (0~11) Example:10
z Time zone Example:Eastern Standard Time
‘ Escape for text Delimiter
” Single quote `
Date Format Using printf
Date and time formatting can be done very easily using printf method. You use a two-letter format, starting with t and ending in one of the letters of the table as shown in the following code.
Example
import java.util.Date;
public class ExampleDateDemo {
public static void main(String args[]) {
Date date = new Date(); // Instantiate a Date object
String str = String.format("Current Date/Time : %tc", date ); // display time and date
System.out.printf(str);
}
}
This will produce the following result −
Output
Current Date/Time : Mon Jun 07 13:08:21 UTC 2021
It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted. The index must immediately follow the % and it must be terminated by a $.
Example
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
Date date = new Date();// Instantiate a Date object
System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);// display time and date
}
}
This will produce the following result:
Output
Due date: June 07, 2021
Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again.
Example
import java.util.Date;
public class ExampleDateDemo {
public static void main(String args[]) {
Date date = new Date(); // This statement Instantiate a Date object
System.out.printf("%s %tB %<te, %<tY", "Due date:", date); // This statement display formatted date
}
}
This will produce the following result −
Output
Due date: June 7, 2021
Date and Time Conversion Characters
Character |
Description |
c |
Complete date and time; Example: Mon May 04 09:51:52 CDT 2009 |
F |
ISO 8601 date |
D |
U.S. formatted date (month/day/year). Example: 02/09/2004 |
T |
24-hour time |
r |
12-hour time |
R |
24-hour time, no seconds. Example: |
Y |
Four-digit year (with leading zeroes). Example: |
y |
Last two digits of the year (with leading zeroes). Example: |
C |
First two digits of the year (with leading zeroes) |
B |
Full month name |
b |
Abbreviated month name |
m |
Two-digit month (with leading zeroes) |
d |
Two-digit day (with leading zeroes) |
e |
Two-digit day (without leading zeroes) |
A |
Full weekday name |
a |
Abbreviated weekday name. Example: |
j |
Three-digit day of year (with leading zeroes) . Example: |
H |
Two-digit hour (with leading zeroes), between 00 and 23 |
k |
Two-digit hour (without leading zeroes), between 0 and 23 |
I |
Two-digit hour (with leading zeroes), between 01 and 12 |
l |
Two-digit hour (without leading zeroes), between 1 and 12 |
M |
Two-digit minutes (with leading zeroes) . Example: |
S |
Two-digit seconds (with leading zeroes) |
L |
Three-digit milliseconds (with leading zeroes) |
N |
Nine-digit nanoseconds (with leading zeroes) |
P |
Uppercase morning or afternoon marker |
p |
Lowercase morning or afternoon marker |
z |
RFC 822 numeric offset from GMT |
Z |
Time zone |
s |
Seconds since 1970-01-01 00:00:00 GMT. Example: |
Q |
Milliseconds since 1970-01-01 00:00:00 GMT. Example: |
There are other useful classes related to Date and time. For more details, you can refer to Java Standard documentation.
Parsing Strings into Dates
The SimpleDateFormat class has some additional methods, notably parse( ), which tries to parse a string according to the format stored in the given SimpleDateFormat object.
Example
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
SimpleDateFormat ft = new SimpleDateFormat (“yyyy-MM-dd”);
String input = args.length == 0 ? “1818-11-11″ : args[0];
System.out.print(input + ” Parses as “);
Date t;
try {
t = ft.parse(input);
System.out.println(t);
} catch (ParseException e) {
System.out.println(“Unparseable using ” + ft);
}
}
}
A sample run of the above program would produce the following result −
Output
1818-11-11 Parses as Wed Nov 11 00:00:00 UTC 1818
Sleep for a While
You can sleep for any period of time from one millisecond up to the lifetime of your computer. For example, the following program would sleep for 3 seconds −
Example
import java.util.*;
public class SleepDemo {
public static void main(String args[]) {
try {
System.out.println(new Date( ) + “\n”);
Thread.sleep(5*60*10);
System.out.println(new Date( ) + “\n”);
} catch (Exception e) {
System.out.println(“Got an exception!”);
}
}
}
This will produce the following result:
Output
Mon Jun 07 13:13:30 UTC 2021
Mon Jun 07 13:13:33 UTC 2021
Measuring Elapsed Time
Sometimes, you may need to measure point in time in milliseconds. So let’s re-write the above example once again −
Example
import java.util.*;
public class DiffDemo {
public static void main(String args[]) {
try {
long start = System.currentTimeMillis( );
System.out.println(new Date( ) + “\n”);
Thread.sleep(5*60*10);
System.out.println(new Date( ) + “\n”);
long end = System.currentTimeMillis( );
long diff = end – start;
System.out.println(“Difference is : ” + diff);
} catch (Exception e) {
System.out.println(“Got an exception!”);
}
}
}
This will produce the following result :
Output
Mon Jun 07 13:14:57 UTC 2021
Mon Jun 07 13:15:00 UTC 2021
Difference is : 3036
GregorianCalendar Class
GregorianCalendar is a concrete implementation of a Calendar class that implements the normal Gregorian calendar with which you are familiar. We did not discuss Calendar class in this tutorial, you can look up standard Java documentation for this. The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the current date and time in the default locale and time zone. GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar. There are also several constructors for GregorianCalendar objects:
Constructor |
Description |
GregorianCalendar() |
This Constructor constructs a default GregorianCalendar using the current time in the default time zone with the default locale. |
GregorianCalendar(int year, int month, int date) |
This Constructor constructs a GregorianCalendar with the given date set in the default time zone with the default locale. |
GregorianCalendar(int year, int month, int date, int hour, int minute) |
This Constructor constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale. |
GregorianCalendar(int year, int month, int date, int hour, int minute, int second) |
This Constructor constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale. |
GregorianCalendar(Locale aLocale) |
This Constructor constructs a GregorianCalendar based on the current time in the default time zone with the given locale. |
GregorianCalendar(TimeZone zone) |
This Constructor constructs a GregorianCalendar based on the current time in the given time zone with the default locale. |
GregorianCalendar(TimeZone zone, Locale aLocale) |
This Constructor constructs a GregorianCalendar based on the current time in the given time zone with the given locale. |
Here is the list of few useful support methods provided by GregorianCalendar class:
Method |
Description |
void add(int field, int amount) |
Adds the specified (signed) amount of time to the given time field, based on the calendar’s rules. |
protected void computeFields() |
Converts UTC as milliseconds to time field values. |
protected void computeTime() |
Overrides Calendar Converts time field values to UTC as milliseconds. |
boolean equals(Object obj) |
Compares this GregorianCalendar to an object reference. |
int get(int field) |
Gets the value for a given time field. |
int getActualMaximum(int field) |
Returns the maximum value that this field could have, given the current date. |
int getActualMinimum(int field) |
Returns the minimum value that this field could have, given the current date. |
int getGreatestMinimum(int field) |
Returns highest minimum value for the given field if varies. |
Date getGregorianChange() |
Gets the Gregorian Calendar change date. |
int getLeastMaximum(int field) |
int getLeastMaximum(int field) Returns lowest maximum value for the given field if varies. |
int getMaximum(int field) |
Returns maximum value for the given field. |
Date getTime() |
Gets this Calendar’s current time. |
long getTimeInMillis() |
Gets this Calendar’s current time as a long. |
TimeZone getTimeZone() |
Gets the time zone. |
int getMinimum(int field) |
Returns minimum value for the given field. |
int hashCode() |
Overrides hashCode. |
boolean isLeapYear(int year) |
Determines if the given year is a leap year. |
void roll(int field, boolean up) |
Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields. |
void set(int field, int value) |
Sets the time field with the given value. |
void set(int year, int month, int date) |
Sets the values for the fields year, month, and date. |
Example
import java.util.*;
public class ExampleGregorianCalendarDemo {
public static void main(String args[]) {
String months[] = {“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”,
“Oct”, “Nov”, “Dec”};
int year; // Create a Gregorian calendar initialized with the current date and time in the default timezone.
GregorianCalendar gcalendar = new GregorianCalendar();
System.out.print(“Date: “);// Display current time and date information.
System.out.print(months[gcalendar.get(Calendar.MONTH)]);
System.out.print(” ” + gcalendar.get(Calendar.DATE) + ” “);
System.out.println(year = gcalendar.get(Calendar.YEAR));
System.out.print(“Time: “);
System.out.print(gcalendar.get(Calendar.HOUR) + “:”);
System.out.print(gcalendar.get(Calendar.MINUTE) + “:”);
System.out.println(gcalendar.get(Calendar.SECOND));
if(gcalendar.isLeapYear(year)) { // Test if the current year is a leap year
System.out.println(“The current year is a leap year”);
}else {
System.out.println(“The current year is not a leap year”);
}
}
}
This will produce the following result −
Output
Date: Jun 7 2021
Time: 1:16:54
The current year is not a leap year
For a complete list of constant available in Calendar class, you can refer the standard Java documentation.
Java Dates does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes. For example:
- LocalDate class: Represents a date (year, month, day (yyyy-MM-dd))
- LocalTime class: Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns))
- LocalDateTime class: Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)
- DateTimeFormatter class:Formatter for displaying and parsing date-time objects
If you don’t know what a package is, read our Java Packages article .
Current Date
To display the current date, import the java.time. LocalDate class, and use its now() method:
Example
import java.time.LocalDate; // import the LocalDate class
public class ExampleMain {
public static void main(String[] args) {
LocalDate myObj = LocalDate.now(); // This is Create a date object
System.out.println(myObj); // This is Display the current date
}
}
The output will be:
2021-06-07
Current Time
To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class, and use its now() method:
Example
import java.time.LocalTime; // This is import the LocalTime class
public class ExapleMain {
public static void main(String[] args) {
LocalTime myObj = LocalTime.now();
System.out.println(myObj);
}
}
The output will be:
14:47:34.528
Display Current Date and Time
In order to display the current date and time, import the java.time.LocalDateTime class, and use its now() method:
Example
import java.time.LocalDateTime; // import the LocalDateTime class
public class ExampleMain {
public static void main(String[] args) {
LocalDateTime myObj = LocalDateTime.now();
System.out.println(myObj);
}
}
The output will be:
2021-06-07T14:48:24.914
Formatting Date and Time
The “T” in the example above is used to separate the date from the time. You can use the DateTimeFormatter class with the ofPattern() method in the same package to format or parse date-time objects. The following example will remove both the “T” and nanoseconds from the date-time:
Example
import java.time.LocalDateTime; // This Import the LocalDateTime class
import java.time.format.DateTimeFormatter; //This Import the DateTimeFormatter class
public class ExampleMain {
public static void main(String[] args) {
LocalDateTime myDateObj = LocalDateTime.now();
System.out.println("Before formatting: " + myDateObj);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDate = myDateObj.format(myFormatObj);
System.out.println("After formatting: " + formattedDate);
}
}
output:
Before formatting: 2021-06-07T14:50:38.049
After formatting: 07-06-2021 14:50:38
The ofPattern() method receive all of values, if you want to display the date and time in a different format. For example:
Value
yyyy-MM-dd Example: “2020-05-29″
dd/MM/yyyy Example:”29/05/2020″
dd-MMM-yyyy Example:”29-May -2020″
E, MMM dd yyyy Example:”Thu, May 29 2020”
by Jesmin Akther | Jun 7, 2021 | JAVA
Java User Input
The Scanner class is used to get user input and is the easiest way to read input in Java program. Java Scanner class permits the user to take input from the console. The class is belongs to java.util package. It is used to read the input of primitive types like int, double, long, short, float, and byte.
Syntax
Scanner sc=new Scanner(System.in);
The above statement creates a constructor of the Scanner class having System.in as an argument. it is going to read from the standard input stream of the program taking input from the console. The java.util package should be import while using Scanner class. It also converts the Bytes that is from the input stream into characters using the platform’s default charset.
The most widely used method is Scanner and I personally prefer it because of its simplicity and easy implementation, as well as its powerful utility to parse text into primitive data.
Advantages of Using Scanner
- Easy to use the Scanner class.
- Easy input of numbers (int, short, byte, float, long and double).
- Exceptions are unchecked which is more convenient. It is up to the programmer to be civilized, and specify or catch the exceptions.
- Is able to read lines, white spaces, and regex-delimited tokens
In order to use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings:
Example
import java.util.Scanner; // This statement is Import the Scanner class
class ExampleMain {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // This statement is Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // This statement is Read user input
System.out.println("Username is: " + userName); // This statement is Output user input
}
}
OUTPUT
Enter username
Harun
Username is: Harun
If you are not well known what a package is, read our Java Packages/API Tutorial.
Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below:
Method |
Description |
nextBoolean() |
It is used to scan Reads a Boolean value from the user |
nextByte() |
It is used to scan Reads a byte value from the user |
nextDouble() |
It is used to scan Reads a double value from the user |
nextFloat() |
It is used to scan Reads a float value from the user |
nextInt() |
It is used to scan Reads an int value from the user |
nextLine() |
It is used to scan Reads a String value from the user |
nextLong() |
It is used to scan Reads a long value from the user |
nextShort() |
It is used to scan Reads a short value from the user |
int nextInt() |
It is used to scan the next token of the input as an integer. |
nextBigInteger() |
It is used to scan the next token of the input as a BigInteger. |
nextBigDecimal() |
It is used to scan the next token of the input as a BigDecimal. |
In the example below, we use different methods to read data of various types:
Example
import java.util.Scanner;
class ExampleMain {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name age and salary:");
String name = myObj.nextLine(); // This statement is String input
int age = myObj.nextInt(); // This statement is Numerical input
double salary = myObj.nextDouble();
System.out.println("Name: " + name); // This statement is Output input by user
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
OUTPUT
Enter name, age and salary:
Harun
22
40000
Name: Harun
Age: 22
Salary: 40000
Example of integer input from user. The following example allows user to read an integer form the System.in.
import java.util.*;
class ExampleMain
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter first number: ");
int a= sc.nextInt();
System.out.print("Enter second number:");
int b= sc.nextInt();
System.out.print("Enter third number: ");
int c= sc.nextInt();
int d=a+b+c;
System.out.println("Total= " +d);
}
}
Output:
How to get input from user in Java
Example of String Input from user
Let’s see another example, in which we have taken string input.
import java.util.*;
class ExampleMain
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter a string: ");
String str= sc.nextLine(); //This statement is read string
System.out.print("You have entered: "+str);
}
}
Output:
How to get input from user in Java. If you enter wrong input (for example, text in a numerical input), you will get an exception/error message ( such as “InputMismatchException”).
by Jesmin Akther | Jun 7, 2021 | JAVA
Java Polymorphism
Polymorphism means “many forms”, It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class. It occurs when we have many classes that are related to each other by inheritance. Like we definite in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in diverse ways.
For example, think of a superclass called Tree that has a method called treeSound(). Subclasses of Tree could be SmallTree, MidSizeTree. And they also have their own implementation of an tree sound:
Example
class Tree {
public void treeSound() {
System.out.println(“The tree makes a sound in wind”);
}
}
class SmallTree extends Tree {
public void treeSound() {
System.out.println(“The SmallTree can also makes a sound in wind”);
}
}
class MidSizeTree extends c {
public void treeSound() {
System.out.println(“The MidSizeTree can also makes a sound in wind”);
}
}
Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.Now we can create Pig and Dog objects and call the animalSound() method on both of them:
Example
class Tree {
public void treeSound() {
System.out.println(“The tree makes a sound in wind”);
}
}
class SmallTree extends Tree {
public void treeSound() {
System.out.println(“The SmallTree can also makes a sound in wind”);
}
}
class MidSizeTree extends c {
public void treeSound() {
System.out.println(“The MidSizeTree can also makes a sound in wind”);
}
}
class Main {
public static void main(String[] args) {
Tree myTree = new Tree(); // create Tree obj
Tree mySmall = new SmallTree();// create SmallTree obj
Tree myMidSize = new MidSizeTree();// create MidSizeTree obj
myTree.treeSound();
mySmall.treeSound();
mymyMidSize.treeSound();
}
}
OUTPUT
The tree makes a sound in wind
The SmallTree makes a sound in wind
The MidSizeTree can also makes a sound in wind
by Jesmin Akther | Jun 7, 2021 | JAVA
Java Inheritance
Subclass and Superclass contains in inheritance mainly. In Java, it is possible to inherit attributes and methods from one class to another. It contains of two categories:
subclass (child) – the class that inherits from another class
superclass (parent) – the class being inherited from
To inherit from a class, use the extends keyword. In the example below, the Car class (subclass) inherits the attributes and methods from the Vehicle class (superclass):
Example
class Tree {
protected String leavesColor = “Green”; // attribute
public void branch() { // method
System.out.println(“Tree !”);
}
}
class Fruits extends Tree {
private String fruitsName = “Mango”; // attribute
public static void main(String[] args) {
// Create a myFruit object
Fruits myFruits = new Fruits();
// Call the () method (from the Vehicle class) on the myCar object
myFruits.branch ();
// Display the value of the brand attribute (from the Tree class) and the value of the fruitsName from the Fruits class
System.out.println(myFruits.branch + ” ” + myCar.fruitsName);
}
}
Did you notice the protected modifier in Vehicle? Here, set the brance attribute in Tree to a protected access modifier. If it was set to private, the Fruits class would not be able to access it. Why and when to Use “Inheritance”? It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.
The final Keyword
If you don’t want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:
final class Tree {
…
}
class Fruits extends Tree {
…
}
The output will be something like this:
Main.java:9: error: cannot inherit from final Tree
class Main extends Tree {
^
1 error)
Java inheritance refers to the capability in Java for one class to inherit from another class. In Java this is also called extending a class. One class can extend another class and thereby inherit from that class. When one class inherits from another class in Java, the two classes take on certain roles. The class that extends (inherits from another class) is the subclass and the class that is being extended (the class being inherited from) is the superclass. In other words, the subclass extends the superclass. Or, the subclass inherits from the superclass. Another commonly used term for inheritance is specialization and generalization. A subclass is a specialization of a superclass, and a superclass is a generalization of one or more subclasses.
Inheritance is a Method of Code Reuse: Inheritance can be an effective method to share code between classes that have some traits in common, yet allowing the classes to have some parts that are different.
Class Hierarchies
In java, Superclasses and subclasses form an inheritance structure which is also called a class hierarchy. At the top of the class hierarchy you have the superclasses. At the bottom of the class hierarchy you have the subclasses. A class hierarchy may have multiple levels, meaning multiple levels of superclasses and subclasses. A subclass may itself be a superclass of other subclasses etc.
Java Inheritance Basics
When a class inherits from a superclass, it inherits parts of the superclass methods and fields. The subclass can also override (redefine) the inherited methods. Fields cannot be overridden, but can be “shadowed” in subclasses. How all this works is covered later in this text.
What is Inherited?
When a subclass extends a superclass in Java, all protected and public fields and methods of the superclass are inherited by the subclass. By inherited is meant that these fields and methods are part of of the subclass, as if the subclass had declared them itself. protected and public fields can be called and referenced just like the methods declared directly in the subclass.
Fields and methods with default (package) access modifiers can be accessed by subclasses only if the subclass is located in the same package as the superclass. Private fields and methods of the superclass can never be referenced directly by subclasses. They can, however, be referenced indirectly via methods reachable from the subclass e.g default (package), protected and public methods. Constructors are not inherited by subclasses, but a subclass constructor must call a constructor in the superclass. This will be explained in detail in a later section.
Java Only Supports Singular Inheritance
The Java inheritance mechanism only allows a Java class to inherit from a single superclass (singular inheritance). In some programming languages, like C++, it is possible for a subclass to inherit from multiple superclasses (multiple inheritance). Since multiple inheritance can create some weird problems, if e.g., the superclasses contain methods with the same names and parameters, multiple inheritance was left out in Java.
Declaring Inheritance in Java
In Java inheritance is declared using the extends keyword. You declare that one class extends another class by using the extends keyword in the class definition. Here is Java inheritance example using the extends keyword:
public class Tree {
protected String color = null;
public void colorSet (String colors) {
this.color = colors;
}
}
public class Fruits extends Tree {
int numberOftree = 0;
public String getNumberOftree() {
return this. numberOftree;
}
}
The Fruits class in this example extends the Tree class, meaning the Fruits class inherits from the Tree class. Because the Fruits class extends the Tree class, the protected field numberOftree from the Tree class is inherited by the Fruits class. When the numberOftree field is inherited, it is accessible inside a Fruits instance. The numberOftree field is not actually being referenced from the Fruits class in the code above, but it could if we wanted to. Here is an example that shows how that could look:
public class Fruits extends Tree {
int numberOftree = 0;
public String getNumberOfTrees() {
return this. numberOftree;
}
public String getnumberOftrees () {
return this.numberOftree;
}
}
The referencing happens inside the getnumberOftree () method. In many cases it would have made sense to place the getnumberOftree () method in the Tree class where the numberOftree field is located. I just placed the getnumberOftree () method in the Fruits class to show that it is possible.
Inheritance and Type Casting
It is possible to reference a subclass as an instance of one of its superclasses. For instance, using the class definitions from the example in the previous section it is possible to reference an instance of the Fruits class as an instance of the Tree class. Because the Fruits class extends (inherits from) the Tree class, it is also said to be a Tree. Here is a Java code example:
Fruits f = new Fruits ();
Tree tree = f;
First a Fruits instance is created. Second, the Fruits instance is assigned to a variable of type Tree. Now the Tree variable (reference) points to the Fruits instance. This is possible because the Fruits class inherits from the Tree class.Because, it is possible to use an instance of some subclass as if it were an instance of its superclass. That way, you don’t need to know exactly what subclass the object is an instance of. You could treat e.g. Fruits instances as Tree instances.
The process of referencing an object of class as a different type than the class itself is called type casting. You cast an object from one type to another.
Upcasting and Downcasting
You can always cast an object of a subclass to one of its superclasses. This is referred to as upcasting (from a subclass type to a superclass type).
It may also be possible to cast an object from a superclass type to a subclass type, but only if the object really is an instance of that subclass (or an instance of a subclass of that subclass). This is referred to as downcasting (from a superclass type to a subclass type). Thus, this example of downcasting is valid:
Fruits f = new Fruits ();
// upcast to Tree
Tree tree = f;
// downcast to f again
Fruits f = (Fruits)tree;
However, the following downcast example is not valid. The Java compiler will accept it, but at runtime when this code is executed the code will throw a ClassCastException.
Truck truck = new Truck();
// upcast to Tree
Tree tree = truck;
// downcast to f again
Fruits f = (Fruits) tree;
The Truck object can be upcast to a Tree object, but it cannot be downcast to a Fruits object later. This will result in a ClassCastException.
Overriding Methods
In a subclass you can override or redefine the methods defined in the superclass. Here is a Java method override example:
public class Tree {
String treePlate = null;
public void setLicensePlate(String treePlate) {
this. treePlate = treePlate;
}
}
public class Fruits extends Tree {
public void settreePlate (String treeP) {
this.treePlate = treeP.toLowerCase();
}
}
Notice how both the Vehicle class and the Car class defines a method called settreePlate (). Now, whenever the settreePlate () method is called on a Fruits object, it is the method defined in the Fruits class that is called. The method in the superclass is ignored.
To override a method the method signature in the subclass must be the same as in the superclass. That means that the method definition in the subclass must have exactly the same name and the same number and type of parameters, and the parameters must be listed in the exact same sequence as in the superclass. Otherwise the method in the subclass will be considered a separate method.
In Java you cannot override private methods from a superclass. If the superclass calls a private method internally from some other method, it will continue to call that method from the superclass, even if you create a private method in the subclass with the same signature.
The @override Annotation
If you override a method in a subclass, and the method is accidently removed or modified in the superclass, the method in the subclass no longer overrides the method in the superclass. But how do you know? It would be nice if the compiler could tell you that the method being overridden no longer overrides a method in the superclass, right?
This is what the Java @override annotation is for. You place the Java @override annotation above the method that overrides a method in a superclass. Here is Java @override example:
public class Fruits extends Tree {
@Override
public void settreePlate (String treeP) {
this.treePlate= treeP.toLowerCase();
}
}
Calling Superclass Methods
If you override a method in a subclass, but still need to call the method defined in the superclass, you can do so using the super reference, like this:
public class Fruits extends Tree {
public void settreePlate (String treeP) {
super.settreePlate (treeP);
}
}
In the above code example the method settreePlate() in the Car class, calls the settreePlate() method in the Tree class. You can call superclass implementations from any method in a subclass, like above. It does not have to be from the overridden method itself. For instance, you could also have called super.treePlate() from a method in the Car class called updatetreePlate() which does not override the settreePlate() method.
The instanceof Instruction
Java contains an instruction named instanceof. The instanceof instruction can determine whether a given object is an instance of some class. Here is a Java instanceof example:
Fruits f = new Fruits ();
boolean isFruits = f instanceof Fruits;
After this code has been executed the isFruits variable will contain the value true.
The instanceof instruction can also be used determine if an object is a instance of a superclass of its class. Here is an instanceof example that checks if a Car object is an instance of Vehicle:
Fruits f = new Fruits ();
boolean isTree = f instanceof Tree;
Assuming that the Fruits class extends (inherits from) the Tree class, the isTree variable will contain the value true after this code is executed. A Fruits object is also a Tree object because Fruits is a subclass of Vehicle.
As you can see, the instanceof instruction can be used to explore the inheritance hierarchy. The variable type used with the instanceof instruction does not affect its outcome. Look at this instanceof example:
Fruits f = new Fruits ();
Tree tree = f;
boolean isFruits = tree instanceof Fruits;
Even though the tree variable is of type Tree, the object it ends up pointing to in this example is a Fruits object. Therefore the tree instanceof Fruits instruction will evaluate to true. Here is the same instanceof example, but using a Truck object instead of a Fruits object:
Truck truck = new Truck();
Tree tree = truck;
boolean isFruits = tree instanceof Fruits;
After executing this code the isFruits will contain the value false. The Truck object is not a Fruits object.
Fields and Inheritance
As mentioned earlier, in Java fields cannot be overridden in a subclass. If you define a field in a subclass with the same name as a field in the superclass, the field in the subclass will hide (shadow) the field in the superclass. If the subclass tries to access the field, it will access the field in the subclass. If, however, the subclass calls up into a method in the superclass, and that method accesses the field with the same name as in the subclass, it is the field in the superclass that is accessed. Here is Java inheritance example that illustrates how fields in subclasses shadow (hides) fields in superclasses:
public class Fruits extends Tree {
int numberOftree = 0;
public String getNumberOfTrees() {
return this. numberOftree;
}
public String getnumberOftrees () {
return this.numberOftree;
}
}
public class Tree {
String treeP = null;
public void settreeP(String treePlate) {
this. treePlate = treePlate;
}
public String getTreeP() {
return treeP;
}
}
public class Fruits extends Tree {
protected String treeP = null;
@Override
public void setTreeP(String tp) {
super.setTreeP(tp);
}
@Override
public String getTreeP () {
return super.getTreeP();
}
public void updateTreeP(String tp){
this.TreeP = tp;
}
}
Notice how both classes have a TreeP field defined. Both the Tree class and Fruits class has the methods setTreeP() and getTreeP(). The methods in the Fruits class calls the corresponding methods in the Tree class. The result is, that eventually both set of methods access the treeP field in the Tree class.
The updateTreeP() method in the Car class however, accesses the treeP field directly. Thus, it accesses the treeP field of the Fruits class. Therefore, you will not get the same result if you call setTreeP() as when you call the updateTree() method.
Look at the following lines of Java code:
Fruits f = new Fruits ();
f.setTreeP(“123”);
car.updateTreeP(“abc”);
System.out.println(“tree p: ” + f.getTreeP ());
This Java code will print out the text 123.
The updateTreeP () method sets the license plate value on the TreeP field in the Fruits class. The getTreeP() method, however, returns the value of the TreeP field in the Tree class. Therefore, the value 123 which is set as value for the TreeP field in the Vehicle class via the setTreeP() method, is what is printed out.
Constructors and Inheritance
The Java inheritance mechanism does not include constructors. In other words, constructors of a superclass are not inherited by subclasses. Subclasses can still call the constructors in the superclass using the super() contruct. In fact, a subclass constructor is required to call one of the constructors in the superclass as the very first action inside the constructor body. Here is how that looks:
public class Tree {
public Tree() {
}
}
public class Fruits extends Tree{
public Fruits() {
super();
//perform other initialization here
}
}
Notice the call to super() inside the Car constructor. This super() call executes the constructor in the Vehicle class. You may have seen Java classes where the subclass constructors did not seem to call the constructors in the superclass. Maybe the superclass did not even have a constructor. However, the subclass constructors have still called superclass constructors in those case. You just could not see it. Let me explain why: If a class does not have any explicit constructor defined, the Java compiler inserts an implicit non arg constructor. Thus, a class always has a constructor. Therefore, the following version of Vehicle is equivalent to the version shown just above:
public class Tree {
}
Second, if a constructor does not explicitly call a constructor in the superclass, the Java compiler inserts an implicit call to the no-arg constructor in the superclass. That means that the following version of the Car class is actually equivalent to the version shown earlier:
public class Fruits extends Tree {
public Fruits () {
}
}
In fact, since the constructor is now empty, we could leave it out and the Java compiler would insert it, and insert an implicit call to the non arg constructor in the superclass. This is how the two classes would look then:
public class Tree {
}
public class Fruits extends Tree{
}
Even though no constructors are declared in these two classes, they both get a no-arg constructor, and the no-arg constructor in the Fruits class will call the no-arg constructor in the Vehicle class.
If the Tree class did not have a no-arg constructor, but had another constructor which takes parameters, the Java compiler would complain. The Fruits class would then be required to declare a constructor, and inside that constructor call the constructor in the Vehicle class.
Nested Classes and Inheritance
The same Java inheritance rules apply to nested classes. Nested classes which are declared private are not inherited. Nested classes with the default (package) access modifier are only accessible to subclasses if the subclass is located in the same package as the superclass. Nested classes with the protected or public access modifier are always inherited by subclasses.
Here is a nested class inheritance example:
class FruitsClass {
class MyFruitsClass {
}
}
public class MyFruitsSubclass extends MyFruitsClass {
public static void main(String[] args) {
MyFruitsSubclass subclass = new MyFruitsSubclass();
MyFruitsClass nested = subclass.new MyFruitsClass ();
}
}
Notice how it is possible to create an instance of the nested class MyFruitsClass which is defined in the superclass (MyFruitsClass) via a reference to the subclass (MyFruitsSubclass). Final Classes and Inheritanc. A class can be declared final. Here is now that looks:
public final class MyFruitsClass {
}
A final class cannot be extended. In other words, you cannot inherit from a final class in Java.
by Jesmin Akther | Jun 6, 2021 | JAVA
Enums in java
An enum is a group of constants. To create an enum, use the enum keyword instead of class or interface. Also separate the constants with a comma. It is use when you have values that you know aren’t going to change such as month days, days, colors, deck of cards, etc. They should be in uppercase letters:
Example
enum Days {
SAT,
SUN,
MON,
TUE,
WED,
THU,
FRI
}
You can access enum constants with the dot syntax:
Days myVar = Days.MON;
Enum is short for “enumerations”, which means “specifically listed”. Enum inside a Class example:
Example
public class Month
{
enum Level
{
SAT,
SUN,
MON,
TUE,
WED,
THU,
FRI
}
public static void main(String[] args)
{
Days myVar = Days.MON;
System.out.println(myVar);
}
}
The output will be:
MON
Enums in a Switch Statement:
Enums are often used in switch statements to check for corresponding values:
Example
enum Level
{
SAT,
SUN,
MON,
TUE,
WED,
THU,
FRI
}
public class Main {
public static void main(String[] args) {
Days myVar = Days.MON;
switch(myVar) {
case SAT:
System.out.println("This is Saturday");
break;
case MON:
System.out.println("This is Monday");
break;
case SUN:
System.out.println("This is Sunday");
break;
}
}
}
The output will be:
This is Monday
Loop Through an Enum:
The enums type has a values() method where they returns an array of all enums constants. This method is useful when you want to loop through the constants of an enums:
Example
for (Days myVar : Days.values()) {
System.out.println(myVar);
}
The output will be:
SAT
SUN
MON
Difference between Enums and Classes
An enums is like a class which have attributes and methods. The only difference is that enum constants are public, static and final that is unchangeable also cannot be overridden. An enum cannot be used to create objects, and it cannot extend other classes though it can implement interfaces.
by Jesmin Akther | Jun 5, 2021 | JAVA
Java Packages & API
In Java, a package is group related classes or a folder in a path (file directory). Generally, packages are used to avoid name conflicts and to write a better supportable code.
Packages are divided into two categories:
- User-defined Packages (create your own packages)
- Built-in Packages (packages from the Java API)
Built-in Packages
The Java API is a library of classes free to use in the Java Development Environment. The library contains components for input, database, programming and so on.
For more details, application programming interface (API) is a list of all classes. These classes are part of the Java development kit (JDK). It includes all Java packages, classes, and interfaces, with their methods, fields, and constructors. These are pre-written classes provide a great amount of functionality to a programmer. A programmer should be aware of these classes and should know how to use them.
Some examples of Java API can be found at Oracle’s website: http://docs.oracle.com/javase/7/docs/api/.
In order to use a class from Java API, one needs to include an import statement at the start of the program.
The API library is divided into packages and classes either import a single or a whole package. When import single package contain class along with its methods and attributes. Also, for a whole package import, contain all the classes that belong to the definite package. To use a class or a package from the library, you need to use the import keyword such as Syntax
import package.name.Class; //for import a single class
import package.name.*; //for import the whole package
Import a Class
When want to use a class, for sample, Scanner class, which is used to get user input, example code:
Example
import java.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of the java.util package. In order to use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation.
What is util?
In Java Package java.util Contains the collections framework, legacy of the collection of various classes, event model, date and time facilities, internationalization, and miscellaneous utility classes, for example, a string tokenizer, a random-number generator, and a bit array.
In our example, we will use the nextLine() method, which is used to read a complete line:
Example
Using the Scanner class to get user input:
import java.util.Scanner;
class Sclass {
public static void main(String[] args) {
Scanner sObj = new Scanner(System.in);
System.out.println("Enter User name");
String userName = sObj.nextLine();
System.out.println("Username is: " + userName);
}
}
OUTPUT
Enter username
hey
Username is: hey
Java Application Programming Interface (API)
For example, in order to use the Scanner class, which allows a program to accept input from the keyboard, one must include the following import statement:
import java.util.Scanner;
The above import statement allows the programmer to use any method listed in the
Scanner class. Another choice for including the import statement is the wildcard option
shown below:
import java.util.*;
This version of the import statement imports all the classes in the API’s java.util package and makes them available to the programmer. If check the API and look at the classes written in the java.util package, you will observe that it includes some of the classes that are used often, such as Arrays, ArrayList, Formatter, Random, and many others. Another Java package that has several commonly used classes is the java.lang package. This package includes classes that are fundamental to the design of Java language. The java.lang package is automatically imported in a Java program and does not need an explicit import statement.
Import a Package
There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes. To import a whole package, end the sentence with an asterisk sign (*). The below example will import all the classes in the java.util package:
Example
import java.util.*;
User-defined Packages
To create own package, Java uses a file system directory to store them. Just like folders on a computer:
Example
└── root
└── mypack
└── MyPackClass.java
To create a package, use the package keyword:
MyPackClass.java
package mypack;
class MyPackClass {
public static void main(String[] args) {
System.out.println("Oh! This is my package !");
}
}
Save the file as MyPackageClass.java, and compile it:
C:\Users\Pc Name>javac MyPackClass.java
Then compile the package:
C:\Users\ Pc Name>javac -d. MyPackClass.java
From this path create notepad to practice your java code until expert.
by Jesmin Akther | Jun 4, 2021 | Assembly Language
Assembly language program practice
In the previous article we have share many basic resources and other compile program with Assembly language. Do and keep practice with assembly helps to gather better knowledge on the language.
Example
section .data ;This statement for Data segment
userMsg db 'Please enter a number: ' ; This is for the user to enter a number
lenUserMsg equ $-userMsg ; This is the length of the message
dispMsg db 'You have enter: '
lenDispMsg equ $-dispMsg
section .bss ;This is Uninitialized data
num resb 5
section .text ;This Code Segment
global _start
_start: ;This is for User prompt
mov eax, 4
mov ebx, 1
mov ecx, userMsg
mov edx, lenUserMsg
int 80h ;Read and store the user input
mov eax, 3
mov ebx, 2
mov ecx, num
mov edx, 5 ;5 bytes (numeric, 1 for sign) of that information
int 80h ;Output the message 'The enter number is: '
mov eax, 4
mov ebx, 1
mov ecx, dispMsg
mov edx, lenDispMsg
int 80h ;Output the number enter
mov eax, 4
mov ebx, 1
mov ecx, num
mov edx, 5
int 80h ; Exit code
mov eax, 1
mov ebx, 0
int 80h
OUTPUT:
Please enter a number:
1234
You have enter:1234
Most assembly language instructions require operands to be processed. An operand address provides the location, where the data to be processed is stored. Some instructions do not require an operand, whereas some other instructions may require one, two, or three operands. Generally, in assembly language an instruction needs two operands, the first operand is the destination, where data in a register or memory location and the second operand is the source. Source contains either the data to be delivered that is immediate addressing or the address that means in register / memory of the data. The source data remains unchanged after the operation.
The three basic modes of addressing are:
- Register addressing
- Immediate addressing
- Memory addressing
Register Addressing:
A register which contains the operand. In this addressing mode this is the first concern. In order to depending upon the instruction, the register may be the first operand, the second operand or both.
For example,
MOV DX, TAX_RATE ; This is the Register in first operand
MOV COUNT, CX ; This is the Register in second operand
MOV EAX, EBX ; This is Both the operands are in registers
As handing out data between registers does not comprise memory, it provides fastest processing of data.
Immediate Addressing:
In an immediate operand, it has a constant value or an expression. Therefore, when an instruction with two operands uses immediate addressing, the first operand may be a register or memory location, and the second operand is an immediate constant. The first operand defines the length of the data.
For example,
BYTE_VALUE DB 150 ; This is A byte value is defined
WORD_VALUE DW 300 ; This statement A word value is defined
ADD BYTE_VALUE, 65 ; This statement An immediate operand 65 is added
MOV AX, 45H ; This statement is Immediate constant 45H is transferred to AX
Direct Memory Addressing:
This is used, when operands are specified in memory addressing mode. In direct access to main memory, usually to the data segment, it is needed. This is a way of addressing where results in slower processing of data. In order to locate the precise location of data in memory, we need the segment start address, which is typically found in the DS register and an offset value. Hence, this offset value is also called effective address. Again, In direct addressing mode, the offset value is definite directly as part of the instruction, indicated by the variable name. The assembler calculates the offset value and maintains a symbol table, which stores the offset values of all the variables used in the program. In direct memory addressing, one of the operands refers to a memory location and the other operand references a register.
For example,
ADD BYTE_VALUE, DL ; This statement is Adds the register in the memory location
MOV BX, WORD_VALUE ; This statement is Operand from the memory is added to register
Direct-Offset Addressing
This addressing mode uses the arithmetic operators to modify an address. For instance, following definitions define tables of data;
A_BYTE_TABLE DB 14, 15, 22, 45 ; This statement is Tables of bytes
A_WORD_TABLE DW 134, 345, 564, 123 ; This statement is Tables of words
The below operations access data from the tables in the memory into registers:
MOV CL, A_BYTE_TABLE [2] ; This is used to Gets the 3rd element of the BYTE_TABLE
MOV CL, A_BYTE_TABLE + 2 ; This is used, Gets the 3rd element of the BYTE_TABLE
MOV CX, A_WORD_TABLE[3] ; This is used, Gets the 4th element of the WORD_TABLE
MOV CX, A_WORD_TABLE + 3 ; This is used , Gets the 4th element of the WORD_TABLE
Indirect Memory Addressing
This addressing mode operates the computer’s capability of Segment like Offset addressing. Normally, the base registers EBX, EBP or BX, BP and the index registers DI, SI, coded within square brackets for memory references, are used for this purpose. Indirect addressing is used for variables containing several elements like, arrays. Starting address of the array is stored in, say, the EBX register.
The following code snippet shows how to access different elements of the variable.
MINE_TABLE TIMES 10 DW 0 ; This is used to Allocates 10 words (2 bytes) each initialized to 0
MOV EBX, [MY_TABLE] ; This is used to Effective Address of MINE_TABLE in EBX
MOV [EBX], 110 ; MINE _TABLE[0] = 110
ADD EBX, 2 ; EBX = EBX +2
MOV [EBX], 123 ; MINE _TABLE[1] = 123
The MOV Instruction
MOV instruction that is used for moving data from one storage space to another. The MOV instruction takes two operands.
The syntax of the MOV instruction is −
The MOV instruction may have one of the following five forms, example statements are given below:
MOV register, register
MOV register, immediate
MOV memory, immediate
MOV register, memory
MOV memory, register
Here, Both of the operands in MOV operation should be of same size so the value of source operand remains unchanged. The MOV instruction reasons ambiguity at times. For example, look at the statements:
MOV EBX, [MINE_TABLE] ; Effective Address of MINE_TABLE in EBX
MOV [EBX], 110 ; MY_TABLE[0] = 110
It is not clear. Here, either you want to move a byte equivalent or you want a word equivalent of the number 110. In such cases, it is wise to use a type specifier. Here is a table shows some of the common type of specifiers:
Type Specifier Bytes addressed
BYTE 1
WORD 2
DWORD 4
QWORD 8
TBYTE 10
Example
There is a program which illustrates some of the concepts discussed in the post. It stores a name ‘ATM SAMSUZZAMAN’ in the data section of the memory, then changes its value to another name ‘Humayon Faridi’ programmatically and displays both the names.
section .text
global _start ;This statement must be declared for linker (ld)
_start: ; This tell linker entry point
;writing the name 'ATM SAMSUZZAMAN'
mov edx,9 ;This is for message length
mov ecx, name ; This is for message to write
mov ebx,1 ; This is for a file descriptor (stdout)
mov eax,4 ; This is system call number (sys_write)
int 0x80 ; This call kernel
mov [name], dword ' Humayon Faridi ' ; Changed the name to Humayon Faridi ;writing the name ‘Humayon Faridi’
mov edx,8 ;This for message length
mov ecx,name ;This is for a message to write
mov ebx,1 ;This is the file descriptor (stdout)
mov eax,4 ;This is the system call number (sys_write)
int 0x80 ;this call kernel
mov eax,1 ;This is system call number (sys_exit)
int 0x80 ;This call kernel
section .data
name db 'ATM SAMSUZZAMAN'
When the above code is compiled and executed, it produces the following result as:
ATM SAMSUZZAMAN Humayon Faridi
by Jesmin Akther | Jun 4, 2021 | Assembly Language
Memory Arrangement or Memory Segments
A segmented memory model splits the system memory into clusters or set of autonomous segments. Each independent segments referenced by pointers located in the segment registers. This is used to contain a specific type of data. One segment is used to hold instruction codes, another segment stores the data elements, and a third segment preserves the program stack. Though there are various memory segments such as
This segment is represented by .data section and the .bss. The .data section is used to declare the memory section, where data elements are stored for the program. A section cannot be extended after the data elements are declared, and it remainders static all over the program.
This segment .bss section is also a static or not change memory section. This section comprises buffers for data to be declared later in the program. This buffer memory is zero-filled.
This is represented by .text section. This defines an area in memory that stores the instruction codes. This is also static or unchangeable or a fixed area.
This segment that is stack contains data values passed to functions and procedures within the program. In order to speed up the processor operations, the processor includes some internal memory storage locations, called registers. Registers store data elements for processing without taking to access the memory. A partial number of registers are built into the processor chip.
Processor Registers
There are ten 32-bit and six 16-bit processor registers in IA-32 architecture. The registers are grouped into three categories, for example
- General registers,
- Control registers,
- Segment registers.
The general registers are further divided into the following categorise:
- Data registers,
- Pointer registers, and
- Index registers.
- Data Registers
There are four 32-bit data registers which are used for arithmetic, logical, and other operations. These 32-bit registers can be used in three ways, such as complete 32-bit data registers: EAX, EBX, ECX, EDX. Here, Lower halves of the 32-bit registers can be used as four 16-bit data registers: AX, BX, CX and DX. Lower and higher halves of the above-mentioned four 16-bit registers can be used as eight 8-bit data registers: AH, AL, BH, BL, CH, CL, DH, and DL.
Data Registers
Some of these data registers have specific use in arithmetical operations.
AX is the primary accumulator where this is used in input/output and most arithmetic instructions. For instance , in multiplication operation, one operand is stored in EAX or AX or AL register according to the size of the operand.
BX – is known as the base register, as it could be used in indexed addressing.
CX- is known as the count register, as the ECX, CX registers store the loop count in iterative operations.
DX- is known as the data register. This register is also used in input/output operations. It is also used with AX register along with DX for multiply and divide operations involving large values.
Pointer Registers
The pointer registers are 32-bit EIP, ESP, and EBP registers and corresponding 16-bit right portions IP, SP, and BP. There are three categories of pointer registers:
Instruction Pointer (IP):
The 16-bit IP register stores the offset address of the next instruction to be executed. IP in association with the CS register gives the complete address of the current instruction in the code segment.
Stack Pointer (SP):
The 16-bit SP register provides the offset value within the program stack. SP in association with the SS register (SS:SP) refers to be current position of data or address within the program stack.
Base Pointer (BP):
The 16-bit BP register mainly helps in referencing the parameter variables passed to a subroutine. The address in SS register is combined with the offset in BP to get the location of the parameter. BP can also be combined with DI and SI as base register for special addressing.
Pointer Registers
Index Registers
The 32-bit index registers, ESI and EDI, and their 16-bit rightmost portions. SI and DI, are used for indexed addressing and sometimes used in addition and subtraction. There are two sets of index pointers:
- Source Index (SI) − It is used as source index for string operations.
- Destination Index (DI) − It is used as destination index for string operations.
Index Registers
Control Registers
The 32-bit instruction pointer register and the 32-bit flags register combined are considered as the control registers. Many instructions involve comparisons and mathematical calculations and change the status of the flags and some other conditional instructions test the value of these status flags to take the control flow to other location. The common flag bits are:
Overflow Flag (OF): This flag is indicating the overflow of a high-order bit (leftmost bit) of data after a signed arithmetic operation.
Direction Flag (DF): This flag is determining left or right direction for moving or comparing string data. When the DF value is 0, the string operation takes left-to-right direction and when the value is set to 1, the string operation takes right-to-left direction.
Interrupt Flag (IF): This flag is governs whether the external interrupts like keyboard entry, etc., are to be ignored or processed. It disables the external interrupt when the value is 0 and enables interrupts when set to 1.
Trap Flag (TF) ): This flag is allows setting the operation of the processor in single-step mode. The DEBUG program we used sets the trap flag, so we could step through the execution one instruction at a time
Sign Flag (SF) ): This flag is shows the sign of the result of an arithmetic operation. This flag is set according to the sign of a data item following the arithmetic operation. The sign is indicated by the high-order of leftmost bit. A positive result clears the value of SF to 0 and negative result sets it to 1.
Zero Flag (ZF) ): This flag is indicates the result of an arithmetic or comparison operation. A nonzero result clears the zero flag to 0, and a zero result sets it to 1.
Auxiliary Carry Flag (AF): This flag is containing the carry from bit 3 to bit 4 following an arithmetic operation; used for specialized arithmetic. The AF is set when a 1-byte arithmetic operation causes a carry from bit 3 into bit 4.
Parity Flag (PF): This flag is indicating the total number of 1-bits in the result obtained from an arithmetic operation. An even number of 1-bits clears the parity flag to 0 and an odd number of 1-bits sets the parity flag to 1.
Carry Flag (CF): This flag is containing the carry of 0 or 1 from a high-order bit (leftmost) after an arithmetic operation. It also stores the contents of last bit of a shift or rotate operation.
Segment Registers
Segments are specific areas defined in a program for containing data, code and stack. There are three main segments:
- Code Segment: This flag is containing all the instructions to be executed. A 16-bit Code Segment register or CS register stores the starting address of the code segment.
- Data Segment: This flag is contains data, constants and work areas. A 16-bit Data Segment register or DS register stores the starting address of the data segment.
- Stack Segment: This flag is containing data and return addresses of procedures or subroutines. It is implemented as a ‘stack’ data structure. The Stack Segment register or SS register stores the starting address of the stack.
Apart from the DS, CS and SS registers, there are other extra segment registers – ES (extra segment), FS and GS, which provide additional segments for storing data. These are combines the segment address in the segment register with the offset value of the location. Look at the following simple program to understand the use of registers.
Example
The use of registers in assembly programming. This program displays 7 stars on the screen with a message:
section .text
global _start ; This is must be declared for linker (gcc)
_start: ; This tell linker entry point
mov edx,len ; This is a message length
mov ecx,msg ; This is a message to write
mov ebx,1 ; This is a file descriptor (stdout)
mov eax,4 ; This is system call number (sys_write)
int 0x80 ; This is call kernel
mov edx,7 ; This is message length
mov ecx,s2 ; This is message to write
mov ebx,1 ; This is a file descriptor (stdout)
mov eax,4 ; This is system call number (sys_write)
int 0x80 ; This is call kernel
mov eax,1 ; This is system call number (sys_exit)
int 0x80 ; This is call kernel
section .data
msg db 'Displaying 7 stars',0xa ;a message
len equ $ - msg ;length of message
s2 times 7 db '*'
OUTPUT
Displaying 7 stars
*******
by Jesmin Akther | May 31, 2021 | Assembly Language
Environment Setup
Assembly language is dependent upon the instruction set and the architecture of the processor. There are many good assembler programs, for example
- NASM: It is an operating system independent assembler. One of the two widely used Linux assemblers and the other GNU
- The GNU assembler (GAS): The syntax differs significantly in many ways from
- MASM (Microsoft Assembler): MASM syntax is a standard. So, almost always understood by other x86 assemblers TASM, CHASM, A386, etc. The syntax has some significant defects that makes coding error hence many of them are rectified in NASM.
- Borland Turbo Assembler (TASM)
Installing NASM
It could be used on both Linux and Windows, can download from various web sources. All are well documented. While installing Linux, if “Development Tools” is chacked, NASM installed along with the Linux operating system. For checking have NASM installed, take the following steps
- Open a Linux terminal.
- Type where is nasm and press ENTER.
We use a online compiler of assymbly language in this blog. Go to this link – https://www.jdoodle.com/compile-assembler-nasm-online/
Basic of NASM assembler
Character Set: Letters a..z; A..Z; ()
Digits: 0.9
Special Chars: ? _ @ $ . ~
- NASM is case-sensitive with respect to labels and variables
- It is not case-sensitive with respect to keywords, mnemonics, register names, directives, etc.
- Special Characters.
Write a basic assembly program
Generally, an assembly program can be divided into three sections, such as
- The data section,
- The bss section, and
- The text section.
The data Section
The section is used for declaring data or constants which are not modify at runtime. Various constant values, file names, or buffer size, etc. are declare in this section.
The syntax for declaring data section is “section.data”
The bss Section
The section is used for declaring variables. The syntax for declaring bss section is “section.bss”
The text section
This section must be begun with the declaration global _start, which tells the kernel where the program execution begins. The section is used for care the actual code.
The syntax for declaring text section is
section.text
global _start
_start:
Comments
AL comment begins with a semicolon (;). It may contain any printable character including blank. It can appear on a line by itself, like below
; This program displays a message on screen
or, on the same line along with an instruction, like
add eax, ebx ; this statement state as adds ebx to eax
Assembly Language Statements
Assembly language programs consist of three types of statements, for example
- Executable instructions or instructions:
The executable instructions or simply instructions tell the processor what to do. Each instruction consists of an operation code (opcode). Each executable instruction generates one machine language instruction.
- Assembler directives or pseudo-ops
The assembler directives or pseudo-ops tell the assembler about the various aspects of the assembly process. These are non-executable and do not generate machine language instructions.
- macros
In AL macros are basically a text substitution mechanism.
Syntax of Assembly Language(AL) Statements
Assembly language statements are entered one statement per line. Each statement follows the following format:
[label] mnemonic [operands] [;comment]
A basic instruction has two parts, the first one is the name of the instruction (or the mnemonic), which is to be executed, and the second are the operands or the parameters of the command. Here the fields in the square brackets are optional.
Following are some examples of typical assembly language statements :
INC COUNT ; this statement state as Increment the memory variable COUNT
MOV TOTAL, 48 ; this statement state as Transfer the value 48 in the ; memory variable TOTAL
ADD AH, BH ; this statement state as Add the content of the BH register into the AH register
AND MASK1, 128 ; this statement state as Perform AND operation on the variable MASK1 and 128
ADD MARKS, 10 ; this statement state as Add 10 to the variable MARKS
MOV AL, 10 ; this statement state as Transfer the value 10 to the AL register
The Hello World Program in Assembly Language
The following assembly language code displays the string ‘Hello World’ on the screen −
section .text
global _start ;This is must be declared for linker (ld)
_start: ; this statement tells linker entry point
mov edx,len ; this state as message length
mov ecx,msg ; this statement state as message to write
mov ebx,1 ; this statement state as file descriptor (stdout)
mov eax,4 ; this statement state as system call number (sys_write)
int 0x80 ;call kernel
mov eax,1 ; this statement state as system call number (sys_exit)
int 0x80 ;call kernel
section .data
msg db 'Hello, world!', 0xa ;string to be printed
len equ $ - msg ;length of the string
OUTPUT:
Hello, world!
Now Compiling and Linking an AL Program in NASM. Make sure you have set the path of nasm and ld binaries in your PATH environment variable. Now, take the following steps for compiling and linking the above program:
- Type the above code using a text editor and save it as hello.asm.
- Make sure that you are in the same directory as where you saved hello.asm.
- To assemble the program, type nasm -f elf hello.asm
- If there is any error, you will be prompted about that at this stage. Otherwise, an object file of your program named hello.o will be created.
- To link the object file and create an executable file named hello, type ld -m elf_i386 -s -o hello hello.o
- Execute the program by typing ./hello
- If you have done everything correctly, it will display ‘Hello, world!’ on the screen.
if replace the section keyword with segment by follow code:
segment .text
global _start ;This is must be declared for linker (ld)
_start: ; this statement tells linker entry point
mov edx,len ; this state as message length
mov ecx,msg ; this statement state as message to write
mov ebx,1 ; this statement state as file descriptor (stdout)
mov eax,4 ; this statement state as system call number (sys_write)
int 0x80 ;call kernel
mov eax,1 ; this statement state as system call number (sys_exit)
int 0x80 ;call kernel
segment .data
msg db 'Hello, world!', 0xa ;string to be printed
len equ $ - msg ;length of the string
OUTPUT
Hello, world!
by Jesmin Akther | May 31, 2021 | Assembly Language
What is Assembly Language?
Assembly Language (AL) is one line of code translates to one machine instruction. Every computer has a microprocessor that achieves the computer’s arithmetical, logical, and control actions. ALs are NOT machine-independent that is each different machine or processor has a different machine languages. Any particular machine can have more than one assembly language. This is a low-level language that represents various instructions in symbolic code and a clearer form. A processor understands only machine language instructions, which are strings of 1’s and 0’s. Each set of processors has own instructions set for handling numerous operations such as getting input from keyboard, displaying information on screen and performing many works where each set of instructions are named ‘machine language instructions’.
Assembly language makes one aware of:
- How OS, processor, and BIOS programs interface mutually;
- How data is represented in memory with other devices;
- How the processor accesses and executes instruction;
- How each instruction access to process data;
- How a program accesses external device
Assembly Language Advantages:
- The language requires less memory and execution time;
- It allows hardware-specific complex jobs in an easier way;
- It is suitable for time-critical trades;
- It is most suitable for writing interrupt service routines along other memory resident programs.
A computer Hardware Basic Features
The main internal hardware of a PC consists of processor, memory, and registers. Registers are processor components where data and address are hold. To execute a program, the system copies it from the external device into the internal memory. The processor executes the program instructions.
The fundamental unit of computer storage is a bit; it could be ON (1) or OFF (0) and a group of 8 bits and makes a byte on most of the modern computers.
The parity bit is used to make the number of bits in a byte odd. If the parity is even, the system assumes that there had been a parity error (though rare), which might have been caused due to hardware fault or electrical disturbance.
The processor supports data sizes:
- Word: Contain a 2-byte data item
- Doubleword: Consist of a 4-byte (32 bit) data item
- Quadword: Contain an 8-byte (64 bit) data item
- Paragraph: Have a 16-byte (128 bit) area
- Kilobyte: Have 1024 bytes
- Megabyte: Have 1,048,576 bytes
Binary Number System
Every number system uses positional notation. Each position is power of the base, which is 2 for binary number system, and these powers begin at 0 and increase by 1.
The positional values for an 8-bit binary number, with all bits are set ‘ON’
Bit value |
1 |
1 |
1 |
1 |
1 |
1 |
1 |
1 |
Position value as a power of base 2 |
128 |
64 |
32 |
16 |
8 |
4 |
2 |
1 |
Bit number |
7 |
6 |
5 |
4 |
3 |
2 |
1 |
0 |
The value of a binary number is based on the presence of 1 bits and their positional value. So, the value of a given binary number is:
1 + 2 + 4 + 8 +16 + 32 + 64 + 128 = 255
which is same as 28 – 1.
Hexadecimal Number System
Hexadecimal number system uses base 16 range from 0 to 15 each digit. The letters A through F is represented corresponding to decimal values 10 through 15.
Decimal number |
Binary representation |
Hexadecimal representation |
0 |
0 |
0 |
1 |
1 |
1 |
2 |
10 |
2 |
3 |
11 |
3 |
4 |
100 |
4 |
5 |
101 |
5 |
6 |
110 |
6 |
7 |
111 |
7 |
8 |
1000 |
8 |
9 |
1001 |
9 |
10 |
1010 |
A |
11 |
1011 |
B |
12 |
1100 |
C |
13 |
1101 |
D |
14 |
1110 |
E |
15 |
1111 |
F |
To convert a binary number to its hexadecimal equivalent, break it into groups of 4 consecutive groups each, starting from the right, and write those groups over the corresponding digits of the hexadecimal number.
Example − Binary number 1000 1100 1101 0001 is equivalent to hexadecimal – 8CD1
To convert a hexadecimal number to binary, just write each hexadecimal digit into its 4-digit binary equivalent.
Example − Hexadecimal number FCD7 is equivalent to binary – 1111 1100 1101 0111
Binary Arithmetic
The following table illustrates four simple rules for binary addition −
(i) |
(ii) |
(iii) |
(iv) |
|
|
|
1 |
0 |
1 |
1 |
1 |
+0 |
+0 |
+1 |
+1 |
=0 |
=1 |
=10 |
=11 |
Rules (iii) and (iv) show a carry of a 1-bit into the next left position.
Example
Decimal |
Binary |
60 |
00111100 |
+42 |
00101010 |
102 |
01100110 |
A negative binary value is expressed in two’s complement notation. According to this rule, to convert a binary number to its negative value is to reverse its bit values and add 1.
Example
Number 53 |
00110101 |
Reverse the bits |
11001010 |
Add 1 |
00000001 |
Number -53 |
11001011 |
To subtract one value from another, convert the number being subtracted to two’s complement format and add the numbers.
Example
Subtract 22 from 33
Number 33 |
00100001 |
Number 22 |
00010110 |
Reverse the bits of 42 |
11101001 |
Add 1 |
00000001 |
Number -22 |
00010110 |
33 – 22 = 11 |
00001011 |
Overflow of the last 1 bit is lost.
Addressing Data in Memory
The processor which the controls process of execution of instructions is denoted as the fetch-decode-execute cycle or the execution cycle. It consists of three continuous steps:
- Fetching the instruction from memory
- Decoding or identifying the instruction
- Executing the instruction
The processor may access one or more bytes of memory at a time. Let us consider a hexadecimal number 0225H. This number will require two bytes of memory. The high-order byte or most significant byte is 02 and the low-order byte is 25. The processor stores data in reverse-byte sequence, i.e., a low-order byte is stored in a low memory address and a high-order byte in high memory address. So, if the processor brings the value 0225H from register to memory, it will transfer 25 first to the lower memory address and 02 to the next memory address.
There are two kinds of memory addresses:
- Absolute address: It is a direct reference of specific location.
- Segment address (or offset) : It is a starting address of a memory segment with the offset value.