Overview of Java and Its Applications

Java is a versatile and widely-used programming language that has left an indelible mark on the world of software development. Since its inception in the mid-1990s, Java has grown to become one of the most popular and influential programming languages. Its robustness, platform independence, and wide range of applications make it a cornerstone in the world of software development.

A Brief History of Java:

Java was created by James Gosling, Mike Sheridan, and Patrick Naughton at Sun Microsystems in the early 1990s. It was initially designed as a language for consumer electronic devices, but its founders quickly recognized its potential for general-purpose programming. In 1995, Sun Microsystems officially released Java, and it rapidly gained traction due to its “Write Once, Run Anywhere” capability, which allows developers to write code that can be executed on any platform that supports Java.

Key Features of Java:

  1. Platform Independence: One of Java’s most significant advantages is its ability to run on multiple platforms without modification. This is achieved through the use of the Java Virtual Machine (JVM), which interprets Java bytecode on the target platform. As a result, Java is known for its “write once, run anywhere” philosophy.
  2. Object-Oriented: Java is an object-oriented programming language, which promotes modularity, reusability, and ease of maintenance. It allows developers to create objects, which encapsulate data and behavior, making code more organized and understandable.
  3. Robust and Secure: Java’s strict type checking, automatic memory management, and exception handling features contribute to the language’s robustness and security. It helps prevent common programming errors, making Java applications more reliable.
  4. Multi-threading: Java provides built-in support for multithreading, allowing developers to create concurrent, efficient, and responsive applications. This is crucial for tasks such as parallel processing and creating responsive user interfaces.
  5. Rich Standard Library: Java comes with an extensive standard library that provides a wide range of classes and methods for common tasks, from data manipulation to networking. This reduces the need for developers to reinvent the wheel and accelerates development.

Applications of Java:

  1. Desktop Applications: Java is often used to build cross-platform desktop applications. Tools like JavaFX provide a rich set of UI components for creating visually appealing and responsive applications. Popular applications such as the Eclipse IDE and Azureus (a BitTorrent client) are written in Java.
  2. Web Development: Java is widely used in web development. Java Enterprise Edition (Java EE) provides a robust platform for building scalable, secure, and enterprise-level web applications. Frameworks like Spring and JavaServer Faces (JSF) are popular choices for web development.
  3. Mobile Applications: Android, the world’s most popular mobile operating system, is based on Java. Android app developers use Java (or Kotlin, a language closely related to Java) to create applications for smartphones and tablets.
  4. Enterprise Software: Many large-scale enterprises rely on Java for building mission-critical software. Java’s stability, security, and support for distributed computing make it an excellent choice for creating backend systems, middleware, and data processing applications.
  5. Embedded Systems: Java is used in embedded systems and Internet of Things (IoT) devices where platform independence is crucial. It allows developers to write code that can run on diverse hardware with minimal modifications.
  6. Scientific and Research Applications: Java is also utilized in scientific and research domains. Its libraries, such as Apache Commons Math and Weka, make it a viable choice for data analysis, simulations, and scientific computing.

Conclusion:

Java’s versatility, portability, and vast ecosystem of libraries and frameworks make it a compelling choice for a wide range of applications, from building mobile apps to powering large-scale enterprise systems. As one of the most enduring and influential programming languages in history, Java continues to evolve, adapting to the ever-changing demands of the software development landscape. Whether you’re a beginner learning to code or a seasoned professional, Java remains an essential language to master in the world of programming.

Difference Between JSON vs XML,How to use in the Programming Language.

The JSON vs XML,And basically used in the Programming Language because of simplicity and structured data format.Basically JSON and XML format is useful in sending data over network between different web services because of its simplicity in representation of data.Image result for xml vs json

Those who are the new to these format they can try  for the xml because of its easy user friendly tag structure.Tag is like HTML language tag but no hard fast rules for tag Names,Their is not predefined tag names.You can create your own tag names for your ease of use.

Difference between JSON(Java Script Object Notation) and XML(eXtensible Markup Language). The major difference between are as follows.

No. JSON XML
1) JSON stands for JavaScript Object Notation. XML stands for eXtensible Markup Language.
2) JSON is simple to read and write. XML is less simple than JSON.
3) JSON is easy to learn. XML is less easy than JSON.
4) JSON is data-oriented. XML is document-oriented.
5) JSON doesn’t provide display capabilities. XML provides the capability to display data because it is a markup language.
6) JSON supports array. XML doesn’t support array.
7) JSON is less secured than XML. XML is more secured.
8) JSON files are more human readable than XML. XML files are less human readable.
9) JSON supports only text and number data type. XML support many data types such as text, number, images, charts, graphs etc. Moreover, XML offeres options for transferring the format or structure of the data with actual data.

JSON Example

{“employees”:[
{ “firstName”:”John”, “lastName”:”Doe” },
{ “firstName”:”Anna”, “lastName”:”Smith” },
{ “firstName”:”Peter”, “lastName”:”Jones” }
]}

XML Example

<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>

 

If you are finding any difficulties with these format with any language you can give your issues in the comment section of Difference Between JSON vs XML,How to use in the Programming Language.

Selenium Wait Implicit Wait Explicit Wait Fluent Wait

Selenium Wait  Command is used in Selenium WebDriver to wait a particular amount of time defined by user.Selenium Wait can be divided into two categories Implicit wait and Explicit wait and another type of hybrid wait is Fluent Wait.In the implicit wait selenium WebDriver wait for a fixed amount of time before executing next command or throwing an exception . Where in all other Selenium Wait type of  WebDriver will execute the next line of command if it found that element.

Implicit wait

This is the Selenium Wait statement gives command to the browser to wait for an certain period of time in that time if the element is located in the page the execution will take place or else the “WebDriver wait” for a specific amount of time to check whether the element is located on that page or not.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

[codesyntax lang=”java”]

package tesng;
public class robot { protected WebDriver driver;
 @Test public void tutorials() throws InterruptedException { 
System.setProperty("webdriver.gecko.driver", "D:\\geckodriver.exe");
 driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 
driver.get("http://www.marketwatch.com/"); System.out.println(driver.findElement(By.linkText("The Moneyologist")).getTagName()); } }

[/codesyntax]

In above example  the WebDriver wait for 10 Second to find the link text is present or not.

Note for implicit-From Selenium 3.0.1 release the WebDriver is not throwing the exception “Element not Found Exception” instead of  it is waiting for element to be present.

Explicit wait

An explicit wait is a wait statement let the user to define for a certain condition and predefined time to wait for  proceeding further in the code. The Explicit wait wait for an particular event to occur in that period of time to perform any operation on that  web element.

 

   WebElement DynamicElement = (new WebDriverWait(driver, 10))
                .until(ExpectedConditions.presenceOfElementLocated(By.xpath(".//input[@type='text']")));

[codesyntax lang=”java”]

package tesng;

public class explicit_wait {    
 protected WebDriver driver;    
 @Test     public void guru99tutorials() throws InterruptedException {   
      System.setProperty("webdriver.gecko.driver", "D:\\geckodriver.exe");    
     driver = new FirefoxDriver();        driver.get("http://www.google.co.in");   
      WebElement DynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.xpath(".//input[@type='text']")));     } }

[/codesyntax]

The WebDriver will for a  maximum 10 second to check the presence of the element located by xpath if in between 10 seconds the driver is finding that element it will execute the next step.

 

Selenium Fluent Wait

Fluent Wait is an special type of Selenium Wait used to find the object when the object is dynamic in nature. It will check the presence of element in particular interval time and will handle exception by its own if the element is not currently visible.

We can use this Selenium Fluent Wait in the scenarios where we do not sure whether the element is visible or not. If the element is visible we will perform operation in it if not visible the fluent wait will handle the error by its own.

In this bellow example i have taken 2 second  for the presence of element and in each 250 millisecond it will check whether the  element is visible or not till end of 2 second by Selenium Fluent Wait.

Syntax-
Driver declaration
Waiting Time setting in driver
Function declaration and function definition(With driver and web element as parameter )
Function call

Example-

 

[codesyntax lang=”java”]

FluentWait wait=new FluentWait(driver);
wait.poolingEvery(250,TimeUnit.MILISECONDS);
wait.withTimeout(2, TimeUnit.SECONDS);
wait.ignoring(TimeoutException.class);
Function<WebDriver, Boolean> function = new Function<WebDriver, Boolean>() {
public Boolean apply(WebDriver arg) {
WebElement element = arg
.findElement(By.xpath("//div[contains(text(),'You already have a Mailbox named')]"));
if (element.isDisplayed()) {
System.out.println("Found");
arg.findElement(By.xpath("//button[@class='btn pull-right create-toggle']")).click();
return true;
} else {
System.out.println("Not Found");
return false;
}
}
};
wait.until(function);

[/codesyntax]

Thread.Sleep(Time)

Thread.Sleep is the worst method for “Selenium Wait” so we do not advise to use this type of wait in the program unless until u need this. This Thread.Sleep() will pause your java program for an specific duration.

Code

Thread.Sleep(1000);

All the Selenium Wait methods we are discuses above are need for different time in Selenium WebDriver So please use the require Selenium Wait for your definite purpose.

Polymorphism in Java Static Polymorphism/Compile time polymorphism vs Dynamic Polymorphism/Run time Ploymorphism

Polymorphism in the java as the word poly means “More than one” and morph ism means “Functionality”  is also applicable in java,where the function behave the more than one way, With same function name and different parameter.


For instance, let’s consider a class Animal and let Cat be a subclass of Animal. So, any cat IS animal. Here, Cat satisfies the IS-A relationship for its own type as well as its super class Animal.

Note: It’s also legal to say every object in Java is polymorphic in nature, as each one passes an IS-A test for itself and also for Object class.

Static Polymorphism/Compile time polymorphism:

In Java, static polymorphism is achieved through method overloading. Method overloading means there are several methods present in a class having the same name but different types/order/number of parameters.

At compile time, Java knows which method to invoke by checking the method signatures.  So, this is called compile time polymorphism or static binding. The concept will be clear from the following example:

class DemoOverload{

    public int add(int x, int y){  //method 1

    return x+y;

    }

    public int add(int x, int y, int z){ //method 2

    return x+y+z;

    }

    public int add(double x, int y){ //method 3

    return (int)x+y;

    }

    public int add(int x, double y){ //method 4

    return x+(int)y;

    }

}

class Test{

    public static void main(String[] args){

    DemoOverload demo=new DemoOverload();

    System.out.println(demo.add(2,3));      //method 1 called

    System.out.println(demo.add(2,3,4));    //method 2 called

    System.out.println(demo.add(2,3.4));    //method 4 called

    System.out.println(demo.add(2.5,3));    //method 3 called

    }

}

In the above example, there are four versions of add methods. The first method takes two parameters while the second one takes three. For the third and fourth methods there is a change of order of parameters.  The compiler looks at the method signature and decides which method to invoke for a particular method call at compile time.

Dynamic Polymorphism/Run time Ploymorphism:

Suppose a sub class overrides a particular method of the super class. Let’s say, in the program we create an object of the subclass and assign it to the super class reference. Now, if we call the overridden method on the super class reference then the sub class version of the method will be called.

Have a look at the following example.

class Vehicle{

    public void move(){

    System.out.println(“Vehicles can move!!”);

    }

}

class MotorBike extends Vehicle{

    public void move(){

    System.out.println(“MotorBike can move and accelerate too!!”);

    }

}

class Test{

    public static void main(String[] args){

    Vehicle vh=new MotorBike();

    vh.move();    // prints MotorBike can move and accelerate too!!

    vh=new Vehicle();

    vh.move();    // prints Vehicles can move!!

    }

}

It should be noted that in the first call to move(), the reference type is Vehicle and the object being referenced is MotorBike. So, when a call to move() is made, Java waits until runtime to determine which object is actually being pointed to by the reference.  In this case, the object is of the class MotorBike. So, the move() method of MotorBike class will be called. In the second call to move(), the object is of the class Vehicle. So, the move() method of Vehicle will be called.

As the method to call is determined at runtime, this is called dynamic binding or late binding.

If you have any further clarification on this topic please give comment below post Polymorphism in Java Static Polymorphism/Compile time polymorphism vs Dynamic Polymorphism/Run time Ploymorphism

Access Modifiers in Java ,How Access Level Helps in Inheritance and Polymorphism

In java their are 4 access modifiers public,protected,<default>,<package>,private

  • Public-Public  is the access modifiers which shows the highest visibility any class member declare as public can be visible
    1.Within the class.
    2.Within the package.
    3.Outside the package.
  • Protected-Any class member declare as protected are visible
    1.Within the class.
    2.Within the package.
    3.Out side the package but only in the case of is-a relationship.
  • Default-
    If we do not any access modifier to declare then the class member is consider as default member.
    1.Default member are visible within the class
    2.Within the package.
  • Private-
    Private is the access modifier which shows the least visibility if we declare any member as private then it is visible
    1.Only within that classes.

Understanding all java access modifiers

Let’s understand the access modifiers by a simple table.

Access Modifier within class within package outside package by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

If you have any further clarification on Access Modifiers in Java ,How Access Level Helps in Inheritance and Polymorphism please give comment bellow

Java Autoboxing and Unboxing with examples

Java 1.5 introduced a special feature of auto conversion of primitive types to the corresponding Wrapper class and vice versa.

Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.

Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double etc.

Primitive type Wrapper classboolean         Booleanbyte            Bytechar            Characterfloat           Floatint             Integerlong            Longshort           Shortdouble          Double

When does the autoboxing and unboxing happens in Java

Autoboxing

: Lets see few cases with examples, where autoboxing happens.
Case 1: When a method is expecting a wrapper class object but the value that is passed as parameter is a primitive type. For example in the below code, the method myMethod() is expecting an object of Integer wrapper class, however we passed a primitive int type. The program ran fine as compiler does the autoboxing (conversion of int to Integer)

class AutoboxingExample1{   public static void myMethod(Integer num){        System.out.println(num);   }   public static void main(String[] args) {       /* passed int (primitive type), it would be         * converted to Integer object at Runtime        */        myMethod(2);   }}

Output:

2

Case 2: When at some point of time, you are assigning a primitive type value to an object of its wrapper class. For example: The below statements are valid because compiler does the autoboxing at runtime.

Integer inum = 3; //Assigning int to Integer: AutoboxingLong lnum = 32L; //Assigning long to Long: Autoboxing

Case 3: When dealing with collection framework classes:

ArrayList<Integer> arrayList = new ArrayList<Integer>();arrayList.add(11); //Autoboxing – int primitive to IntegerarrayList.add(22); //Autoboxing

Here ArrayList class is expecting an Integer wrapper class object but we are providing int primitive.

Unboxing

Case 1: Method is expecting Integer object (parameter) but we have supplied int. Auotmatic conversion(unboxing) happened that converted Integer to int.

class UnboxingExample1{   public static void myMethod(int num){        System.out.println(num);   }   public static void main(String[] args) {                Integer inum = new Integer(100);                /* passed Integer wrapper class object, it          * would be converted to int primitive type          * at Runtime         */        myMethod(inum);    }}

Output:

100

Case 2: Assignments

Integer inum = new Integer(5);int num = inum; //unboxing object to primitive conversion

Case 3: While dealing with collection classes:

ArrayList arrayList = new ArrayList()int num = arrayList.get(0); // unboxing because get method returns an Integer object

What happens behind the scenes?

In the above section we learnt how java compiler performs automatic conversion between primitive type and corresponding Wrapper objects. Lets discuss what compiler actually does during autoboxing and unboxing. The best way to understand this is to compare things before java 1.5 and after java 1.5 (boxing and unboxing introduced in java 1.5).

Autoboxing:
What we see:

Integer number = 100;

What compiler does (or what we used to do before java 1.5):

Integer number = Integer.valueOf(100);

Unboxing:
What we see:

Integer num2 = new Integer(50);int inum = num2;

What compiler does:

Integer num2 = new Integer(50);int inum = num2.intValue();

Similar things happen with the other wrapper classes and primitive types such as long, double, short etc.

Few things you should take care:

Do not mix primitives and objects while doing comparisons. You might get unpredictable results for such comparisons. Better thing to do is: compare object with objects (using equals() method) and compare primitive with primitives(using logical operators such as “==”, “<” etc).