Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to display information about available fonts in Java Swing API

Program to display available fonts :
package com.hubberspot.graphics.example;

import java.awt.*;
import javax.swing.*;

public class FontsInfo
{
  JFrame frame;
  JTextArea textarea;

  FontsInfo()
  {
    frame = new JFrame();
    frame.setLayout(new FlowLayout());
    textarea = new JTextArea();
  
    String[] font = GraphicsEnvironment
    .getLocalGraphicsEnvironment()
   .getAvailableFontFamilyNames();
  
    String temp = "";
  
    for (String name : font)
    {  
      temp = temp + name+"\n";
    }   
  
    textarea.setText(temp);
  
    frame.add(textarea);
    frame.setTitle("Welcome to Hubberspot!.");
    frame.setSize(300,600);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

  public static void main(String[] args)
  {
    new FontsInfo(); 
  }
}

Output of the program :


How to use ArrayList in Java with example ?.


ArrayList is a simple Collection which is provided by the Java Collection Framework API. The class ArrayList is dynamic implementation of an array. ArrayList is like an array which can grow dynamically.


Program to demonstrate how to implement ArrayList class in java.util.*; package along with its operations :

package com.hubberspot.collections.example;

import java.util.*;

public class ArrayListExample 
{
   public static void main(String args[]) 
   {
      ArrayList list = new ArrayList();
      
      System.out.println("Initial size of list :" +
        " " + list.size());
     
      list.add("A");
      list.add("B");
      list.add("C");
      list.add("D");
      list.add("E"); 
      list.add("F");
      list.add(1, "1");

      System.out.println("Size after addition :" +
        " " +list.size());

      System.out.println("Contents of list: " + list);
      
      for(Object str : list)
        System.out.println(str);
      
      list.remove("F");
      list.remove(2);

      System.out.println("Size of after deletion : "
                + list.size());
      System.out.println("Contents of list : " + list);
 } 
}


Output of the program :


How to add a Button to a Frame using Swing API in Java ?

Program to demonstrate adding of Button to a Frame

package com.hubberspot.awtSwing.example;

import java.awt.FlowLayout;
import javax.swing.*;

public class AddButtonToFrame
{
  JFrame frame;
  JButton button;
 
  AddButtonToFrame()
  {
 frame = new JFrame("Welcome to HubberSpot Frame");
 button = new JButton("Click Me!");
 frame.setSize(200,100);
 frame.setLayout(new FlowLayout());
 frame.add(button);
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setVisible(true);
  }
  
  public static void main(String[] args)
 {
 new AddButtonToFrame();
 }
}
Output of the program :


How to Create a Simple Frame using Swing API in Java?.


In order to create our Simple frame using Swing Application Programming Interface in Java , we have to deal with JFrame class in Java , present in the package javax.swing.* ;. This program will display just the title on the window frame after running the program.


Program to demonstrate Simple Frame creation using Swing API in Java

package com.hubberspot.awtSwing.example;

import javax.swing.*;

public class SimpleFrame
{
  JFrame frame;
  SimpleFrame()
  {
    frame = new JFrame("Welcome to HubberSpot frame");
    frame.setSize(200,100);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
   }
  public static void main(String[] args)
  {
 new SimpleFrame();
  }
}

Output of the program :





















The output of the program is the simple GUI window having close , minimize and maximixe buttons at the top right of the frame . The window component is a simple frame having nothing to display . The frame in above example will contain a simple window having title displayed as : “ Welcome to HubberSpot frame ” .

How to add components and event handling to a Java Applet ?.

Program to demonstrate an Applet with components and event handling
package com.hubberspot.applet.example;

import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/*


 */

public class AddComponentToApplet extends Applet {
  JPanel panel;
  JTextField textField ;
  String print;

  public void init() {
 textField = new JTextField(18);
 add(textField);
 addMouseListener(new MouseAdapter(){
  
 public void mouseClicked(MouseEvent event) {
    print = "Mouse Clicked: X = " + event.getX()
      + " Y = " + event.getY();
    textField.setText(print);
 }
  });

 addMouseMotionListener(new MouseMotionAdapter(){
    
 public void mouseMoved(MouseEvent event) {
    print = "Mouse Moved: X = " + event.getX()
   + " Y = " + event.getY();
    textField.setText(print);
 }
  });
 }

}
Output of the program :


Program to demonstrate the use of Abstract class and methods in Java

Abstract class have their own importance in Java. Abstract classes works on the principle of generalization. They are created just that some other class extends them and implement its abstract methods. These classes cannot be instantiated and cannot have objects of their own. These classes works really well when it comes to Polymorphism. Generally concept of Polymorphism deals with single thing having more than one form. The abstract classes usually behave as more than one form for its sub classes. Abstract classes can have methods of their own, but it should have abstract methods so that derived class can implement those. The classes should be appended with a keyword called as abstract, to make it abstract by nature. 

Program to demonstrate the use of Abstract class and Abstract method in Java
package com.hubberspot.abstractTest.example;

abstract class Shape
{
 double a, b;
 Shape(double d1, double d2)
 {
  a = d1;
  b = d2;
 }
 abstract double area();
}

class Circle extends Shape
{
 Circle(double radius)
 {
  super(radius, 0); 
 }
 double area()
 {
  return Math.PI * a * a;
 }
}

class Rectangle extends Shape
{
 Rectangle(double length, double breadth)
 {
  super(length, breadth);
 }
 double area()
 {
  return a * b;
 }
}

public class AbstractTest
{
 public static void main(String[] args)
 {
  Shape shape;
  shape = new Circle(5);
  System.out.println("Area of circle =" +
    " " + shape.area());
  
  shape = new Rectangle(5, 10);
  System.out.println("Area of rectangle = " 
  + shape.area());
 }
}

Output of the program : 

how to implement Binary Search in Java ?.

package com.hubberspot.binarysearch.example;

import java.util.Scanner;

public class BinarySearch {
  public static void main(String[] args){       
    int[] numbers = {3, 4, 5, 6, 7, 2, -3, 4, 16, 14};
    sort(numbers);
        
    Scanner scanner = new Scanner(System.in);    
    System.out.println("Enter the number you want to "
            + "search from array : ");
    
    int key = scanner.nextInt();
        
    boolean position = binarySearch(numbers,key);
    
    if(position == true)
      System.out.println("Array contain the element to "
              + "be searched");
    else
      System.out.println("Array does not contain the element"
              + " to be searched");
    }
    
  public static void sort(int[] list) {
    boolean nextPass = true;
    
    for (int k = 1; k < list.length && nextPass; k++) {
      nextPass = false;
      for (int i = 0; i < list.length - k; i++) {
        if (list[i] > list[i + 1]) {
      
          int temp = list[i];
          list[i] = list[i + 1];
          list[i + 1] = temp;
          
          nextPass = true; 
        }
      }
    }
  }  
    
  public static boolean binarySearch(int[] list, int key) {
    int low = 0;
    int high = list.length - 1;

    while (high >= low) {
      int mid = (low + high) / 2;
      if (key < list[mid])
        high = mid - 1;
      else if (key == list[mid])
        return true;
      else
        low = mid + 1;
    }

    return false; 
  }
}

Output of the program




Video tutorial to demonstrate how to implement Binary Search in Java.








Java Server Pages (JSP) : Advantages over Servlets and other technologies

Introduction
In this section of blog, we will look into server side technologies that are popular. We will compare Other leading technologies with one of the highly used technologies called as Java Server Pages (JSP). So, What exactly do we mean by JSP ?. A JSP is a web-based powerful technology in which an html page has Java code embedded to it. It is one of the powerful technology which is implemented on server side to provide dynamic as well as static content to a client browser. It provides Java Developer and Web designer a way to execute a Java code present in a html page on the server side. Generally, the Java code embedded into an html page returns static or dynamic content upon executing on server side. The static content can be anything from normal html page, xml or simple txt etc. The dynamic content is been generated by Java code embedded into the web-page.

JSP Versus SERVLETS
It is been seen that JSP and Servlets provides dynamic content to a web-page, but in a different way. Both technologies are powerful and complimentary to each other. Servlets and JSP operate quite differently and even opposite at some extent. A Servlet is a simple Java program in which html is embedded. The Java program executes on the server-side and display the result to the browser by embedding html which is output to the browser. The Servlet embed html into Java code through out.println statements.

Relation between JSP and Servlets
Usually JSP and Servlets are very closely related to each other. Each JSP is first compiled into a Servlet before it can be used. When a first call is made to JSP, it translates to Java Servlet source code and then with the help of compiler it gets compiled to Java Servlet class file. This class file gets executed in the server and result are returned back to client.    

Advantages of JSP over Servlets
  1. Servlets use println statements for printing an HTML document which is usually very difficult to use. JSP has no such tedius task to maintain.
  2. JSP needs no compilation, CLASSPATH setting and packaging.
  3. In a JSP page visual  content and logic are seperated, which is not possible in a servlet.
  4. There is automatic deployment of a JSP, recompilation is done automatically when changes are made to JSP pages.
  5. Usually with JSP, Java Beans and custom tags web application is simplified. 
 Advantages of JSP over other Technologies
  1. Active Server Pages (ASP) : ASP is a Microsoft technology. The dynamic part of JSP is written in Java, so it is more powerful and easier to use. Secondly, JSP is platform independent whereas ASP is not. 
  2. Pure Servlets : It is more convenient to write regular HTML than to have println statements that generate HTML. Allows separation of look from the content. In a JSP web designer can design web page separately and servlet programmers can insert the dynamic content separately. 
  3. Server-Side Includes (SSI) : SSI is widely supported technology for including externally defined pieces into a static web page. JSP is better because it lets you use servlets instead of a separate program to generate that dynamic part. Besides, SSI is really only intended for simple inclusions, not for real programs that use form data, make database connection. 
  4. JavaScript : JavaScript can generate HTML dynamically on the client. However, it can only access client environment. JavaScript can't access server-side resources like databases, catalogs, pricing information etc. 
  5. Static HTML : Regular HTML cannot contain dynamic information. JSP is easy and convenient. It is quite feasible to insert small amounts of dynamic data.
   

How to pass input from a console to a Java program ?.


In this section of blog, we will look into a tutorial and a simple Java program, explaining how to pass input from a console to a Java program. Usually, Input is given to the program from the standard input device called as keyboard. In Java reading an input is not as simple as output. Java API is full of several classes which can be used for the purpose of reading the input from a keyboard.

System.in is a predefined stream object which can be used to read input. But System.in is a byte oriented stream, it can be used only to read bytes. In order to make it read characters we usually wrap it across a character oriented stream called as InputStreamReader. InputStreamReader is a reader class which is been used to read characters. For reading the input as string we wrap this byte stream to BufferedReader which buffers characters.

In order to apply above concepts to these streams we follow these steps :


1. BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

2. InputStreamReader isr = new InputStreamReader(
System.in);
BufferedReader br = new BufferedReader(isr);


In order to read a string, we use method readLine on the BufferedReader object as

String read = br.readLine();

Program to demonstrate how to pass input from console to a Java program in order to calculate sum and average of numbers as wished by user

package com.hubberspot.streams.example;

import java.io.*;
public class ConsoleReader {

public static void main(String[] args) throws IOException {

int number, sum=0, n, i;
float avg;

BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));

System.out.println("How many numbers? ");

n = Integer.parseInt(br.readLine());

 for(i=0; i < n ; i++)
{
System.out.println("Enter number " + (i+1));

number = Integer.parseInt(br.readLine());
sum += number;
}

avg = sum / n;

System.out.println("Sum of numbers is = " + sum);
System.out.println("Average of numbers is = "+ avg);

}
} 


Output of the program :





How to Create User Defined Exceptions in Java ?.

In this section of blog, we will be looking into more depth about Exception handling. In this section we will see how to create user defined exceptions in Java ?. The Java API provides several Exception classes which are adequate for most purposes. However, in some cases, we may encounter a situation which cannot be described by standard exception types. For example, suppose we are accepting the birthdate of the user. If the user enters month as 15, we may want to treat it as an InvalidMonthException. For such cases, we may need to define our own exception types.

A user defined exception class must extend Exception. The syntax is given below:

Syntax: 

class UserDefinedException extends Exception
{
  // code
}

To give a default text message regarding the exception, simply override the toString() method. This class can also define a constructor which can pass this string to the superclass constructor.

Program to demonstrate User Defined Exceptions 

package com.hubberspot.exception.example;

class InvalidMonthException extends Exception
{
  public String toString()
  {
    return "Invalid Month given";
  }
}
class InvalidDayException extends Exception
{
  public String toString()
  {
    return "Invalid Date given";
  }
}
class UserExceptionDemo
{
  public static void main(String[] args)
  {
    try
    {
     if(args.length < 3)
       throw new NullPointerException();
     else
     {
       int dd = Integer.parseInt(args[0]);
       int mm = Integer.parseInt(args[1]);
       int yy = Integer.parseInt(args[2]);
       if(dd < 1 || dd > 31)
          throw new InvalidDayException();
       if(mm < 1 || mm > 12)
                throw new InvalidMonthException();
                  System.out.println("Valid Input");
     }
   }
   catch(Exception e)
        {
System.out.println(e);
}
 }
}

Output 1: java UserExceptionDemo 
 java.lang.NullPointerException

Output 2: java UserExceptionDemo 24 6 2011
 Valid Input

Output 3: java UserExceptionDemo 24 16 2012
 Invalid Month given

Output 4: java UserExceptionDemo 31 2 2012
 Invalid Date is given





Video tutorial to demonstrate how to create user-defined or application specific exceptions in Java.











Interfaces Vs Abstract Classes in Java

Introduction 
In this section of blog, we will look into comparison between Interfaces and Abstract Classes. Generally, programmers often get confuse at the time of design that, when to use interfaces and when to use abstract classes. It all depends on class design. An abstract class is a class which is incomplete, it can contain data members, constructors, method definitions, static fields and methods. So it has already functionality defined as compared to interface. A class which extends an abstract class inherits all this. When say a class tyre extends an abstract class car, objects of class tyre are also of type car.

Interfaces are used when one or more classes need the functionality of the interface. It is not necessary that this class must have any relationship with interface. Let say we have two classes class Employee and class Rectangle, both class can implement Comparable interface for comparing their objects. But, none of the class Employee and Rectangle has any relationship with the Comparable interface.

Comparison between Interfaces and Abstract Classes

1. An Abstract class is an Incomplete class, whereas an Interface is a pure abstract class. 

2. An Abstract class generally defines common behaviour and attributes that a class inherits, whereas an Interface specifies functionality which a class should have.

3. An Abstract class contains method declarations and definitions, whereas an Interface contains only method declarations.

4. An Abstract class can contain fields which can be static, final, as well as instance fields, where as Interface fields are implicitly final and static.

5. An Abstract class can have a constructor, whereas an Interface cannot have a constructor.

6. An Abstract class is used with extends keyword, whereas an Interface is used with implements keyword.

7. An Abstract class can be extended by more than one class, whereas an Interface can be implemented by more than one class.

8. A class can extend only one abstract class, whereas a class can implement more than one Interface.

9. An Abstract class can be extended by another abstract as well as concrete class, whereas an Interface can be extended by another Interface.

10. A class cannot extend more than one class, whereas an Interface can be used to implement multiple inheritance. 


Program to demonstrate how to display File information in Java ?.

Introduction
In this section of blog, we will look into a simple program that will demonstrate how to display File information in Java. The methods used here are defined in File class present in java.io.* package. For more details of this method read my blog post : Creating objects and methods list of File class in Java

package com.hubberspot.file.example;

import java.io.*;

/**
 *
 * @author Jontymagicman
 */

public class FileInformation {
  public static void main(String[] args){
        
    File file = new File("E:\\notepad.txt");
        
    System.out.println("File Name : "+ file.getName()); 
 
 System.out.println("File last modified : "+ file.lastModified()); 
 
 System.out.println("File size : " + file.length() + " Bytes"); 
 
 System.out.println("Path : "+file.getPath()); 
 
 System.out.println("Abs Path : "+file.getAbsolutePath()); 
 
 System.out.println("Parent : "+ file.getParent()); 
 
    System.out.println(file.exists() ? +
+"File exists":"File does not exist"); 
 
    System.out.println(file.canWrite() ? +
+"File is writable" : "File is not writable"); 
 
 System.out.println(file.canRead() ? +
+"File is readable" : "File is not readable"); 
 
    System.out.println(file.isHidden() ? +
+"File is hidden" : "File is not hidden"); 
 
 System.out.println(file.isDirectory() ? +
+"Is a directory" : "Is not a directory"); 
 
    System.out.println(file.isFile() ? +
+"Is a file" : "Is not a file"); 
 
    System.out.println(file.isAbsolute() ? +
+"File is absolute" : "File is not absolute" );
        
  }
    
}

Output of the program




How to set path/classpath in Java ?.

Introduction :
In this section of blog post, we will learn how to set path or classpath in Java. After downloading Java from Sun's website, next step is to install java. After successful install we have to set classpath for Java Development Kit. Generally, in order to compile and execute a java program we have to set classpath or else every time we run java program we have to provide absolute path for compilation or execution. After installation of Java on say Windows machine, we have Java's JDK .exe installed on "C:\Program Files\Java\jdk1.6.0_18\bin". Here the CLASSPATH is the environment variable whose value is a list of directories in which compiler and interpreter search for the compiled class files.

Step 1 - Start the Control Panel
Click the Windows Start button and then click Control Panel in the menu which appears. See the figure below:


Step 2 - Click on System
In the Control Panel, Click on System. See the image below :




Step 3 : As soon as System Properties window is opened, Right-Click on Advanced tab and below in the Advanced tab, Right-Click on environment variable. See image below :




Step 4 : As soon as Environment Variable window is opened, in order to set path right-click on Path in the System Variables. After selecting Path in System Variables, right-click on edit button to place your required Java JDK path. 






Step 5 : As soon as Edit System Variable window is opened, in order to set path, scroll at the last semi-colon (;) in the variable value and place jdk's bin path as "C:\Program Files\Java\jdk1.6.0_18\bin". Then right-click on OK. After installing java in your machine just go to Program files in C drive and traverse in Java folder to bin and copy that path to place here. In my case bin path was at folder structure "C:\Program Files\Java\jdk1.6.0_18\bin".




Step 6 : Right-click on OK.




Step 6 : Right-click on Apply and then Right-click on OK.


That's it you are done in successfully setting path in Java. For testing the latest set path, open command prompt and just type Java command as "java -version" and you will get details of latest installed Java version.




Exception Handling in Java : Checked and Unchecked Exceptions

Introduction
Errors and unexpected situations are an integral part of programming. It rarely happens that programs are error free. It is the responsibility of the programmer to identify all possible errors and correct them so that the program runs. There are different types pf errors that can occur in a program. Syntax errors occur when the rules and the syntax of the language is not followed. For e.g. if we forget to end a statement with semicolon or we misspell a keyword. Syntax errors are detected and reported by the compiler. Logical errors occur when we make a mistake in the program logic i.e,. algorithm. For e.g. instead of addition, we perform subtraction. In such a case, the program will run but will not give the correct output. Removal of logical errors is called debugging which should be done by the programmer.
Another kind of errors are called exceptions which are run-time errors which occur when the program is running. Now here we will look after exceptions and exception handling in detail.

Dealing with Errors
Since errors are an intrinsic part of programming, we cannot ignore them but we have to deal with errors. When a runtime error occurs in a program, there are two things that should ideally take place.
  1. The program should return to a stable state and allow the user to take further action.
  2. If the program has to be terminated, it should five the user to save all work before termination.
The above may not happen automatically in the program. For this purpose, the programmer must understand the various causes of errors, anticipate what kind of errors can occur in the program so that the program does not terminate abnormally when some error occurs.

Causes of errors :
  1. User Input Error – These errors occur in input values given to a program. These include invalid out of range values given to variables, values of wrong types, invalid paths etc.
  2. Device Error – These errors are related to the hardware devices which the program uses. For e.g., a network connection may be unavailable, the printer may fail, the removable disk may be malfunction while file I/O etc.
  3. Physical Limitations – These errors are caused due to limitations on available the printer, stack space for recursion , limited connection bandwidth etc.
  4. Code Errors – These errors are caused due to the code itself. These include violation of constraints, invalid method calls, illegal assignments, undefined class, exceeding array limits etc.
Any of these can occur in a program. An elegant way to handling these occurences is by theuse of an Exception handling mechanism which is discussed in the next section.

Exceptions:
An exception is an abnormal condition that arises in a code at run time. In other words an exception is a runtime error. Java has an inbuilt exception handling mechanism.
An exception in Java is an object trhat describes the occurrence of some exceptional or unexpected condition during execution. It encapsulates the information of the error so that further action can be taken. This is what happens when an exception occurs:
  1. When an exception arises, an object representing that exception is exception itself.
  2. The method in which the error occurred may choose to handle the exception itself.
  3. If the method can’t handle the exception, it throws this exception object to the method which called it.
  4. The exception is caught and processed by some method or finally by the default java exception handler.
Exception Classes
There are several predefined execution classes defined in the java.lang package . In the java programming language, an exception object is always an instance of a class derived from Throwable.
All exception classes extend Throwable. From the Throwable class, there are two separate hierarchies: Error and Exception.

Error: These classes are related to internal errors and resources exhaustion during runtime. The user has to control over such situations and hence, these types cannot be handled by the program. The java runtime system takes default action when this type of situation occurs.

Exception: The classes belonging to this hierarchyrepresents exceptions that a program would want to be made aware of during execution. There are two brancheshere: exceptions of the type RuntimeException and those that do not inherit from RuntimeExc eption. RuntimeException represents many common programming errors that occur runtime.

Checked and UncheckedExceptions
Exceptions can be classified into 2 types : Checked and Unchecked.

Checked Exceptions: Except for RuntimeException, Error, and their subclasses, all other exceptions are called checked exceptions. It means that it is compulsary for the user to check i.e, to handle an exception. If a method throws a checked exception then the method must take the responsibilty to deal with it. The method must either catch the exception and take appropriate action, or pass the execution on to its caller.
Examples : IOException, ClassNotFoundException, InterruptedException, CloneNotSupportException

Unchecked Exception: Exception defined by Error and RuntimeException classes and their subclasses are known as unchecked exceptions. It means that it is not mandatory for a method to deal with such kinds of exceptions, The compiler doesn’t check if a method handles or throws this exception. Such exceptions are either irrecoverable and the program should not attempt to deal with them or they cannot be treatedas exceptions.
Examples- NullPointerException, ArrayIndexOutofBoundsException,
ArithematicException, NumberFormatException etc

How to implement Stack collection in Java ?.

Introduction :-
In this section of post we will look into a basic implementation of Stack class in Java. The Stack Class is a very useful data structure used for storing elements/data/information using FILO (First In Last Out) ordering. We can analyze it by observing say bunch of books placed one over the other. So the book kept first over the table or surface will be the last one to read. The book kept on top is one that is first to be used. In the below example stack is governed by two methods called as push and pop. If we want to put an element on the top of the stack we use push method and, if we want to take element from the top of the stack we use pop method.

Program to demonstrate Stack Collection implementation in Java 

package com.hubberspot.stack.example;

/**
 *
 * @author Jontymagicman
 */
 
class Stack {
  int stack[] = new int[10];
  int topOfStack;
  
  Stack() {
    topOfStack = -1;
  }

  void push(int item) {
    if(topOfStack==9) 
      System.out.println("Stack is full.");
    else 
      stack[++topOfStack] = item;
  }

  int pop() {
    if(topOfStack < 0) {
      System.out.println("Stack underflow.");
      return 0;
    }
    else 
      return stack[topOfStack--];
  }
}

public class StackTest {
  public static void main(String args[]) {
    Stack mystack = new Stack();
    
    for(int i=0; i<10; i++) 
        mystack.push(i);
    
    System.out.println("Stack in mystack :");
    for(int i=0; i<10; i++) 
       System.out.println(mystack.pop());

  }
}
  Output of the program :- 





In above example, we have used an array named stack which will hold all the integers in a stack form. Generally, we have used topOfStack variable which initializes the stack array. This variable has the index of the top of the stack.The class StackTest creates one integer stacks, pushes some values onto each, and then pops them off.


How to run a simple Applet in Java ?.

Introduction
This blog post will guide you about the basics of Java Applet. This tutorial will teach you how to run a simple Applet in Java. So, What is an Applet in Java ? An Applet is a small java program that runs in a Java enabled web browser. Java Applet is a small piece of java code that is embedded into HTML page, which gets executed when the HTML page loads into the browser. Applet runs on the Client machine, while Servlet runs on Server side. They are rarely used to make website dynamic. Its secure and platform independent. They require JVM and Java enabled web browser such as IE, Mozilla etc, to get execute on client machine. Applets are embedded into HTML documents and has various methods in java.applet.Applet, which governs its life-cycle.

Program to demonstrate how to run a simple Applet in Java

import java.applet.*;
import java.awt.*;

/*
<applet code="SimpleApplet.class" 
         height="250" width="250">
</applet>
*/
public class SimpleApplet extends Applet {
  public void init() {
  }

  public void start() {
  }

  public void stop() {
  }

  public void destroy() {
  }

  public void paint(Graphics g) {
    g.setColor(Color.RED);
    g.drawString("Welcome to Hubberspot!", 50, 100);
  }
}

SimpleApplet.html file to run applet on Web Browser

<html>
  <head>
       <title>Simple Applet</title>
  </head>

  <body>
       <applet 
              code="SimpleApplet.class" 
              height="250" 
              width="250">
       </applet>
  </body>
</html>

Output of program :



Running an Applet in Java
Java Applet are compiled by javac command. It can be run by two ways, but not with using java command. It can be run by using either java tool- appletviewer or by loading Applet into web browser using applet tag in html. Let us look into more details below :

1) Using Web Browser :
To view the applet in a web browser, you will require a java enabled web browser. To enable java in the browser, go to browser advanced setting an enable java. The following steps should be followed :

a) Create an HTML file as above, containing the APPLET tag.
b) Compile the applet source code using javac.
c) Open the html file in the web browser.

2) Using appletviewer :
It is a java tool provided to view applets. It is like a small browser provided to have a preview of applet as they would look in browser.It understands APPLET tag and used in the creation phase. The APPLET tag should be written in source code file enclosing in comments. The following steps should be followed:

a) Write HTML APPLET tag in comments in the source file.
b) Compile the applet source code using javac.
c) Use appletviewer ClassName.class to view the applet.

How Garbage Collection works in Java ?

Introduction :- 
Garbage Collection is an important concept in Java programming language which deals with the removal of unwanted objects from the heap memory. This concept is applied by Java Virtual Machine which automatically cleans object from the heap memory when they are unused. If we talk about heap memory, it is an special and large pool area of memory. It has unused memory and usually store Java objects used in Java applications. The size of heap memory depends on the environment. The heap memory can store large chunks of objects, but if it keeps on storing more and more objects finally it can run out of memory.
Usually JVM performs automatic garbage collection of objects which are unreachable in our application. Garbage Collection is performed by Garbage Collector present in JVM. There is no specific algorithm followed by Garbage Collector to free memory by removing unwanted objects stored on heap. JVM implements different algorithm to determine the time and efficiency of performing Garbage Collection. The main thing we should keep focus on is the point when object becomes free, unreachable and unused for garbage collection.

Generally, new keyword is used to create a new object on heap dynamically. It also returns a reference value of an object in memory. We save this value in a variable which we can use to refer to that object later. Garbage Collector performs many tasks such as :
  1. It has a track of object references. 
  2. It frees memory when an object is unreachable from its reference. 
  3. It uses free memory to allocate new objects.
  4. It finally invokes finalize method. 
Garbage Collector can/ may be invoked by two ways :
  1. Using Runtime class instance and invoking gc method through it. 
  2. Using the System class gc method to invoke it. 
Program to demonstrate the use of garbage collector : 

package com.hubberspot.garbagecollection.example;

/**
 *
 * @author jontymagicman
 */

public class GarbageCollector {
  public static void main( String[] args){
    Runtime rt = Runtime.getRuntime();
    
    System.out.println("Total JVM memory "
            + "available = "+ rt.totalMemory());
    System.out.println("Free memory before "
            + "Garbage Collection = " + rt.freeMemory());
    
    rt.gc();
    
    System.out.println("Free memory after "
            + "Garbage Collection = " + rt.freeMemory());
        }
}
Output of the program : 




Program to demonstrate how to swap two numbers with and without using third variable

Introduction:-
Hello friends, In this section of tutorial we will go over and look into two quite simple programs:
  • How to Swap two numbers in Java ?.
  • How to Swap two numbers in Java without using third variable ?. 
In the first program we will swap two numbers with the use of third variable called as temp. It is generally a temporary local variable which can store value of a number for sometime and assign it to a different variable.
The code to swap two numbers by using third variable is written in swap method in below program. In the swap method our both the numbers i.e number1 and number2 are passed as arguments. In the swap method a temp variable is created to which number1 value is assigned to store it for sometime, so that it can assign it to number2 which will help us in performing swapping of two numbers.Meanwhile, number2 value is directly assigned to number1.




Program to demonstrate how to swap two numbers in Java
package com.hubberspot.swap.example;

/**
 *
 * @author jontymagicman
 */
public class Swap {
  public static void main(String[] args) {
    int number1 = 5;
    int number2 = 9;
    
    System.out.println("Before Swapping the numbers : ");
    System.out.println("Value of number1 is :" + number1);
    System.out.println("Value of number2 is :" +number2);
    
    swap(number1, number2);
  }
  
  private static void swap(int number1, int number2) {
    int temp = number1;
    number1 = number2;
    number2 = temp;
    
    System.out.println("After Swapping the numbers : ");
    System.out.println("Value of number1 is :" + number1);
    System.out.println("Value of number2 is :" +number2);
    
   }
}


In the second program below we will look into swapping of two numbers without using third variable. In the swap method our both the numbers i.e number1 and number2 are passed as arguments. In order to swap two numbers without using the third variable, we generally use mathematical logic. We add number1, number2 together and assign it to number1. After that in next step, we subtract number2 from number1 and assign it to number2. After that in next step, we subtract number2 from number1 and assign it to number1. Program to demonstrate how to swap two numbers without using third variable in Java
package com.hubberspot.swap;

/**
 *
 * @author jontymagicman
 */

public class Swap {
  public static void main(String[] args) {
    int number1 = 5;
    int number2 = 9;
    
    System.out.println("Before Swapping the numbers : ");
    System.out.println("Value of number1 is :" + number1);
    System.out.println("Value of number2 is :" +number2);
    
    swap(number1, number2);
  }
  
  private static void swap(int number1, int number2) {
    number1 = number1 + number2;
    number2 = number1 - number2;
    number1 = number1 - number2;
    
    System.out.println("After Swapping the numbers : ");
    System.out.println("Value of number1 is :" + number1);
    System.out.println("Value of number2 is :" +number2);
    
   }
}



Output of the programs : 

Program to demonstrate this keyword to find area of rectangle

How to use the this keyword in Java ?.
The this keyword is a special keyword frequently used in the Java programming language. Usually, this keyword is used when we want to refer currently executing object. Here this keyword is the reference to a calling object itself. When a object calls a method also called as Instance method, it has variable this which refers to object which has called it. By using this keyword you can refer or access to any field of a particular object in a method or constructor. Whenever an instance method or constructor is called this keyword is set to a variable holding reference to a object who has called it.

package com.hubberspot.this.example;

class Rectangle{
    
  private int length;
  private int breadth;
    
  Rectangle(int length){
    this.length = length;
  }
    
  Rectangle(int length, int breadth){
    this(length);
    this.breadth = breadth;       
  }
  public int area(){
    return (length*breadth);
  } 
}

public class ThisTest {
  public static void main(String [] args){
    Rectangle rect = new Rectangle(5,5);
        
    System.out.println("The Area of rectangle is : "+
        + rect.area());
    
    }
    
}

Output of the program :- 

How to demonstrate working of Multidimensional Arrays in Java

What do we mean by  Multi-Dimensional Arrays in Java ?. 
Multi-Dimensional Arrays in Java are termed as arrays of arrays. Normal arrays are objects in Java, while if we talk about Multi-Dimensional arrays, those are array objects whose elements themselves store array objects. Two Dimensional arrays are basic representation of tables having rows and columns. Thus, the information stored in two dimensional array is generally in rows and columns. Let us look into a simple program that demonstrate Multidimensional Arrays in Java :- 

package com.hubberspot.multidimensional.array.example; 

public class TwoDimensionalArrayDemo {
  public static void main(String args[]) {
     int twoDArray[][]= new int[5][5];
     int i, j, k = 0;

     for(i=0; i<5; i++)
       for(j=0; j<5; j++) {
         twoDArray[i][j] = k;
         k++;
     }
        
     for(i=0; i<5; i++) {
       for(j=0; j<5; j++)
         System.out.print(twoDArray[i][j] + " ");
         System.out.println();
     }
  }
} 

Output of the program :- 


How to declare, create and access a one-dimensional Array in Java

Introduction :-
Today I will be explaining you some of the basic concepts related to an array. I will be teaching you how to declare an array ?. , how to create an array ?. and how to assign values to array elements?.Generally an array is group of variables holding values which have same data types. It means an array can store many values in them which are of same data types. Generally arrays are objects in Java, so they come under category of reference types. An array variable provides reference to an array object in a memory which can either hold primitives data types or reference data , based upon the declaration of an array. To retrieve elements of an array we use concepts of index.We provide the name of array variable and position number of array element which we want to retrieve in a square bracket. Let us go further and see how this whole concept works.


How to declare a One-Dimensional arrays ?.
A one-dimensional array is a linear list of elements of the same type. Let us see how to declare an One-Dimensional array:

Syntax : 
type array-name [ ]; 
Or 
type [ ] array-name;

Here, type declares the base type of the array and array-name is the name of the array.
Let us look into few of examples :

int [ ] intArray ; 
byte [ ] byteArray ;
Object [ ] objectArray;

In first example, we have declared an array which can hold int values. The array name is intArray. However, the array does not exist. The object intArray is set to null which represents an empty array.

How to create a One-Dimensional array ?.
In order to create a One-Dimensional array, we use new operator. The new operator creates an object of array in heap memory. Let us look into the syntax :

Syntax :
array-name = new type [ size ] ; 

Here array-name is the name of the array, type is the datatype of elements in the array and size is the number of elements.

Let us look into few of the examples :

intArray = new int [ 10 ] ;
byteArray = new byte [ 10 ];
objectArray = new Object [ 10 ] ;

In first example, we have created an integer array of 10 elements and assigns it to the variable intArray. After writing this syntax an array object is created in heap which can hold 10 integer values.


How to assign values to array through example ?.
Values can be assigned to an array by couple of ways. Let us look into syntax of some of those ways below :

Syntax :
array-name [ index ] = value ;

The value can be assign to each array element through their respective index number. As arrays are linear so they have sequential indexing. The indexing of an array starts with number 0.

Let us look into an example below :

for( int i = 0; i < 10 ; i++ )
intArray[ i ] = i + 1 ;

After for loop gets executed, values from 1 to 10 are assigned to array elements intArray[ 0 ] to intArray[ 9 ]. There is also an another way of assigning values to an array at the time of declaration. This assigning of value to an array is called as initialization. If we initialize an array, the size of an array need not be given. Let us look into syntax of initialization of an array.

syntax : 
type array-name [ ] = { value1, value2, value3 .... .... , valueN }
Let us look into the example:

int [ ] intArray = { 1,2,3,4,5,6,7,8,9,10} ;


Accessing Array Elements 

Generally, Arrays in Java are implemented as objects. Arrays in Java have a attribute called as length which stores the size of an array. Each and every array created has this attribute. It always store size of an array. This attribute or field can be accessed by using syntax :

array-name.length

Let us look into an example :

int [ ] intArray = { 4,5,6,7,8,9,1,2,3} ; 
for (int i = 0; i < intArray.length; i++ )
System.out.println( "Value of element" + i + " = " + intArray[ i ] );
Above code will print the values of an array element using length field. If we make an attempt to access array elements beyond the legal index, it throws an exception called ArrayIndexOutOfBoundsException.

Java Applets Life-Cycle Methods

Introduction 
This blog post will guide you about the basics of Java Applet. This tutorial will teach you how to create small applets. So, What is an Applet in Java ? An Applet is a small java program that runs in a Java enabled web browser. Java Applet is a small piece of java code that is embedded into HTML page, which gets executed when the HTML page loads into the browser. Applet runs on the Client machine, while Servlet runs on Server side. They are rarely used to make website dynamic. Its secure and platform independent. They require JVM and Java enabled web browser such as IE, Mozilla etc, to get execute on client machine. Applets are embedded into HTML documents and has various methods in java.applet.Applet, which governs its life-cycle. Let us look into few of those :

Applet Life-Cycle Methods

1. public void init()

It is the first method that is invoked or called for an applet. Any initialization needed for an applet is performed in this method. It is launched by the system automatically when Java executes an applet. It performs small tasks such as loading images and reading parameters etc . Applets can be initialized by the constructors but init method is preferred for doing all the applet initialization.


2. public void start()

After Java calls init method, this method is executed next. It gets automatically called after init method completes execution. It is special method, when a user goes to any other website and finally returns back to html page of applet, this method is called again. All the tasks that we need to perform after applet gets loaded and after user revisits applet is written here. Generally, animation performing code or new start to a different thread is written here.

3. public void paint( Graphics g )

This method is called usually after init and start method gets executed. This method is called whenever applet needs to be redrawn in the browser window. If user covers applet window by a different window and later comes back to same window by uncovering, the paint method is called. This method has one parameter of type Graphics which performs actions involved with drawing. It is also used for displaying text, graphics etc.

4. public void stop()

This method is called when the user leaves the page on which applet is running. This method performs tasks of stopping execution of animations and threads. This method is called just after the destroy method.

5. public void destroy()

This method is called when the browser completely ends the applet and it is being removed from memory. This method is called when browser shuts down normally. The destroy method has the code that perform tasks that are required to clean up resources such as graphics object, threads etc allocated to the applet.

Applet Advantages and Restrictions

What is an Applet in Java ?
An Applet is a small java program that runs in a Java enabled web browser. Java Applet is a small piece of java code that is embedded into HTML page, which gets executed when the HTML page loads into the browser.Applets provide powerful client-side functionality. As applets are loaded from remote machines and executed on client-side, there are various security restrictions on applets. Let us look into various Applets advantages and Applets Restrictions in brief :

Applet Advantages
Applets have many advantages over stand-alone application. Some of them are :

  1. As applet is a small java program, so it is platform independent code which is capable to run on any browser.
  2.  Applets can perform various small tasks on client-side machines. They can play sounds, show images, get user inputs, get mouse clicks and even get user keystrokes, etc ... 
  3.  Applets creates and edit graphics on client-side which are different and independent of client-side platform.
  4. As compared to stand-alone application applets are small in size, the advantage of transferring it over network makes it more usable.
  5. Applets run on client browser so they provide functionality to import resources such as images, audio clips based on Url's.
  6. Applets are quite secure because of their access to resources.
  7. Applets are secure and safe to use because they cannot perform any modifications over local system.
  8. Various small tasks such as performing login, inventory checking, task scheduling can be done by applets running over Intranets. 


Applets Restrictions
Applets have many restrictions over the areas of security because they are obtained from remote machines and can harm client-side machines. Some of them are as follows :

  1. If we are running an applet from a provider who is not trustworthy than security is important. 
  2. Applet itself cannot run or modify any application on the local system.
  3. Applets has no access to client-side resources such as files , OS etc. 
  4. Applets can have special privileges. They have to be tagged as trusted applets and they must be registered to APS (Applet Security Manager). 
  5. Applet has little restriction when it comes to communication. It can communicate only with the machine from which it was loaded. 
  6. Applet cannot work with native methods. 
  7. Applet can only extract information about client-machine is its name, java version, OS, version etc ... .
  8. Applets tend to be slow on execution because all the classes and resources which it needs have to be transported over the network. 

Creating objects and methods list of File class in Java

Introduction :-

Hello friends, In this hub, I will be creating and demonstrating the working of File objects in Java. Before we go further, lets go in the basics of importance of files in computers. Generally, data stored in variables and objects are not permanent. They are not persistent. They are normally temporary data which remains in memory as long as the scope of variable. Once a local variable gets out of scope the data is lost. So to keep the data for long time use generally computer uses files. These files are been stored in secondary storage devices such as hard disk, flash drives etc. The data stored in them is permanent.In terms of programming language such as Java, terms like Files and Streams have their own meaning. Java actually sees a file as a stream of bytes which is sequential.
Java provides us a package called as java.io package. This package consist of class File which helps in retrieving information about various files and various directories in disk. Generally they don't provide capabilities such as opening or closing a file and basic processing of a file or directory. However File objects are frequently used with other objects in java.io package to do the above processing of the files and directories.

Creating File Objects :-

File Objects are created with new operator, which calls constructor with four different arguments. One of the constructor requires string passed to it as argument. This string provides the constructor name of the file or directory. The name usually is the path given to constructor where File object can locate the file or directory. The path information provided into the constructor can be either relative or absolute path. The relative path deals with current directory from where the application has began. The absolute path starts from a root directory and proceed to name of the file or directory specified. Another constructor has two arguments passed to it, first argument contains the relative or the absolute path to file directory and the second argument contains the name of the file or directory , which we want to associate to File object. Another constructor with File and String argument is used. Here we use existing File object which points to file or directory specified by the String argument. The last constructor uses the URI as an argument to point to the file or directory. Here by URI we mean Uniform Resource Identifier which are like Uniform Resource Locators. They use URL like pattern to locate the files, e.g. file://C:/java-programs.txt.

Constructors of File :-
File (String path);
File (String path, String name);
File (File obj, String name);
File (URI);

Important methods of File class
  1. boolean isFile() :- This method return either true or false. It return true if the File object created by passing a String object to it, is an existing file.
  2. boolean isDirectory() :- This method return either true or false. It return true if the File object created by passing a String object to it, is an existing directory.
  3. boolean exists() :- This method returns true if the file / directory represented by the object exists.
  4. boolean canWrite() :- It returns true if the current application can write the file.
  5. boolean canRead() :- It returns true if the current application can read the file.
  6. boolean isAbsolute() :- It returns true if the path specified as String in the File object constructor is absolute.
  7. String[ ] list() :- If you want directory's content in the form of array of string this method is used. It returns null if the file specified in the argument is not directory.
  8. long lastModified() :-It provides us with the time, that when a file was last modified.
  9. long length() :- It returns the length of the file in bytes. If its a directory, an unusual value is returned.
  10. String getPath() :- It basically returns the path of the file in use.
  11. String getParent() :- It basically returns the name of parent directory holding the file .
  12. String getName() :- It return name of the file used at the time of creating File object
  13. String getAbsolutePath() :- It basically returns the absolute path of file or directory.
  14. String getCanonicalPath() :- Returns the path of the file object but separators in the path name are system-dependent separators such as / or \.
  15. Boolean isHidden() :- Returns true if the file is hidden and false otherwise.
  16. Boolean renameTo(File name) :- Renames the file (or directory) represented by this File instance to the new name specified by Name.
  17. boolean delete() :- Deletes the file or directory associated with the File object.
  18. boolean createNewFile() :- Creates a new file with the specified name if it does not exists.
  19. boolean mkdir() :- Creates a directory by using the abstract path name associated with this File instance.
  20. boolean mkdirs() :- Creates a directory by using the abstract path name associated with this File instance. Also creates any non-existent parent directories appearing in the given path.
  21. File [ ] listFiles() :- Returns an array that contains the names of files only contained in the directory represented by this File instance. 


    How to sort array elements using Bubble Sort algorithm in Java ?


    How Bubble Sort is implemented in Java ?. 
    Bubble Sort is a special sorting technique, which sorts elements by making multiple passes. While making each pass neighboring elements are compared in pairs. Generally the order is important, if the comparison comes out in decreasing order the numbers are swapped. If the order comes out in ascending order the values remain unchanged. It is called as Bubble Sort technique because the large value in each pass sinks to bottom while the smaller value bubbles out to top. After first successful pass the largest elements becomes the last element and after second pass, second largest elements becomes the second last element. Bubble Sort is implemented in Java by below small program :    

    package com.hubberspot.sort.example;
    
    public class BubbleSort {
      
      public static void main(String[] args) {
        int[] numbers = {3, 4, 5, 6, 7, 2, -3, 4, 16, 14};
        sort(numbers);
        for (int i = 0; i < numbers.length; i++)
          System.out.print(numbers[i] + " ");
      }  
      
      public static void sort(int[] list) {
        boolean nextPass = true;
        
        for (int k = 1; k < list.length && nextPass; k++) {
          nextPass = false;
          for (int i = 0; i < list.length - k; i++) {
            if (list[i] > list[i + 1]) {
          
              int temp = list[i];
              list[i] = list[i + 1];
              list[i + 1] = temp;
              
              nextPass = true; 
            }
          }
        }
      }  
    } 



    Video tutorial to demonstrate how to sort an array using Bubble Sort algorithm in Java.








    Java Tools and Utilities for Java Programming Language

    Java Tools and Editors
    The Java SDK (Software Development Kit) comes with various utilities which helps programmer to work with Java platform efficiently. Java SDK comes with set of such powerful tools. Let us look into some of widely used tools or utilities one by one :

    1.    javac – the java compiler

    The javac tool is most widely used tool in Java. It provides compilation power to Java. It basically reads program containing classes and interfaces, compiles them to Java bytecodes. These bytecodes are java .class files. Let us look into the syntax of this command-line tool :

    Syntax:
    javac [options] [source_files] [@list_files] 

    where,
    options: Command-line options.
    source_files: Source files to be compiled.
    @list_files: A file containing a list of source file to be compiled.

    Let us look into few examples:

    1.    javac TestClass.java
    This command  compiles TestClass.java into bytecodes named as TestClass.class .

    2.    javac @list_files
    This command compiles all java source files listed in the file called as list_files.
         
     2.   java – the application launcher
    The java tool launches a Java application. It starts Java Runtime Environment, loads the specified .class file and invokes main method in the class.

    Syntax:
    java [options] [class_name] [argument list]
    java [options] –jar JarName.jar [argument list]

    After the option this tool contains name of the class file to be execute, which has the main method. If we use –jar option than we need to specify jar name containing all the classes and resource files. The tool searches main method class in the jar by reading manifest file.
     Let us look into few examples:

    1. java TestClass
    This command executes TestClass.class file by calling main method in it.

    2. java –jar JarName.jar
    This command launch main method of file listed in jars manifest file.

    3. jdb – the java debugger
    The Java Debugger tool jdb is used to help developer to find and fix bugs in java programs.

    Syntax:
    jdb [options] [class_name] [arguments]

    Let us look into few examples:

    1. jdb TestClass
    This command executes TestClass.class and help programmer to debug the code. 

    4. javap – Disassembling classes
    The javap tool allows you to query any class and find out list of methods and constants or find out commands executed by the underlying JVM.

    Syntax:
    javap [options] [class_name]

     Let us look into few examples:

     1. javap java.lang.String
    This command list all the methods and class members of String class. 

    5. javah – Header file generator
    This tool connects Java programs to C and C++ programs. It is used when Java wants to use legacy libraries or Java can’t do something because of platform needs. javah generates C header and source files that are needed to implement native methods. The generated header and source files are used by C programs to reference an object’s instance variables from native source code.

    6. jar – the java archive manager
    The jar tool is a java application that combines multiple files into a single JAR archive file. jar is general purpose archiving and compression tool, based on ZIP compression format. jar allows packaging of all files related to java applets or applications into single archive.

    Syntax:
    jar [options] [manifest] [input-files]

    Let us look into few examples:
    jar –cf JarName TestClass1.class TestClass2.class


    How to use for , while and do-while loop statements in Java code

    Introduction :-
    Java has mostly three looping statements such as for, while and do-while. All three looping statements help us iterating over a code which we want to perform frequently. In this tutorial I will be providing to you Java tutorial on these looping statements. Learning Java through explanation and code is the most effective mechanism. I will be providing you with few basics of looping statements , syntax and than provide you with Java source code. After we get few fundamentals of Java looping statements , I will explain you the code through images. This will make you understand all the three looping statements clearly at basic level.
    The overall looping process involves 3-4 steps. Let us examine each of them one-by-one :
    1. initialization :- A counter variable is set to a value and used to loop the body accordingly.
    2. execution of loop body :- After initialization and condition fulfillment body gets executed that many times based on condition and iteration.
    3. condition :- After initialization a boolean condition is tested with counter variable. If condition comes out to true body of loop gets executed , if condition comes out to be false the loop terminates.
    4. iteration :- Iteration is the increment or decrement process set to counter variable so that we can get exact number of loops.
    Let us start with the for loop :


    1. for loop statements working :-
    Let us look at working of for loop in Java. Before going further you should be familiar with the basics of for loop. Let us view the syntax of the for loop :-




    A sample for loop code
    
    public class ForDemo {
        public static void main(String[] args) {
            
            for (int i = 0; i <= 10; i++) {
                System.out.println("i = " + i);
            }            
        }
    }










    1. Code and Diagram explanation :-
    In the ForDemo class we have a main method which is the entry point for the execution of our program. Then comes the for loop statement. If examining the example by above four criteria we see that here initialization step is int i = 0; condition is i <= 10; if the condition is true body of for loop gets executed i.e System.out.println("i = " + i); if the condition is false the for loop exits. After execution of body each time iteration or increment of i is done and then condition is again tested. This process continues till condition fails.



    2. while loop statements working :-
    Let us look at working of while loop in Java. Before going further you should be familiar with the basics of while loop. Let us view the syntax of the while loop :-






    A sample while loop code 
    
    public class WhileDemo {
        public static void main(String[] args) {        
            
           int countDown = 10;
           
           while (countDown >= 0) {
              
              System.out.println(countDown);
              countDown--;            
            }
        }
    }




    1. Code and Diagram explanation :-
    In the WhileDemo class we have a main method which is the entry point for the execution of our program. Then comes initialization of countDown variable. It is assigned with value 10. Then comes the while loop statement. Here condition is countDown>= 10; if the condition is true body of while loop gets executed i.e System.out.println(countDown); and countDown gets decrement to 1. If the condition is false the while loop exits. Again condition is tested. This process continues till condition fails.



    A sample do-while loop code 
    
    public class DoWhileDemo {
        public static void main(String[] args) {
            int i = 0;
            
            do {            
                System.out.println(i);
                i++;
            } while (i <= 10);
        }





    1. Code and Diagram explanation :-
    In the DoWhileDemo class we have a main method which is the entry point for the execution of our program. After initialization of variable i = 0;. Then comes the do-while loop and body starts executing printing the value of i. Then there is increment in the i value. Then condition is tested that is i<=10; If the condition is true the do loop body again gets executed.This process continues till condition fails. As condition fails the loop gets exit.

     
    © 2021 Learn Java by Examples Template by Hubberspot