Professional Documents
Culture Documents
Java Tutorials RoseIndia
Java Tutorials RoseIndia
Java is great programming language for the development of enterprise grade applications. This programming Language
is evolved from a language named Oak. Oak was developed in the early nineties at Sun Microsystems as a platform-
independent language aimed at allowing entertainment appliances such as video game consoles and VCRs to communicate
. Oak was first slated to appear in television set-top boxes designed to provide video-on-demand services. Oak was
unsuccessful so in 1995 Sun changed the name to Java and modified the language to take advantage of the burgeoning
World Wide Web.
Java is an object-oriented language, and this is very similar to C++. Java Programming Language is simplified to eliminate
language features that cause common programming errors. Java source code files are compiled into a format called
bytecode, which can then be executed by a Java interpreter.
Core Java
Java SE 6
Java SE 7
Advanced Java
J2ME
JSP
Servlets
JDBC
EJB
Web Services
JSTL
Java Flavors
1. What is Java?
Java is a high-level object-oriented programming language developed by the Sun
Microsystems. Though it is associated with the World Wide Web but it is older
than the origin of Web.
Java Features
4. Case sensitivity
What is case sensitivity: Case sensitivity is the mechanism in which words can be
differ in meaning based on different use of uppercase and lowercase letters.
Java Tools
7. Java Compiler
To commence with Java programming, we must know the significance of Java
Compiler.
8. Java Interpreter
We can run Java on most platforms provided a platform must has a Java
interpreter.
9. Java Debugger
Java debugger helps in finding and the fixing of bugs in Java language programs.
11. JavaDoc
This tool is used to generate API documentation into HTML format from Java
source code.
2. Java Keywords
There are few keywords in Java programming language. Remember, we cannot
use these keywords as identifiers in the program. The keywords "const" and
"goto" are reserved though, they are not being currently used.
4. Literals
By literal we mean any number, text, or other information that represents a value.
This means what you type is what you get. We will use literals in addition to
variables in Java statement. While writing a source code as a character sequence,
we can specify any value as a literal such as an integer.
5. Arrays
In this section you will be introduced to the concept of Arrays in Java
Programming language. You will learn how the Array class in java helps the
programmer to organize the same type of data into easily manageable format.
6. Operators
Operators are symbols that performs some operations on one or more then one
operands. Once we declare and initialize variables, we can use operators to
perform certain tasks like addition, subtraction etc.
8. Java Classes
In this section you will be introduced to some essential classes in Java like
Exceptions, Basic I/O, Concurrency etc.
9. Class Inheritance
To know the concept of inheritance clearly you must have the idea of class and its
features like methods, data members, access controls, constructors, keywords this,
super etc.
10. Summary
You have been introduced to the contents of Java language providing a great
amount of information. Perhaps it would be a bit arduous to grasp the whole lot of
things at one go. However, the implementation of these little basics will make you
a substantial programmer.
New to Java?
technology and you want to learn Java and make career in the Java technology then this page is for you. Here we have
explained how to learn Java and master the Java technologies.
Java is a vast language and it requires a lot of effort to learn and master the necessary Java technology to start your real life
projects.
Here at RoseIndia.Net, we have developed hundreds of tutorials, examples and articles to help you learn Java quickly and
easily. We have tried to put support examples related to each Java technology that will help you master the concepts.
These tutorials and examples are arranged in a sequence, so that you can learn Java step by step and master the Java and
JEE technologies.
If you want to start java programming then you need to use a text editor to create and edit the source code. By using the
Java complier, you can change the source code into byte code. The byte code can be run on any platform having Java
interpreter that can convert the byte code into codes suitable for the operating system.
a) Java SE - Java SE or Java Standard Edition provides tools and API's that you can use to create server applications,
desktop applications, and even applets. These programs developed using Java SE can be run on almost every popular
operating system, including Linux, Macintosh, Solaris, and Windows.
b) JEE - Based on the foundation framework of the standard edition, Java Enterprise Edition helps in web application
service, component model and enterprise class service oriented architecture (SOA).
c) JME - Java Micro Edition or JME for short is an accumulation of Java APIs that are used for the development of software
for devices like mobile phones, PDAs, TV set-top boxes, game programming. The platform of micro edition generally
consists of an easy user interface, a robust security model and a wide variety of built-in networks for running Java based
application.
JSE Components
JavaBeans - It is the component architecture for J2SE platform and one can develop and assemble these software
programs for better web application. It is a reusable software component that can be manipulated visually in a builder tool.
This software assists visual builder tools in using reflection, introspection, and also analyze and customize JavaBeans.
Java Foundation Classes (JFC) - It is a part of Java class libraries based on the Java platform used for developing
graphical user interface (GUI). JFC helps in 2D graphics, imaging, text formatting and printing with the help of Abstract
Window Toolkit (AWT), Swing and Java2D. With the help of input method framework, the JFC technology assists in
preparing application that can be accessible to all users around the world in different languages. Drag and Drop is another
feature of JFC that supports data transfers between different Java applications.
JavaHelp - It is a platform independent and a feature oriented software system that offers developer an automated help
component. JavaHelp 2.0 API is useful while building online documentation and presenting online information to the
application users.
Java Web Start - It is framework in the Java platform that assists in starting Application software directly from the internet by
using a web browser. As we know Java applet can run in a browser but in case of Java Web Start, it doesn't run inside and
solve many complex problems associated with Javaplugins and JVM. It also provide many classes that in turn provides
various services and allow better access to resources. Version 1.0 was introduced in the year 2001. Now with the release of
J2SE 1.4, Java Web Start is included with Java Runtime Environment and does need any separate installation.
Java Database Connectivity (JDBC) - JDBC API is a part of Java Standard Edition that helps in accessing data from a
SQL based database. Besides, it also process the result and allows in using the programming language with "Write Once,
Run Anywhere" feature. Some of its key features are like full access to metadata, no special installation and database
identification.
Java Media Framework (JMF) - Its an advanced API that allows Java developers to process and add audio-video source to
Java application and applets. It is useful for multimedia developers to capture, playback, transcode different media formats.
JEE - Components:
Enterprise JavaBeans (EJB) - This technology is a server side component of Java platform used for the construction of
enterprise application. It is one of the Java APIs attached with the enterprise edition. By using Java technology, EJB helps in
quick development of small, distributed, transactional and secure application.
JavaMail - This JavaMail API technology allows to build mails and messaging application in a platform independent and
protocol independent framework. It is both a part of JSE and JEE platform. Thus, JavaMail uses an extensible platform for
transferring all kinds of Multimedia Internet Mail Extension (MIME).
Java Message Service (JMS) - Developed under Java community process, JMS technology is used for sending messages
between users. Basically, it is an enterprising messaging tool used for building enterprising application. The JMS API is a
combination of Java technology and enterprising messaging that provides facilities for building small message based
application. It functions under two models:Point-to-Point and Publishing & Subscribing model.
JavaServer Pages (JSP) - The JSP technology enables web developers in developing and maintaining web content pages
in formats like HTML and XML. With the help of JSP, it becomes very easy to build server and platform independent web
based application. This uses HTML and XML tags that offers logical solution for the content. This separately user interface
and content development from each other, which allows the designer to change page layout without changing the content.
Java Servlets - This enables a developer in adding content to a web server by using Java platform. This provides the
mechanism for enhancing the functionality of web server. In short, servlets provides platform independent and component
based web based application without the performance limiting of CGI program.
JME - Components:
Connected Limited Device Configuration (CLDC) - It is one of the configurations of Java Micro Edition. 'Configuration'
describes minimal features of a complete Java. The CLDC specifies the capabilities of JVM, the base set of API for resource
limited devices like pager and mobile phones. There are two version of CLDC: version 1.0 was released in 2000 and came
to be known as Java Specification Request (JSR)30. Later version 1.1 or JSR 139 but 1.0 is more widely used. The
Connected Limited Device Configuration and the Mobile Information Device Profile (MIDP) together provides solid Java
platform for developing application to run on less processing power devices.
Mobile Information Device Profile (MIDP) - This is another configuration of Java Micro Edition and coupled with CLDC, it
provides a farm Java Runtime Environment for various mobile devices and other personal digital assistance (PDA). With the
help of MIDP, developers can develop application once and then redistribute them into various mobile information devices in
a very small period of time. Its principal functions include the user interface, network connectivity data storage and overall
application process management. There are two versions of MIDP: one is MIDP 2.0 or JSR 118 and the second one is the
MIDP 1.0 or JSR 37.
Connected Device Configuration (CDC) - Developed under the Java Community Process (JCP), it is a standard
framework of Java technology used for building and delivering application that can be shared in a wide range of networks
and devices ranging from pagers, mobile phones, set top box and other PDA devices. It is in two versions: the JSR 36 (CDC
1.0) and the latest one is the JSR 218 (CDC 1.1).
a. Learn JSP - JSP technology assists developers in generating HTML, XML web pages. It uses Java code and
some predefined actions while creating web content. This helps in the creation of JSP tag libraries that acts as
extensions to HTML and XML tags.
b. Learn Servlets - In a Java Platform, Servlets assists developers in adding content to a web server. Servlets
with Java server pages acts as a competitor to various dynamic web content technologies like CGI, ASP.NET,
JavaScript etc.
c. Learn about Tomcat and other servers - Developed by Apache Software Foundation Tomcat is a Java based
web application server used to run Servlet and JSP. It is not merely limited to application server and provides an
open platform to develop extensible web and content management service.
d. Learn Open Source technologies (Struts, Hibernate, Spring) - Basically in Java there are three open
source technologies known as frameworks; these are Spring, Hibernate and Struts. These open source application
frameworks solves many problems related to JSE and J2EE, and helps in effective development of web
application.
e. Learn EJB - Enterprise Java Beans are a part of J2EE and also a server sided component used mostly in large
projects. It helps in easy and rapid development of distributed, transactional and small application based on Java
technology.
f. Learn about Database Management System - It is a software designed to manage and run a database.
Generally, it is used in company back office work, accounting, customer support system and several other
purposes.
Java is a high-level object-oriented programming language developed by the Sun Microsystems. Though it is associated
with the World Wide Web but it is older than the origin of Web. It was only developed keeping in mind the consumer
electronics and communication equipments. It came into existence as a part of web application, web services and a platform
independent programming language in the 1990s.
Earlier, C++ was widely used to write object oriented programming languages, however, it was not a platform independent
and needed to be recompiled for each different CPUs. A team of Sun Microsystems including Patrick Naughton, Mike
Sheridan in the guidance of James Goslings decided to develop an advanced programming language for the betterment of
consumer electronic devices. They wanted to make it new software based on the power of networks that can run on different
application areas, such as computers and electronic devices. In the year 1991 they make platform independent software and
named it Oak. But later due to some patent conflicts, it was renamed as Java and in 1995 the Java 1.0 was officially
released to the world.
Java is influenced by C, C++, Smalltalk and borrowed some advanced features from some other languages. The company
promoted this software product with a slogan named “Write Once Run Anywhere” that means it can develop and run on any
device equipped with Java Virtual Machine (JVM). This language is applicable in all kinds of operating systems including
Linux, Windows, Solaris, and HP-UX etc.
The programming language Java was developed by Sun Microsystems in the year 1995. Earlier, it was only used to design
and program small computing devices but later adopted as one of the platform independent programming language. The
most important feature of Java is its byte code that can be interpreted on any platform including windows, Linux etc. One
can also download it freely from the official website of Sun.
As we have mentioned above that java-programming language was only developed for the small devices but now it can be
found in a variety of devices like cell phones, e-commerce application, PCs and almost all network or computing devices.
Java Applets ? This is another type of Java program that used within a web page to add many new features to a web
browser. These are small program used in the programming of instant messaging, chat service, solving some complex
calculation and for many other purposes.
J2EE ? The software Java 2 Enterprise Edition are used by various companies to transfer data based on XML structured
documents between one another.
JavaBeans ? This is something like Visual Basic and a reusable software component that can be easily assemble to create
some new and advanced application.
As far as syntax is concerned, Java is similar as the C programming language but a distinct style of coding. It follows all the
general programming features like loops, data types, conditions, curly braces, semi-colon etc. Its a fully featured Object
Oriented Programming (OOP) language as it supports all OOP features including classes, modules, inheritance,
Polymorphism etc.
Mobile Java - Besides the above technology, Java is also used for various entertainment devices especially mobile phone.
Mobile Information Devices Profile (MIDP) uses Java run time environment in cell phones, mobile tracking systems and
other traditional PDA devices. Java technology enabled application is key to the games and services available in the mobile
world. This also plays an important role in the field of telemedicine such as PulseMeter. As far as mobile technology is
concerned, it offers offline facility, so that users can get service even if they face loss of connection. Today, all leading
mobile service provider like Nokia, Siemens, Vodafone are using Java technology. Sun Java Wireless Toolkit offers
complete support for developing different MIDP application.
Java technology is enabled with healthy content ecosystem by offering a healthy development and deployment environment,
protecting users and operators from down time and viruses. The increase volume of users now encouraging manufactures
and developers to apply Java technology in numerous other productive and functional ways including MP3 players, digital
TV, video, 3D, simplifying games, etc.
Java Releases
Java is developed by Sun Microsystems in 1996. Now the Java is powerful tools for the development of robust and scalable
enterprise applications.
The tables given below provide information about the name and time of releases for different versions of Java technology.
Download JDK
JDK also known as Java 2 Platform, That comes in three editions J2ME, J2SE & J2EE.
If you are beginner or learning Java then start by downloading J2SE.
Acronyms:
JDK Java Development Kit
JVM Java virtual machine
Download JDK
You can download JDK from www.javasoft.com/j2se
In this beginners java Tutorial ,We will first download, install and configure the J2SE development environment.
Once you have downloaded the j2se on your system, you are ready to install . In the following section we will learn how to
install jdk development environment on your machine. here are the step to install JDK on your windows machine.
Step 1
Double click the JDK down loaded file, the executable extracts the required Contents to the temporary directory and then
License agreement screen appears. On the license agreement page read and accept the license and the click the next
button .
Step 2
The custom setup screen appears as follows.
Step 3
Click on the change button to change the installation directory to "c:\jdk1.5.0_06" as shown in the following screen.
and click on the "OK" button. After clicking on the "OK" button installation begins:
Step 4
In the next window installer asks for the installing the runtime as shown in the following screen:
Step 5
Click on next button install the J2SE runtime on your machine. Next screen shows the browser selection:
Click on the "Next" button.
Step 6
Once the installation is finished it shows you the final screen indications the success. Now you have successfully installed
J2SE on your machine. Installer shows the following final confirmation window as shown below:
Click on the "Finish" button to exit from the installer.
In this Section we will add some settings to the windows environment so that the java compiler and runtime becomes
available for compiling and running the java application.
Go to the control panel and double click on "System Properties" and to to the advance tab.
and add "c:\jdk1.5.0_06" to path variable:
and click on ok button. To save the setting click on "OK" button.
This will make the java environment available for development. Open the dos prompt and type javac on the console, it
should show the following output:
This section introduces the Directory and file structure of SDK (Software Development Kit). The following figure shows
jdk1.5.0 software stored in 'c' directory that has multiple subdirectories like bin, demo, include and jre etc. to hold all
important developing and testing tools. See detail information bellow.
Bin directory - The bin directory provides all inessential tools for developing and testing the program through the help of
command provided by Java compiler.
Demo directory - This directory consists many applications and applets with source code.
Include directory - It contains all header files like for 'C' programming language that enables you to combine C code into a
Java program.
Jre directory - When you run any java program then you have to compile it by the help of Java interpreter or Java Runtime
Environment (JRE). The SDK uses the internal adaptation of JRE, which containing in the jre root directory.
Lib directory - This is a most important directory for development tools that contains libraries and it's supported files.
Docs directory - It is the last directory of Software Development Kit that assists you to store the Java documents. The docs
directory is an optional directory.
Files of the SDK:
JDK1.5.0 directory has following files that provide the detail information about it.
README.html : The jdk1.5.0 directory provides an html file that contains the detail information of SDK shown on the web
browser. This file contains all system requirements, features and documentation links to represents all information's about
the jdk1.5.0.
scr.zip: The zip file is a collection of one of more files that has been compressed or stored to '.zip' extension. Similarly, the
scr.sip file contains the source code of SDK. It become necessary to extract the file that contain the source code from the
ZIP file.
Java is a high level programming language and it is used to develop the robust application. Java application program is
platform independent and can be run on any operating System. Writing Hello World program is very simple. To write the
Hello world program you need simple text editor like note pad and jdk must be install in your machine for compiling and
running. Hello world program is the first step of java programming language. Be careful when you write the java code in
your text pad because java is a case sensitive programming language.
For Example
Write the following code into your note pad to run the Hello World program .
class HelloWorld {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
Save the file and Please remember the location where you save your file. In this example we have saved the file in the "C:\
javatutorial\example" directory. The file name should be match the class name and to save the file give the .java extension.
e.g. HelloWorld.java
Now open the command prompt to compile the HelloWorld.java program. Go to the directory where you have saved the file (
in our case C:\javatutorial\example>) and issue the following command to compile the program:
C:\javatutorial\example>javac HelloWorld.java
javac is a compiler in the java Language. Java compiler change the programming Language into machinery language. So
that the java virtual can understand it. Once the compilation is successful a new file will be created with the
name HelloWorld.class. To run the program issue the following command on command prompt:
C:\javatutorial\example>java HelloWorld
Hello World!
In this lesson you have learned how to write and then test the Hello World! java program.
Now you are familiar with the Java program. In the last lesson you learned how to compile and run the Java program. Before
start hard programming in Java, its necessary to understand each and every part of the program. Lets understand the
meaning of public, class, main, String[] args, System.out, and so on.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Class Declaration:
Class is the building block in Java, each and every methods & variable exists within the class or object. (instance of program
is called object ). The public word specifies the accessibility of the class. The visibility of the class or function can be public,
private, etc. The following code declares a new class "HelloWorld" with the public accessibility:
The main method is the entry point in the Java program and java program can't run without main method. JVM calls the
main method of the class. This method is always first thing that is executed in a java program. Here is the main method:
......
.....
{ and is used to start the beginning of main block and } ends the main block. Every thing in the main block is executed by the
JVM.
The code:
System.out.println("Hello, World");
prints the "Hello World" on the console. The above line calls the println method of System.out class.
The keyword static indicates that the method is a class method, which can be called without the requirement to instantiate
an object of the class. This is used by the Java interpreter to launch the program by invoking the main method of the class
identified in the command to start the program.
Comparing Two Numbers
This is a very simple example of Java that teaches you the method of comparing two numbers and finding out the greater
one. First of all, name a class "Comparing" and take two numbers in this class. Here we have taken a=24 and b=25, now we
have to find out whether a=b, a>b or b>a. To find out this apply if and else condition one by one. Now apply the condition "if
(a=b)", if this satisfies then type that both are equal in the system class. If this doesn't satisfy, then check whether a>b by
applying the "else if" condition and type the message "a is greater than b" in the system class. Again this doesn't satisfy then
'else' condition as shown in the example will show that b is greater than a.
Now compile and run the program and you will find the desired output. If you are getting any error then check the whole
program thoroughly and surely you will get correct result. By compiling and running this exact program, you will find that b is
greater than a.
class Comparing{
public static void main(String[] args) {
int a=24, b=25;
if (a == b){
System.out.println("Both are equal");
}
else if(a>b){
System.out.println("a is greater than b");
}
else{
System.out.println("b is greater than a");
}
}
}
This example of Java programming will teach you the coding for determining the largest number
amongst three. Here we have taken three integers as x = 500, y = 70 and z = 3000. After
defining these three integers under the class "largernumber" apply "if" and "else" conditions that
can help you in finding the largest value one by one.
First check if "x>y". If this satisfies then check whether x>z or not. Again if this satisfies
then write in the system class that "x is greater". Again the term "else" comes when "x"
is not greater than "z". So check again, if "z" is greater than "y" or not. If this satisfies
then type in the system class as "z is greater" otherwise (in the else condition) "y" is
greater. Now check whether "y" is greater than "z" or not.
If "x" is not greater than "y" as per the first condition, then the condition "else" comes
and now you have to check if "y>z" or not. If this satisfies then the output comes as "y is
greater".
Don't get confuse and analyze every condition one by one and follow this example.
class largernumber{
public static void main(String[] args) {
int x=500, y=70, z=3000;
if (x>y){
if (x>z){
System.out.println("x is greater");
}
else{
if(z>y){
System.out.println("z is greater");
}
else{
System.out.println("y is greater");
}
}
}
else{
if (y>z){
System.out.println("y is greater");
}
}
}
}
Here you will learn to write a program for listing out all the even numbers between two numbers.
Write a program to list all even numbers between two numbers
Here you will learn to write a program for listing out all the even numbers between two numbers. For this first create a class
named AllEvenNumunder the java.io package. Now use the try/catch exception to avoid any kind of input error. After this
create a buffer class in which all the input data are stored and modified. Then give message as to "Enter number" in the
System method.
As we have to find out all the even numbers between 1 and the input number, define an integer variable 'num'. Now
apply ParseInt method that parses the string character into decimal integer. Again apply forloop in which define an integer
i=1 and i<= num also with an increment operator. Then apply the ifcondition that i/2=0 i.e. to find even numbers which are
Now and compile and run the program, and enter your desired number to get all even numbers between 1 and this
numbers.
import java.io.*;
class AllEvenNum{
public static void main(String[] args) {
try{
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number : ");
int num = Integer.parseInt(br1.readLine());
System.out.println("Even Numbers:");
for (int i=1;i <=num ; i++){
if(i%2==0 ){
System.out.print(i+",");
}
}
}
catch(Exception e){}
}
}
The given example will teach you the method for preparing a program tocalculate the area and perimeter of a circle. First
of all name a class as "CircleArea" under Java I/O package and define and integer r=o, which is the radius of the circle. Now
use try exception to handle errors and other exceptional events. As we have to input the value of radius here create a
buffered class with an object as 'br1'. This create a buffering character input stream that uses a default sized input buffer.
The InputStreamReader here works as a translator that converts byte stream to character stream. Now type message that
"Enter radius of circle" in the System.out.println method.
Now use the parseInt() method of the Integer class in order to convert from external numeric format to internal format. Now
create the Math class in which all the mathematical functions are defined. This Math class can be imported from the
java.lang.* package. Write the program for both the cases: radius and perimeter.
Before ending the program use the Catch mechanism that detects and catch user input errors. In the end compile and run
the program and enter your desired value as radius for calculating the radius and perimeter of the circle.
import java.io.*;
class CircleArea{
public static void main(String[] args){
int r=0;
try{
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Radius of Circle : ");
r = Integer.parseInt(br1.readLine());
double area = java.lang.Math.PI*r*r;
System.out.println("Area of Circle : "+area);
double perimeter =2*java.lang.Math.PI*r ;
System.out.println("Perimeter of Circle : "+perimeter);
}
catch(Exception e){
System.out.println("Error : "+e);
}
}
}
In this section, you will learn about the palindrome number and how to determine any number is palindrome or not. First of
all we are going to read about the palindrome number. This is the number that the actual number and after reversing this, in
both cases the number is same that is called palindrome number otherwise not. Brief description below:
Description of program:
With the help of this program, we are going to determine whether the given number is palindrome or not. To achieve the
desired result, firstly we have to define a class named "Palindrome". After that we will ask the user to enter any integer type
number and then we will reverse it. After reversing the number we will check whether the given number is palindrome or not.
If the given number is larger, then it will display a message "Out of range!".
import java.io.*;
If you are a newbie in Java programming then our tutorials and examples will be helpful in understanding Java programming
in the most simplest way. Here after reading this lesson, you will be able to write program for calculating the area and
perimeter of a rectangle.
First of all create a class named RecArea under Java.io package. Now define two integer variable 'l' and 'w'. As the
program will be based on keyboard numerical input, it is important for every programmer to use correct data without any
mistake. In this case the exception methods like try/catch mechanism helps in detecting user input errors. So before
starting the functional code, enclosed it with try clause so that any error in the statement causes the execution of the catch
clauses.
Now create an abstract buffer class which is the super class of all classes and represents a stream of input bytes. The
InputSreamReader reads the character stream and stores it in the buffer class. Now use parseInt for both length and width
of the rectangle. This is an instance of class method and is used to convert a string to an integer. Define the area as l*w and
perimeter as 2*(l+w) and in the end use the catch exception.
Now compile and run the program and input the value as you see the message and get the ultimate result. If you find any
kind of error, then check the whole program again.
import java.io.*;
class RecArea
{
public static void main(String[] args)
{
int l=0;
int w=0;
try{
}
}
This tutorial is going to teach you the coding for checking whether a year is a leap year or not. Here, we have taken the year
2000. So define an integer n=2000 in the class "Leapyear" and now apply "if else" condition. As we know leap year is
divided by the integer 4 and so applying if condition as n/4=0, then "n" is a leap year. Now in the System.out.println write the
message that the year is a leap year. Again applying "else" condition the output will be that the year is not a leap year.
class Leapyear
{
public static void main(String[] args)
{
int n=2000;
if (n%4==0){
System.out.println("The given year is a leap year");
}
else{
System.out.println("This is not a leap year");
}
}
}
Download the program:
The programming lesson will teach you the coding for finding and listing out the leap years between two years. In the
following example we have to find out the leap years between 1990 and 2006. First define the two years under a class
"leapyears". Let i = 2006 and n=1990. Now with the help of for loop method initialize the year as n=1990 and n<=i. Also
apply the increment statement in the loop as we have to check one by one.
As we know a leap year is divisible by 4, define an integer l=n%4. So if 'n' is divisible by 4 or l=0, then the particular year can
be a leap year. For checking this, apply the if statement and if this satisfies then, the year will be a leap year. For listing out
each year write "+n" in the System.out.println.
Now compile and run the program in the command window and see the result. If you find any error, check the whole
program and find out the
class leapyears
{
public static void main(String[] args)
{
int i=2006;
int n;
for (n=1990; n<=i ; n++){
int l=n%4;
if (l==0){
System.out.println("leap year: "+n);
}
}
}
}
This tutorial will teach you the methods of preparing the table of a given number by
using loop condition. As we know the loop statements are used to repeat a statement or
process multiple times according to a specified condition. Loop checks certain condition
and if it finds the condition is valuable then all the statements written under loop are
executed.
Here we will take a number a=25 of which we have to prepare a table. Define the
integer a=25 and b=1 as the initial point. Now apply "while" condition of loop and
confine b<=10 as we have to make a table of 25. Again define another integer as c=a*b,
this will be the result when we multiply 'a' with 'b'. Here we have to multiply 'a' with 'b' up
to 10 times like a*1, a*2....................a*9, a*10. So make define b=b+1 as increment
operator.
class PreparingTable{
public static void main(String[] args) {
int a=25, b=1;
System.out.println("the table of "+a+"= ");
while(b<=10){
int c = a*b;
System.out.println(c);
b = b+1;
}
}
}
This lesson of Java programming language will teach you the coding to find out whether a given number is prime or not.
Here we have used the 'for loop' statement and given the required condition for a prime number. As we know, a prime
number is only divided by 1 and itself, in other words it has no other factorial other than 1 and the number itself.
Here, first make a class and named as "Primenumber" and take an integer as num=11, and define an integer 'i' as the
integer other than 1 and the given number. That means, i>2 and i<num. Now apply this in the "for loop" statement and
define an integer n=num/i as given below in the example. Now apply the "if" condition and if the reminder of the earlier
equation comes "0", then the result will be not prime. Again the loop system will check the above condition until it has not
satisfied from the starting point(2) to the end(10). Here under this loop we have to use the "break" statement for
unnecessary checking further one point where the reminder comes zero(0).
Now after checking the whole condition, if the reminders does not come "zero", then we have to again apply the "if" condition
and check whether i=num or not. If it is true then number (num) is prime. As we have taken here as num=11, then after
compiling and running the program, the result will show that num is prime number.
class Prime_number {
public static void main(String[] args) {
int num = 11;
int i;
for (i=2; i < num ;i++ ){
int n = num%i;
if (n==0){
System.out.println("not Prime!");
break;
}
}
if(i == num){
System.out.println("Prime number!");
}
}
}
This Java programming tutorial, we will be read how to get prime number between 1 to given number. First of all we have to
define a class "PrimeNumber". Java I/O package has a input stream and a output stream in which input stream is used for
reading the stream and memory allocating and the output stream used for writing bytes. As in this program we are going to
insert certain instruction by creating buffer reader class. Here we have to create a buffer for the string class that can be used
to instantiate a changeable object for storing and processing a string of character. Now use the ParseInt method for
converting the parses the string argument and define 'num' as an integer.
Now applying in this program we use two 'for' loop. For loop will start from 1 to entered number. And another loop will start
and divide it from 2 to less than those number. If number is divided by any number that means it is not prime otherwise
prime number.
import java.io.*;
class PrimeNumber {
public static void main(String[] args) throws Exception{
int i;
BufferedReader bf = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter number:");
int num = Integer.parseInt(bf.readLine());
System.out.println("Prime number: ");
for (i=1; i < num; i++ ){
int j;
for (j=2; j<i; j++){
int n = i%j;
if (n==0){
break;
}
}
if(i == j){
System.out.print(" "+i);
}
}
}
}
Java is a object oriented programming and to understand the functionality of OOP in Java, we first need to understand several
fundamentals related to objects. These include class, method, inheritance, encapsulation, abstraction, polymorphism etc.
Class - It is the central point of OOP and that contains data and codes with behavior. In Java
everything happens within class and it describes a set of objects with common behavior. The
class definition describes all the properties, behavior, and identity of objects present within that
class. As far as types of classes are concerned, there are predefined classes in languages like C++
and Pascal. But in Java one can define his/her own types with data and code.
Object - Objects are the basic unit of object orientation with behavior, identity. As we
mentioned above, these are part of a class but are not the same. An object is expressed by the
variable and methods within the objects. Again these variables and methods are distinguished
from each other as instant variables, instant methods and class variable and class methods.
Methods - We know that a class can define both attributes and behaviors. Again attributes are
defined by variables and behaviors are represented by methods. In other words, methods define
the abilities of an object.
Inheritance - This is the mechanism of organizing and structuring software program. Though
objects are distinguished from each other by some additional features but there are objects that
share certain things common. In object oriented programming classes can inherit some common
behavior and state from others. Inheritance in OOP allows to define a general class and later to
organize some other classes simply adding some details with the old class definition. This saves
work as the special class inherits all the properties of the old general class and as a programmer
you only require the new features. This helps in a better data analysis, accurate coding and
reduces development time.
Abstraction - The process of abstraction in Java is used to hide certain details and only show the
essential features of the object. In other words, it deals with the outside view of an object
(interface).
Polymorphism - It describes the ability of the object in belonging to different types with specific
behavior of each type. So by using this, one object can be treated like another and in this way it
can create and define multiple level of interface. Here the programmers need not have to know
the exact type of object in advance and this is being implemented at runtime.
Java Exception - Exception Handling in Java
Exception, that means exceptional errors. Actually exceptions are used for handling errors in programs that occurs during
the program execution. During the program execution if any error occurs and you want to print your own message or the
system message about the error then you write the part of the program which generate the error in the try{} block and catch
the errors using catch() block. Exception turns the direction of normal flow of the program control and send to the
related catch() block. Error that occurs during the program execution generate a specific object which has the information
about the errors occurred in the program.
In the following example code you will see that how the exception handling can be done in java program. This example
reads two integer numbers for the variables a and b. If you enter any other character except number ( 0 - 9 ) then the error is
caught by NumberFormatException object. After thatex.getMessage() prints the information about the error occurring
causes.
import java.io.*;
In the given example there are some identifiers have been used like byteident, shortident, intident, longident, charident,
stringident, floatident, doubleident. And there are some primitive data types of used identifiers have been also used in the
program like byte, short, int, long, float, double, char andString.
All the data type has it's own capacity to keep the maximum value. Which have been mentioned below :
Integers
Real numbers
Other types
Source: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html
Variable : You can assign the values to the variable once it has been declared. The values of the variable can be changed
anywhere in the program if the variable is accessible in that scope. In this example we have used the variable intvariable to
illustrate this.
Constants: Constants are declared using the final keyword. The values of the constant can't be changed once its declared.
Literal : literal is an explicit number or string constant used in Java programs. This specifies the syntax of your declaration
of different types of values and operations. That mean literal is totally based on the syntax. Whenever you want to show the
message with java special symbols then you have to use the literals. For example to show the message "Directory of this file
: c:\code\varconstltr.java" then you can write as shown below
There are three type of literals : Numeric Literals, Char type Literals, String Literals as follows.
In the section of Java Tutorial you will learn how to write java program to read file line by line. We will use the
DataInputStream class to Read text File Line by Line.
Class DataInputStream
A data input stream is use to read primitive Java data types from an underlying input stream in a machine-independent way.
An application uses a data output stream to write data that can later be read by a data input stream.
Data input streams and data output streams represent Unicode strings in a format that is a slight modification of UTF-8. (For
more information, see X/Open Company Ltd., "File System Safe UCS Transformation Format (FSS_UTF)", X/Open
Preliminary Specification, Document Number: P316. This information also appears in ISO/IEC 10646, Annex P.) Note that in
the following tables, the most significant bit appears in the far left-hand column.
BufferedReader
Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays,
and lines.
The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
In general, each read request made of a Reader causes a corresponding read request to be made of the underlying
character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations
may be costly, such as FileReaders and InputStreamReaders. For example,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be
read from the file, converted into characters, and then returned, which can be very inefficient.
Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an
appropriate BufferedReader.
Here is the code of java program to Read text File Line by Line:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
This example illustrates how to copy contents from one file to another file. This topic is related to the I/O
(input/output) ofjava.io package.
In this example we are using File class of java.io package. The File class is an abstract representation of file and directory
pathnames. This class is an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two
components:
Explanation
This program copies one file to another file. We will be declaring a function called copyfile which copies the contents from
one specified file to another specified file.
The function copyfile(String srFile, String dtFile) takes both file name as parameter. The function creates a new File instance
for the file name passed as parameter
and creates another InputStream instance for the input object and OutputStream instance for the output object passed as
parameter
import java.io.*;
In the section of Java Tutorial you will learn how to write java program to write to a file. We will use the class FileWriter and
BufferedWriter to write to a file.
Class FileWriter
The FileWriter is a class used for writing character files. The constructors of this class assume that the default character
encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter
on a FileOutputStream.
BufferedWriter
The BufferWriter class is used to write text to a character-output stream, buffering characters so as to provide for the
efficient writing of single characters, arrays, and strings.
import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
In the section of Java Tutorial you will learn how to create directory using java program. This program also explains the
process of creating all non-existent ancestor directories automatically. We will use the class File class to crate the directory.
Class File
The File class an abstract representation of file and directory pathnames. File class is used to interact with the files system.
Here is the code for creating directory and all non-existing ancestor directories:
import java.io.*;
class CreateDirectory
{
public static void main(String args[])
{
try{
String strDirectoy ="test";
String strManyDirectories="dir1/dir2/dir3";
This example illustrates how to delete the specified file or directory after checking weather the file exists or not.
This topic is related to the I/O (input/output) of java.iopackage.
In this example we are using File class of java.io package. The File class is an abstract representation of file and directory
pathnames.
Explanation
This program deletes the specified file if that exists. We will be declaring a function called deletefilewhich deletes the
specified directory or file.
deletefile(String file)
The function deletefile(String file) takes file name as parameter. The function creates a new File instance for the file name
passed as parameter
and delete the file using delete function f1.delete(); which return the Boolean value (true/false). It returnstrue if and only if
the file or directory is successfully deleted; false otherwise.
delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the
directory must be empty in order to be deleted.
Returns:
true if and only if the file or directory is successfully deleted; false otherwise
import java.io.*;
This example illustrates how to count the number of lines, number of words and number of characters in the
specified file. Program takes the file name as parameter and it counts the number of words and lines present in the file.
Parameter is optional and if you simply run the program without mentioning the file name then you will have to input some
strings and program will count the number of characters and number of words for your given strings. This topic is related to
the I/O (input/output) of java.io package.
In this example we are using FileReader class of java.io package. The File class is an abstract representation of file and
directory pathnames.
Explanation
This program counts the number of lines, number of words and number of characters in the specified file. We will be
declaring two functions called wordcount and linecount in the program. The function linecount has been overloaded
according to the passing argument. If you input contents through the file then linecount function will be called (If specified file
exists) otherwise main function counts the number of characters and number of lines (always, the number of line will be only
1 in this condition) itself but for the counting of the number of words by using the wordcount function.
wordcount(String line)
The function wordcount(String line) takes either the content of the specified file or arguments passed with the run command
for a java program as parameter 'String line'. The wordcount() function is usingarrayname.charAt(index) to find position of
space in the string. A counter variable 'numWords' is used to count the number of words.
linecount(String fileName);
The function linecount(String fileName) takes the specified file name as a string parameter and create a instance for the
FileReader class to buffering then the file or string and it is passed to the function linecount(String fName, BufferedReader
in).
The function linecount(String fName, BufferedReader in) takes the specified file name and created instance in for the
BufferedReader class by calling function linecount(String fileName) and assign the content of the buffer in a string
variable line. And then the function linecount(String fileName, BufferedReader) counts and print the number of characters,
number of lines. To count the number of words call the wordcount(String line) function.
import java.io.*;
In this example you will learn about Mathclass. This example explains how you can use functions provided by the Math class
like E, PI, round, abs, ceil, exp, floor,IEEEremainder, max, min, pow, random,rint, sqrt etc. to manipulate the mathematical
operation in your program. The Math class is used to operate the calculations. There is not necessary to import any package
for the Math class because this is already in java.lang package.
Any expressions can be operated through certain method calls. There are some functions have been used in the given
example. All the functions have been explained below with example :
This is E field of the Math class which returns you a default exponent value that is closer than any other to e, the base of the
natural logarithms.
PI
This is also a field of the Method class which returns you a default pi value, the ratio of the circumference of a circle to its
diameter.
abs()
This is the abs() function which returns you the absolute number.
ceil()
This is the ceil() function which returns you the smallest value but greater than the argument.
exp()
This is the exp() function which returns you the exponential value raised to the power of a double value.
floor()
This is the floor() function which returns you the largest value but less than the argument.
IEEEremainder()
This is the IEEEremainder() which returns you the remainder for the given dividend and divisor.
max()
This is the max() function which distinguishes the maximum value from the two given value.
min()
This is the min() function which distinguishes the minimum value from the two given value.
pow()
This is the pow() function which returns you the number raised to the power of a first given value by the another one.
random()
This is the random() function which returns you the random number. It is absolutely system generated.
rint()
This is the rint() function which returns you a value closest to the given value.
round()
This is the round() function which returns you a value that is in the rounded form.
sqrt()
This is the sqrt() function which returns you the square root of the specified value.
Math.IEEEremainder(5.3f,2.2f));
//max()
System.out.println("Maximum Number = " +
Math.max(10,10.3));
//min()
System.out.println("Minimum Number = " +
Math.min(10,10.3));
//pow()
System.out.println("Power = " + Math.pow(10,3));
//random()
System.out.println("Random Number = " +
Math.random());
//rint()
System.out.println("Closest to the Argument
= " + Math.rint(30));
//round()
System.out.println("Round = " + Math.round(Math.E));
//sqrt()
System.out.println("Square Root = " + Math.sqrt(400));
}
}
In this example you will learn about StringBuffer class. This example explains how you can use functions provided by the
StringBuffer class like append, insert, reverse, setCharAt, charAt, length, deleteCharAt, substring, delete, capacityetc. to
manipulate the string operation in your program.
The StringBuffer class is used to represent characters that can be modified. This is simply used for concatenation or
manipulation of the strings.
StringBuffer is mainly used for the dynamic string concatenation which enhances the performance. A string buffer
implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it
contains some particular sequence of characters, but the length and content of the sequence can be changed through
certain method calls. There are some functions used in the given example. All the functions have been explained below with
example :
append()
This is the append() function used for the concatenate the string in string buffer. This is better to use for dynamic string
concatenation. This function works like a simple string concatenation such as : String str = str + "added string";.
insert()
This is the insert() function used to insert any string or character at the specified position in the given string.
reverse()
This is the reverse() function used to reverse the string present in string buffer.
setCharAt()
This is the setCharAt() function which is used to set the specified character in buffered string at the specified position of the
string in which you have to set the given character.
charAt()
This is the charAt() function which is used to get the character at the specified position of the given string.
substring()
This is the substring() function which is used to get the sub string from the buffered string from the initial position to end
position (these are fixed by you in the program).
deleteCharAt()
This is the deleteCharAt() function which is used to delete the specific character from the buffered string by mentioning that's
position in the string.
length()
This is the length() function is used to finding the length of the buffered string.
delete()
This is the delete() function is used to delete multiple character at once from n position to m position (n and m are will be
fixed by you.) in the buffered string.
capacity()
This is the capacity() function is used to know about the current characters kept which is displayed like : number of
characters + 6.
import java.io.*;
//append()
strbuf.append("Hello");
strbuf.append("World");
//print HelloWorld
System.out.println(strbuf);
//insert()
strbuf.insert(5,"_Java ");
//print Hello_Java World
System.out.println(strbuf);
//reverse()
strbuf.reverse();
System.out.print("Reversed string : ");
System.out.println(strbuf);
//print dlroW avaJ_olleH
strbuf.reverse();
System.out.println(strbuf);
//print Hello_Java World
//setCharAt()
strbuf.setCharAt(5,' ');
System.out.println(strbuf);
//prit Hello Java World
//charAt()
System.out.print("Character at 6th position : ");
System.out.println(strbuf.charAt(6));
//print J
//substring()
System.out.print("Substring from position 3 to 6 : ");
System.out.println(strbuf.substring(3,7));
//print lo J
//deleteCharAt()
strbuf.deleteCharAt(3);
System.out.println(strbuf);
//print Helo java World
//capacity()
System.out.print("Capacity of StringBuffer object : ");
System.out.println(strbuf.capacity()); //print 21
This example illustrates that what is type casting? Type Casting refers to changing an entity of one datatype into
another. This is important for the type conversion in developing any application. If you will store a int value into a byte
variable directly, this will be illegal operation. For storing your calculated int value in a byte variable you will have to change
the type of resultant data which has to be stored. This type of operation has illustrated below :
In this example we will see that how to convert the data type by using type casting. In the given line of the
code c = (char)(t?1:0); illustrates that if t which is boolean type variable is true then
value of c which is the char type variable will be 1 but 1 is a numeric value.
So, 1 is changed into character according to the Unicode value. But in this
line c = (char)(t?'1':'0'); 1 is already given as a character which will be stored as it is in the char type
variable c.
Array: Array is the most important thing in any programming language. By definition, array is the static memory allocation. It
allocates the memory for the same data type in sequence. It contains multiple values of same types. It also store the values
in memory at the fixed size. Multiple types of arrays are used in any programming language such as: one - dimensional, two
- dimensional or can say multi - dimensional.
Declaration of an array:
int num[]; or int num = new int[2];
Some times user declares an array and it's size simultaneously. You may or may not be define the size in the declaration
time. such as:
int num[] = {50,20,45,82,25,63};
In this program we will see how to declare and implementation. This program illustrates that the array working way. This
program takes the numbers present in the num[] array in unordered list and prints numbers in ascending order. In this
program the sort() function of the java.util.*; package is using to sort all the numbers present in the num[] array.
The Arrays.sort() automatically sorts the list of number in ascending order by default. This function held the argument which
is the array name num.
import java.util.*;
C:\chandan>javac array.java
C:\chandan>java array
Given number : 50 20 45 82 25 63
This is a program that follows one dimensional array. In this program, firstly we have to define a class"CopyArray".
Now, we take two integer type array like: array1[] and array2[]. The array1[] contains some integer type values (2,3,4,5,8,9)
and another is blank. After initializing this, now we get number of rows and columns by using the array1.length. We use
the 'for' loop statement for displaying and copying ( array1[j] = array2[j] ) the array.
In this section, you will get the detailed explanation about the charAt() method ofString class. We are going for
usingcharAt() method. You can see how to use the method by syntax. There is a section provided for understanding the
usage of the method practically.
Description of program:
Here, you will understand about the procedure of the charAt() method through the following java program. This program
reads a string as input through the keyboard. And first this shows the length of the string then find the character at the 4th
(mentioned as a parameter of the method) position of the string that is retrieved by using charAt() method. This method
takes a parameter that is the position of the string. The charAt() method returns a character value for the character at the
given position of the string.
import java.io.*;
class CharAt{
public static void main(String[] args){
try{
BufferedReader object=
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String");
String s=object.readLine();
int len=s.length();
System.out.println(len);
char char1=s.charAt(4);
System.out.println(char1);
}
catch(Exception e){}
}
}
C:\java_work>java CharAt
Enter the String
roseindia
9
i
C:\java_work>
In this section, you will learn how to uselength() method of the String class. We are going to using length() method. These
method are illustration as follow here:
Description of program:
Here, we will know that how many character of length in String. First of all, we have to define class named "StringLength".
Inside of class we have to define method of class in main class. After that we create one method which returns the integer
type values. So we are using to length() method of the String class for the purpose.
length() method : This method return the length of this string as an integer value.
import java.io.*;
class StringLength{
public static void main(String[] args){
try{
BufferedReader object=
new BufferedReader (new InputStreamReader(System.in));
System.out.println("Eneter string value:");
String s=object.readLine();
int len=s.length();
System.out.println(len);
}
catch(Exception e){}
}
}
C:\java_work>javac
StringLength.java
C:\java_work>java StringLength
Eneter string value:
amar
4
C:\java_work>
In this section, you will learn how to use toUpperCase() method of the String class.
In this section, you will learn how to usetoUpperCase() method of the String class. We are going for
Description of program:
Here, you will see the procedure of converting letters of the string in uppercase letter. So, we are using toUpperCase()
Output of program:
C:\java_work>javac
ConvertInUpperCase.java
C:\java_work>java
ConvertInUpperCase
String is : india
String in uppercase letter: INDIA
C:\java_work>
In this section, you will learn how to usestring array in Java. Here, you will see how to declare a string array and the syntax
for using in the program. This section provides you a simple java program which illustrates about the string array in very
efficient manner.
Program Description:
Following code of the program declares a string array and store some strings like "chandan", "tapan", "Amar", "santosh", and
"deepak" to it. And in the main method these string are displayed one by one by retrieving from the specified string array
named roseindia. In this program all the string values are stored in the roseindia string array at the declaration time.
Here is the code of this program:
class StringCharacter
{
static String[] roseindia={"chanan","tapan","Amar","santosh","deepak"};
public static void main(String args[]){
for(int i=0;i<5;i++){
System.out.println(roseindia[i]);
}
}
}
Output of program:
C:\>javac StringCharacter.java
C:\>java StringCharacter
chanan
tapan
Amar
santosh
deepak
C:\>
Average of Array
In this section, we will learn how to get an average of array. For this, first of all we have to define a class
name "ArrayAverage"that has double type array to contain some values. Now we take a double type data that calculates
the average of array (result/nums.length). And finally it will display the result on the command prompt with message by
using the System.out.println().
In Java tutorial, you will learn about array and matrix. An array is the collection of same data type values. If we create a
variable of integer type then, the array of int can only store the int values. It can't store other than int data type.
Description of program:
In this program we are going to implement a matrix. To make a program over the two dimensional array, first of all we have
to declare class named as MatrixExample that has one static methodoutputArray() which takes integer type array and
represents it. For displaying the matrix we need to its rows and column by using the array.length method. Now, we use
the for loop to print all the values stored in the array. At last use the main() method inside which we are going to declare the
values of the multidimensional array which we are going to use. Call the outputArray() method inside the main method. The
output will be displayed to the user by println() method.
class MatrixExample{
public static void main(String[] args) {
int array[][]= {{1,3,5},{2,4,6}};
System.out.println("Row size= " + array.length);
System.out.println("Column size = " + array[1].length);
outputArray(array);
}
In this section, we are going to calculate the sum of two matrix and containing its rows and columns. See below for better
understanding to this.
In this program we are going to calculate the sum of two matrix. To make this program, we need to declare two dimensional
array of type integer. Firstly it calculates the length of the both the arrays. Now we need to make a matrix out of it. To make
the matrix we will use the for loop. By making use of the for loop the rows and column will get divide. This process will be
performed again for creating the second matrix.
After getting both the matrix with us, we need to sum both the matrix. The both matrix will be added by using the for loop
with array[i][j]+array1[i][j]. The output will be displayed by using the println() method.
class MatrixSum{
public static void main(String[] args) {
int array[][]= {{4,5,6},{6,8,9}};
int array1[][]= {{5,4,6},{5,6,7}};
System.out.println("Number of Row= " + array.length);
System.out.println("Number of Column= " + array[1].length);
int l= array.length;
System.out.println("Matrix 1 : ");
for(int i = 0; i < l; i++) {
for(int j = 0; j <= l; j++) {
System.out.print(" "+ array[i][j]);
}
System.out.println();
}
int m= array1.length;
System.out.println("Matrix 2 : ");
for(int i = 0; i < m; i++) {
for(int j = 0; j <= m; j++) {
System.out.print(" "+array1[i][j]);
}
System.out.println();
}
System.out.println("Addition of both matrix : ");
for(int i = 0; i < m; i++) {
for(int j = 0; j <= m; j++) {
System.out.print(" "+(array[i][j]+array1[i][j]));
}
System.out.println();
}
}
}
Output of program:
C:\amar work>javac
MatrixSum.java
This is a simple java program that teaches you for multiplying two matrix to each other. Here providing you Java source
code with understanding the Java developing application program. We are going to make a simple program that will multiply
two matrix. Two dimensional array represents the matrix.
Now, make this program, you have to declare two multidimensional array of type integer. Program uses two for loops to get
number of rows and columns by using the array1.length. After getting both matrix then multiply to it. Both matrix will be
multiplied to each other by using 'for' loop. So the output will be displayed on the screen command prompt by using
the println() method.
class MatrixMultiply{
public static void main(String[] args) {
int array[][] = {{5,6,7},{4,8,9}};
int array1[][] = {{6,4},{5,7},{1,1}};
int array2[][] = new int[3][3];
int x= array.length;
System.out.println("Matrix 1 : ");
for(int i = 0; i < x; i++) {
for(int j = 0; j <= x; j++) {
System.out.print(" "+ array[i][j]);
}
System.out.println();
}
int y= array1.length;
System.out.println("Matrix 2 : ");
for(int i = 0; i < y; i++) {
for(int j = 0; j < y-1; j++) {
System.out.print(" "+array1[i][j]);
}
System.out.println();
}
array2[i][j] += array[i][k]*array1[k][j];
}
}
}
System.out.println("Multiply of both matrix : ");
for(int i = 0; i < x; i++) {
for(int j = 0; j < y-1; j++) {
System.out.print(" "+array2[i][j]);
}
System.out.println();
}
}
}
This is a simple java program for implementing the two dimensional array program and its square. This session provide you
the best explanation with mathematical operation.
Description of progarm:
We are going to display the square of two matrix. Firstly, we have to define a class "SquareMatrix". Then we take an
integer type array that contains integer type values. After this, we use two 'for' loop that denotes rows and columns of a
matrix. After getting both the matrix with us we need to square both matrix. When we go to square this array then we use
"square[i][j] =square[i][j] * square[i][j]". So, the output will be displayed on the screen command prompt by using
the println() method.
Check Even-Odd:-Example
Now, you have to learn about the syntax of If - Else construct. How the If - Else construct used to flow the program control as
for as needed. If - Else construct has illustrated by a given example.
Given example reads a integer value and check weather number is Odd or Even. In this example you will learn how to
determine the Even or Odd for the given number entered through the keyboard. If the given condition is true then print the
message Given number is Even otherwise the control of the program will jumps in the else block and print the
message Given number is Odd. In this example a special exception has been also used, that
is NumberFormatException which holds the error during the checking the entered data format. Entered data must be a
number not a character or string. If you enter anything except numeric value then normal flow of the program is sent to the
catch block and print the specified message. Full running code is provided with the example.
import java.io.*;
The java programming language supports the following types of controlling statements such as:
1.The break statement
2.The continue statement
3.The return statement
Break: The break statement is used in many programming languages such as c, c++, java etc. Some times we need to exit
from a loop before the completion of the loop then we use break statement and exit from the loop and loop is terminated.
The break statement is used in while loop, do - while loop, for loop and also used in the switch statement.
C:\chandan>javac Break.java
C:\chandan>java Break
The Prime number in between 1 - 50 :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Continue: The continue statement is used in many programming languages such as C, C++, java etc. Sometimes we do not
need to execute some statements under the loop then we use the continue statement that stops the normal flow of the
control and control returns to the loop without executing the statements written after the continue statement. There is the
difference between break and continue statement that the break statement exit control from the loop but continue statement
keeps continuity in loop without executing the statement written after the continue statement according to the conditions.
In this program we will see that how the continue statement is used to stop the execution after that.
C:\chandan>javac Continue.java
Continue.java:12: unreachable
statement
a = i;
^
1 error
C:\chandan>javac
Continue.java
C:\chandan>java Continue
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
Switch is the control statement in java which also turns the normal flow control of the program as per conditions. It works
same as If-Else construct. This is the difference between Switch and If-Else construct that switch is used for reduce the if
statements. If the multiple choices are available then we generally use the If-Else construct otherwise Switch is easier than
the If-Else construct. Switch checks your choice and jump on that case label if the case exists otherwise control is sent to the
default label.
In this Program you will see that how to use the switch statement. This program take a number and check weather the
number lies between 1 to 7. If user enters the number between 1 to 7 then program print the name of the day in sequence
like for 1 prints Sunday, for 2 prints Monday and so on otherwise prints the message Invalid entry!. If user enters any
character then the message will be printed by catchblock. This program also using the break statement. The normal flow of
control quits from the Switch block whenever break statement occurs. Full running program code is provided with the
example.
import java.io.*;
While Loop
Loop is the control statement of any language in which whenever you want to perform the repetitious work then you use
the Loop control statement. There are mainly three types of loops. Loop repeats a statement or a process multiple times
according to the specified conditions. It allows the multiple statements or process to be run for the specified time or it also
follows the certain conditions. Loop makes your program readable, flexible and reliable.
While loop: While loop checks the certain condition first, if the condition is true then all the statements or processes written
under the while loop are executed otherwise ignored all.
In some conditions in java, you need to run some statements and processes once at least. For that you have to use the do
while loop in after that check the condition then we use the do-while loop statement. do-while loop is same as the while loop
statement but while loop checks the certain condition is first and if condition is true then statements or processes are
executed otherwise all the statements written under the while loop is ignored by the interpreter but do - while loop executes
all the statements first at once and then check the condition if the condition is true then all the statements are also executed
in second times otherwise second times ignored all the statements.
do
{
statements;
}
while(condition);
In this example you will see how to use the do-while loop statement. The values are already given the variable n and r in the
program after that it calculate the program and its perform the its original number and its reverse number.
Here is the code of the program:-
The for loop is the type of looping construct. It also works as while loop construct but it provide the initialization, condition
and the increment is same written in the for construct. All the statements which has to be executed written in the for block.
We can use the multiple for loop in a program or a for loop also. When we write a loop under another loop then the second
loop is called nested loop.
The given example illustrates that how to use the for loop for developing a application or a program. In this program we will
see that the initialization of the variable, condition and increment used for the for loop. Initialization, Condition and
Incrementation, all are optional but two semicolons are compulsory which separates Initialization, Condition and
Incrementation.
1
22
333
4444
55555
Class : Whatever we can see in this world all the things are a object. And all the objects are categorized in a special group.
That group is termed as a class. All the objects are direct interacted with its class that mean almost all the properties of the
object should be matched with it's own class. Object is the feature of a class which is used for the working on the particular
properties of the class or its group. We can understand about the class and object like this : we are all the body are different
- different objects of the human being class. That means all the properties of a proper person relates to the human being.
Class has many other features like creation and implementation of the object, Inheritance etc.
In this Program you will see how to use the class, object and it's methods. This program uses the several values of several
defined variables for getting the Area and Perimeter of the Square and Rectangle by calling the different functions from the
different classes through the several objects created for the several class. In this program there are two classes has been
used except the main class in which the main function is declared. First class is square which is using for getting the Area
and Perimeter of the square and another class is rectangle which is using for getting the Area and Perimeter of the
Rectangle. All the functions in the square and rectangle class are calling with different - different arguments two times for
getting the Area and Perimeter of square and rectangle for two different sides. This program gives us the Area and
Perimeter for the different sided Square and Rectangle separately. Full running code is given with the example :
class square{
int sqarea(int side){
int area = side * side;
return(area);
}
int sqpari(int side){
int pari = 4 * side;
return(pari);
}
}
class rectangle{
int rectarea(int length,int breadth){
int area = length * breadth;
return(area);
}
int rectpari(int length,int breadth){
int pari = 2*(length + breadth);
return(pari);
}
}
public class ObjectClass{
public static void main(String args[]){
int sarea1,sarea2,pari1,pari2;
int rectarea1,rectarea2,rectpari1,rectpari2;
square sq = new square();
rectangle rect = new rectangle();
int a=20;
System.out.println("Side of first square = " + a);
sarea1 = sq.sqarea(a);
pari1 = sq.sqpari(a);
System.out.println("Area of first square = " + sarea1);
System.out.println("Parimeter of first square = " + pari1);
a = 30;
System.out.println("Side of second square = " + a);
sarea2 = sq.sqarea(a);
pari2 = sq.sqpari(a);
System.out.println("Area of second square = " + sarea2);
System.out.println("Parimeter of second square = " + pari2);
int x = 10, y = 20;
System.out.println("Length of first Rectangle = " + x);
System.out.println("Breadth of first Rectangle = " + y);
rectarea1 = rect.rectarea(x,y);
rectpari1 = rect.rectpari(x,y);
System.out.println("Area of first Rectangle = " + rectarea1);
System.out.println("Parimeter of first Rectangle = " + rectpari1);
x = 15;
y = 25;
System.out.println("Length of second Rectangle = " + x);
System.out.println("Breadth of second Rectangle = " + y);
rectarea2 = rect.rectarea(x,y);
rectpari2 = rect.rectpari(x,y);
System.out.println("Area of second Rectangle = " + rectarea2);
System.out.println("Parimeter of first Rectangle = " + rectpari2);
}
}
Object : Objects are the basic run time entity or in other words object is a instance of a class . An object is a software
bundle of variables and related methods of the special class. In the above example the sq is the object of square class and
rect is the object of the rectangle class. In real-world objects share two characteristics: They have all state and behavior. For
example, The squares have state such as : sides and behaviors such as its areas and perimeters. Rectangles have state
such as: length, breadth and behavior such as its areas and perimeters. A object implements its behavior with methods of
it's classes. A method is a function (subroutine) associated with an object.
C:\chandan>javac ObjectClass.java
C:\chandan>java ObjectClass
Side of first square = 20
Area of first square = 400
Parimeter of first square = 80
Side of second square = 30
Area of second square = 900
Parimeter of second square = 120
Length of first Rectangle = 10
Breadth of first Rectangle = 20
Area of first Rectangle = 200
Parimeter of first Rectangle = 60
Length of second Rectangle = 15
Breadth of second Rectangle = 25
Area of second Rectangle = 375
Parimeter of first Rectangle = 80
Every class has at least one it's ownconstructort. Constructor creates a instance for the class. Constructor initiates (initialize)
something related to the class's methods. Constructor is the method which name is same to the class. But there are many
difference between the method (function) and the Constructor.
In this example we will see that how to to implement the constructor feature in a class. This program is using two classes.
First class is another and second is the main class which name is Construct. In theConstruct class two objects (a and b) are
created by using the overloaded another Constructor by passing different arguments and calculated the are of the different
rectangle by passing different values for the another constructor.
class another{
int x,y;
another(int a, int b){
x = a;
y = b;
}
another(){
}
int area(){
int ar = x*y;
return(ar);
}
}
public class Construct{
public static void main(String[] args)
{
another b = new another();
b.x = 2;
b.y = 3;
System.out.println("Area of rectangle : " + b.area());
System.out.println("Value of y in another class : " + b.y);
another a = new another(1,1);
System.out.println("Area of rectangle : " + a.area());
System.out.println("Value of x in another class : " + a.x);
}
}
C:\chandan>javac Construct.java
C:\chandan>java Construct
Area of rectangle : 6
Value of x in another class : 3
Area of rectangle : 1
Value of x in another class : 1
Here, you will learn more aboutConstructor and how constructors are overloaded in Java. This section provides you a brief
introduction about theConstructor that are overloaded in the given program with complete code absolutely in running state
i.e. provided for best illustration about the constructor overloading in Java.
Constructors are used to assign initial values to instance variables of the class. A default constructor with no arguments will
be called automatically by the Java Virtual Machine (JVM). Constructor is always called by new operator. Constructor are
declared just like as we declare methods, except that the constructor don't have any return type. Constructor can be
overloaded provided they should have different arguments because JVM differentiates constructors on the basis of
arguments passed in the constructor.
Whenever we assign the name of the method same as class name. Remember this method should not have any return
type. This is called as constructor overloading.
We have made one program on a constructor overloading, after going through it the concept of constructor overloading will
get more clear. In the example below we have made three overloaded constructors each having different arguments types
so that the JVM can differentiates between the various constructors.
class Rectangle{
int l, b;
float p, q;
public Rectangle(int x, int y){
l = x;
b = y;
}
public int first(){
return(l * b);
}
public Rectangle(int x){
l = x;
b = x;
}
public int second(){
return(l * b);
}
public Rectangle(float x){
p = x;
q = x;
}
public float third(){
return(p * q);
}
public Rectangle(float x, float y){
p = x;
q = y;
}
public float fourth(){
return(p * q);
}
}
C:\java>java ConstructorOverloading
The area of a rectangle in first constructor
is : 8
The area of a rectangle in first constructor
is : 25
The area of a rectangle in first constructor
is : 4.0
The area of a rectangle in first constructor
is : 6.0
The keyword this is useful when you need to refer to instance of the class from its method. The keyword helps us to avoid
name conflicts. As we can see in the program that we have declare the name of instance variable and local variables same.
Now to avoid the confliction between them we use this keyword. Here, this section provides you an example with the
complete code of the program for the illustration of how to what is this keyword and how to use it.
In the example, this.length and this.breadth refers to the instance variable length and breadth while length and breadth
refers to the arguments passed in the method. We have made a program over this. After going through it you can better
understand.
class Rectangle{
int length,breadth;
void show(int length,int breadth){
this.length=length;
this.breadth=breadth;
}
int calculate(){
return(length*breadth);
}
}
public class UseOfThisOperator{
public static void main(String[] args){
Rectangle rectangle=new Rectangle();
rectangle.show(5,6);
int area = rectangle.calculate();
System.out.println("The area of a Rectangle is : " + area);
}
}
C:\java>java UseOfThisOperator
The area of a Rectangle is : 30
Thread is the feature of mostly languages including Java. Threads allow the program to perform multiple tasks
simultaneously. Process speed can be increased by using threads because the thread can stop or suspend a specific
running process and start or resume the suspended processes. Multitasking or multiprogramming is delivered through the
running of multiple threads concurrently. If your computer does not have multi-processors then the multi-threads really do
not run concurrently.
This example illustrates how to create a thread and how to implement the thread. In this example we will see that the
program prints numbers from 1 to 10 line by line after 5 seconds which has been declared in the sleep function of the thread
class. Sleep function contains the sleeping time in millisecond and in this program sleep function has contained 5000
millisecond mean 5 second time. There is sleep function must caught by the InterruptedException. So, this program used
theInterruptedException which tells something the user if thread is failed or interrupted.
This section illustrates you how to calculate occurrences of elements in an array. Occurrences means, the how many times
an element occurs in the array. In this section, you will get more and more help from the given following program with the
complete code.
Program Description:
This program first asks for the length of the array whatever you want to fix and then it takes some inputs for the elements of
the array how more you have mentioned for the length of the array. And finally it show the occurrences of each and every
element of the array uniquely.
import java.io.*;
C:\chandan>javac OccurancesInArray.java
C:\chandan>java OccurancesInArray
How many elements you want to enter in the array: 5
123
chand
453
aaa
123
Occurance of '123' : 2
Occurance of 'chand' : 1
Occurance of '453' : 1
Occurance of 'aaa' : 1
C:\work\chandan>_
As we know that JVM reads each data type in a String format. Now consider a case where we to enter a value in int
primitive type, then we have to use int x = Integer.parseInt("any String") , because the value we have entered is in integer
but it will be interpreted as a String so, we have to change the string into integer. Here Integer is a name of a class
in java.lang package and parseInt() is a method ofInteger class which converts String to integer. If we want to enter a
integer in a method or class using keyboard, then we have to use a method parseInt().
In this program we are going to calculate a area of a rectangle by using two classes named Rectangle and
EnterValuesFromKeyboard. In the first class we have used two methods, show(int x, int y) andcalculate(). First
method show() is taking two variables as input and second method calculate()calculates the area of a rectangle. In the
second class which is also our main class we declare a will declare our main method. Inside this method we will create a
object of a Rectangle class. Now we ask the user to input two values and stored those values in the variables. These
entered values will be changed into integer by using parseInt() method. Now these variables are passed in the
method show()and the area will be calculated by calculate() method. These methods will be called by the instance of
Rectangle class because it is the method of Rectangle class.
class Rectangle{
int length, breadth;
void show(int x, int y){
length = x;
breadth = y;
}
int calculate(){
return(length * breadth);
}
}
public class EnterValuesFromKeyboard{
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
rectangle.show(a, b);
System.out.println(
" you have entered these values : " + a + " and " + b);
int area = rectangle.calculate();
System.out.println(" area of a rectange is : " + area);
}
}
Output of the program is given below:
C:\java>java EnterValuesFromKeyboard 4
5
you have entered these values : 4 and 5
area of a rectange is : 20
Tokens can be used where we want to break an application into tokens. We have to break a String into tokens as well as
we will know how many tokens has been generated. That's what we are trying to do in this program. In the program a string
is passed into a constructor of StringTokenizer class. StringTokenizer is a class in java.util.package. We are using while
loop to generate tokens. The following methods have been used in this program.
To break a string into tokens what we need first is to create a class named StringTokenizing. Inside this class we will
declare our main method. Make an object of class StringTokenizer and pass one string inside the constructor which you
want to break into tokens. By using the instance ofStringTokenizer call the method countTokens() which gives the number
of tokens remaining in the string. It is a method of StringTokenizer class. If the object have more tokens available then it
will call method hasMoreTokens() and print the tokens by using nextToken().
import java.util.*;
C:\java>java StringTokenizing
The total no. of tokens generated
:5
You
are
tokenizing
a
string
In this example we are going to show the use of java.util.ArrayList. We will be creatiing an object of ArrayList class and
performs various operations like adding removing the objects.
Arraylist provides methods to manipulate the size of the array that is used internally to store the
list.ArrayList extends AbstractList and implements List, Cloneable, Serializable. ArrayList capacity .grows
automatically. The ArrayList is not synchronized. It permits all elements including null.
In this program we are inserting a value. We are using three methods of ArrayList class.
add(Object o): Appends the specified element to the end of this list. It returns a boolean value.
remove(int index): Removes the element at the specified position in this list. It returns the element that was removed from
the list. It throws IndexOutOfBoundsException : if index is out of range.
import java.util.*;
A file object is used to a give a filename. Creating the File object doesn't mean that a file exists. It may be that the does not
exist. Suppose if the file exists, first of all we need to convert the file object in URL, for this we use a method toURL(). It
returns aURL object and throws MalformedException. After this we will convert this URL to a file object by
using getFile() method. We will read this file by using BufferedReader object.
getFile() : This is the method of the URL class, is used to get the file name from the URL.
import java.io.*;
import java.net.*;
C:\ConstructFileNamePath>java ConstructFileNamePath
The url
isfile:/C:/ConstructFileNamePath/ConstructFileNamePath/ConstructFileNamePath.tx
t
The file name is C:\ConstructFileNamePath\ConstructFileNamePath\
ConstructFileNamePath.txt
C:\ConstructFileNamePath\ConstructFileNamePath\ConstructFileNamePath.txt (The
system cannot find the path specified)
In this program we are going to make a temporary file, which will be deleted automatically by the garbage collector when the
program ends.
createTempFile(String prefix, String suffix): This is a static method of file class. This creates an empty file and we have
used two parameters to generate name.
close(): When we don't need to write further, we should close the program with() that will close the string.
deleteOnExit(): It will delete the existing file when you close the java program or your JVM.
import java.io.*;
FileWriter(tempFile));
out.write("You are writing on temporary file
C:\tapan>
import java.util.*;
This program is going to determine that the file name refers to the same file or not. What you need to do is to create
two Fileobject and pass the file name in the constructor of both the File class. Now match both the file instances. It will
return false if the file paths are not equal. To send the true value we first have to normalize both the paths, only after that it
will return true.
equals():
This is the method of String class. It checks whether the pathname are equal or not.
getCanonicalFile():
It denotes the same file or directory its abstract pathname. It throws IOException andSecurityException.
import java.io.*;
You can solve this problem very easily. What you need to do, just create a Fileobject and pass some file name or a directory
in it.
import java.io.*;
C:\FileOrDirectory>java FileOrDirectory
the name you have entered is a file :
FileOrDirectory
the path is C:\FileOrDirectory\
FileOrDirectory
In this program we will read a file in the form of a byte array. We can do it very easily. Firstly we will create an object
of File class and pass the name of the file which we want to read, in the constructor of Fileclass. We will
use DataInputStream to read primitive data types.
import java.io.*;
The following code helps you in getting the file size in byte array.
import java.io.*;
In Singeton classes only one instance will be created. We are going to serialize the class. This can be done very easily.
What we need to do is to implement ajava.io.Serializable interface. We will use a method of Serializable interface that
is readResolve().
import java.io.*;
public class SerializableSingleton implements java.io.Serializable {
A Checksum is used for error checking while transferring a file. Data flow across the network in the form of packets. So,
checksum is a computed value that is dependent on the contents of a file. For each packet the computed checksum will be
different. This computed value is transmitted with the packet when it is transmitted. The receiving system checks the
checksum and on the basis of checksum it receives and rejects the packet. It is mainly used where it becomes necessary to
check the packets before accepting it.
CRC: CRC means Cyclic Redundancy Check. It is a error checking technique used to check the accuracy of data while
transmitting it to the other end. Errors are checked while the data is transferring. CRC performs some type of calculation
before transmitting the data and send the result to the other end. The other end repeats the same operation before
accepting the data. If both the devices get the result same, it means the transmission is error free.
To make a program on Checksum first of all make a class named CheckSumCRC32. Inside the class declare one method
checkSum(String file) which will take a value of a file which has to pass at run time. Now make a object
of FileInputStream, CheckedInputStream and CRC32 and pass the instance ofFileInputStream, CRC32 into the
constructor of CheckedInputStream class. To calculate the size of the file call the method length() of File class. We have
define a array of type byte, the size of the array is 100, i.e. the size of each packet. The Checksum for each packet will be
generated randomly by the CheckedInputStream class. It returns the long data type. Now define a main method inside which
we will call checkSum() method which will give us the checksum, size of the file and name of the file.
To achieve the desired result we have used the following classes and methods.
FileInputStream: It is a class of java.io package. It extends InputStream class. It is used for reading in byte form.
CheckedInputStream: It is a input stream that keeps the checksum. Its constructor use two parameter, first is InputStream
and second is Checksum.
CRC32: It is a class of java.util.zip package. It implements Checksum. This class is used to calculate the CRC-32 of the
stream.
import java.io.*;
import java.util.zip.CheckedInputStream;
import java.util.zip.CRC32;
In the output we can see that first we have created a file javalearner.txt in
the java folder and pass some information in it. We can see that for each
packet a checksum is calculated. The size of each packet is 100 bytes. It can
be changed. The output will show 100 checksum value as 10 packets are
generated. In the output firstly we are displaying the checksum of the packet,
secondly the size of the file and lastly the name of the file.
This Java programming tutorial will teach you how you can construct a file name path. By using the constructing filename
path it is possible to set dynamic path, which is helpful for mapping local file name with the actual path of the file.
Java API has provided us many packages, one of them is java.io package. This package contains aFile class In this
example we are using one static final variable of File class i.e.. separatorChar. The value of this separator is system
dependent. If we are using Windows platform then the value of this separator is ' \ ' .
import java.io.*;
C:\java>java
ConstructingFileNamePath
The path of the file is : \java\example
This Java programming example will teach you the the concepts of arrays so that you can write a program on array by
yourself. An array works a container object which can hold a values of same type. The length of an array is created when
the array is going to be created. Arrays can be created in following ways. One way to create a array is by
using new operator. e.g.. : a = new int[5];. It will create an array of type int which can store 5 integer values. The next way
to define array is just same as we have defined an array in the program below. Array should be used, where you have to
store multiple values of the same type. For example if we have to store months of the year then the better idea is to make an
array of it.
In the program below we have defined a class named FirstArrayProgram. Now declare a method in which you have to
define a array of String type which can hold only string values. In this array we are storing a months of the year. Now we
want to retrieve the values of an array, so use for loop to access it.
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
}
C:\java>java FirstArrayProgram
Name of months in a year :
January
Febuary
March
April
May
June
July
August
September
October
November
December
methods,instance methods and static methods. Static methods can't use any instance variables. The this keyword can't
be used in a static methods. You can find it difficult to understand when to use a static method and when not to use. If you
have a better understanding of the instance methods and static methods then you can know where to use instance method
A static method can be accessed without creating an instance of the class. If you try to use a non-static method and variable
defined in this class then the compiler will say that non-static variable or method cannot be referenced from a static context.
Static method can call only other static methods and static variables defined in the class.
The concept of static method will get more clear after this program. First of all create a classHowToAccessStaticMethod.
Now define two variables in it, one is instance variable and other is class variable. Make one static method
named staticMethod() and second named as nonStaticMethod(). Now try to call both the method without constructing a
object of the class. You will find that only static method can be called this way.
j=1000;
//nonStaticMethod();
staticMethod();
}
}
C:\java>java
HowToAccessStaticMethod
you can access a static method this
way
This example will help you to understand the concepts of GZIP. Sometimes it happens that when you download a file or any
PDF file you get it in compressed mode. This means that the file is compressed, but can't read it in compressed form so, it
needs to be uncompressed. There are various uncompress ion utility program which can be found very easily found on
internet. If you are uncompressing a PDF with the extension .gz, then its resultant file will have a .PDF extension. Its main
advantage is that it will uncompress the PDF file so that you can be able to read it. This utility is a part
of java.util.zippackage which provides classes and methods to compress and decompress the file.
To make a program on uncompressing a file, firstly you need to import java.util.zip package so, that all classes and method
of this package can be used, also import java.io package for the input/output operation. Then create a class
named JavaUncompress. Declare a main method inside the class which will take one String argument i.e. file name. If the
user forgets to type the name of the input file which has to be uncompressed, then ask the user to enter the file name. After
getting the file name, we need to uncompress that particular file. For that we need to open the gzip file. Print a message so
that you can understand where gzip file is opening. To open the input file firstly create a object ofFileInputStream class
which and pass the instance of FileInputStream class into the constructor ofGZIPInputStream class, which will be created
by using new operator. After opening the input file now we need to open the output file so that the data can be transferred
from the input file to the output file. Print the message so that you can understand where the output is being written. For that
use make a object of FileOutputStream class and pass the name of the resultant file in its constructor. For transferring the
bytes from the compressed file to the output file declare a array of type byte with the size of 1024 bytes. It can be changed
according to the needs of a programmer, now declare one variable of type int which will read the byte from the object
of GZIPInputStream class. At last close the file and stream.
GZIPInputStream: This class is a part of java.util.zip package. It extends DeflaterInputStreamclass. This class reads
compressed data in the GZIP format.
FileOutputStream: This class extends OutputStream class. It is a output stream for writing data to a file.
write(byte[] buf, int off, int len i): It is a method of OutputStream, which takes three arguments. It is used for writing a
array of bytes to the uncompressing file.
import java.util.zip.GZIPInputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
.................. : opened");
FileInputStream(inFilename));
System.out.println("Opening the output file..
........... : opened");
String outFilename = inFilename +".pdf";
OutputStream out = new FileOutputStream(outFilename);
System.out.println("Transferring bytes from the
....closing.......... : closed");
gzipInputStream.close();
out.close();
}
}
catch(IOException e){
System.out.println("Exception has been thrown" + e);
}
}
}
In the output we can see that firstly we have given the name of the compressed
file. The file name should ends with .gz extension, while opening the
compressed gzip file we are printing that the file is opening. After opening
the file we are opening a file to which we have to write the data from the
compressed file and that also is printed in the output. For transferring the
bytes from the compressed file to the output file we are printing the message.
Before closing the file and stream we are again printing the message.
C:\java>
When a number of objects are created from the same class, the same copy of instance variable is provided to all.
Remember, each time you call the instance the same old value is provided to you, not the updated one . In this program we
are showing that how a instance variable is called in each instance, but the copy remains same irrespective the counter we
have used in the constructor of a class. We can't call the non-static variable in a main method. If we try to call the non-static
method in the main method then the compiler will prompt you that non-static variable cannot be referenced from a static
context. We can call the non-static variable by the instance of the class.
The example will show you how you can use a non-static variables. First create a class named NonStaticVariable. Declare
one global variable and call it in the constructor overloaded method in which you will have to increment the value of the
variable by the counter. To access a non-static variable we will have to make a object of NonStaticVariable by using new
operator. Now call the instance variable. Now again make a new object of the class and again call the instance variable.
Now you can realize that the value of the instance variable in both the object is same.
Code of this program is given below:
}
}
As we can see in the output the same copy of the instance variable is provided
to all the objects, no matter how many objects we create.
C:\java>java NonStaticVariable
No. of instances for st1 : 1
No. of instances for st1 : 1
No. of instances for st2 : 1
No. of instances for st1 : 1
No. of instances for st2 : 1
No. of instances for st3 : 1
Example of a class variable (static variable)
This Java programming example will teach you how you can define the static class variable in a class. When a number of
objects are created from the same class, each instance has its own copy of class variables. But this is not the case when it
is declared as static static.
static method or a variable is not attached to a particular object, but rather to the class as a whole. They are allocated when
the class is loaded. Remember, each time you call the instance the new value of the variable is provided to you. For
example in the class StaticVariable each instance has different copy of a class variable. It will be updated each time the
instance has been called. We can call class variable directly inside the main method.
To see the use of a static variable first of all create a class StaticVariable. Define one static variable in the class. Now make
a constructor in which you will increment the value of the static variable. Now make a object of StaticVariable class and
call the static variable of the class. In the same way now make a second object of the class and again repeats the process.
Each time you call the static variable you will get a new value.
C:\java>java StaticVariable
No. of instances for sv1 : 1
No. of instances for sv1 : 2
No. of instances for st2 : 2
No. of instances for sv1 : 3
No. of instances for sv2 : 3
No. of instances for sv3 : 3
This Java programming tutorial will teach you the methods for writing program to calculate swap of two numbers. Swapping
is used where you want to interchange the values. This program will help you to increase your programming ability.
In this program we will see how we can swap two numbers. We can do this by using a temporary variable which is used to
store variable so that we can swap the numbers. To swap two numbers first we have to declare a class Swapping. Inside a
class declare one static method swap(int i, int j) having two arguments, the value of these arguments will be swapped. Now
declare one local variable temp which will help us to swap the values. At last call the main method inside of which you will
call the swap method and the result will be displayed to you.
}
}
Output of this program is given below:
This is a simple Java Oriented language program. If you are newbie in Java programming then our tutorial and example
are helpful for understanding Java programming in the simplest way. Here we will learn how to swap or exchange the
number to each other. First of all we have to create a class "Swap". Now, we use
the Integer.parseInt(args[o]) andInteger.parseInt(args[1]) methods for getting the integer type values in command line.
Use a temporary variable z of type integer that will help us to swap the numbers Assign the value of x to z variable, now
assign the value of y to the variable x. Lastly assign the value of z to variable y. Now we get the values has been
interchanged. To display the values on the command prompt use println()method and the swapped values will be displayed.
int x= Integer.parseInt(args[0]);
int y= Integer.parseInt(args[1]);
System.out.println("Initial value: "+ x +" and " + y);
int z = x;
x = y;
y = z;
System.out.println("Swapped value: " + x +" and " + y);
}
}
This java example will help you to compare the dates of files. In java we have the option to compare two or more files. This
is useful when we have to compare the files. Mostly it happens that after creating a file or a directory we forgets when it was
made or last modified, and sometimes it becomes essential to know the exact date and time of creation. By this example
you will be able to understand it.
To make a program on this example firstly we have to make a class ComparingFileDates. Inside the class we have
defined three static variables, which will be used for comparing the files. Declare a method comparing which will check when
the file is last modified and which file is older or a new one. Now call the main method. Inside this method make a two
objects of a File class which will take file name as its input in the constructor of File class. Now call the method lastModified
by the instances of file classes which will return the time of the file creation. Now call the comparing method inside the main
method and the result will be displayed to you.
File: This class extends class Object and implements Comparable and Serializable interface. It takes the file as its input.
lastModified(): It is a method of a File class. It returns the time when the file was last modified.
import java.io.*;
C:\java>
Getting a absolute path
If you are new in Java programming then our tutorials and examples will be helpful in understanding Java programming in
the most simplest way. Here after reading this lesson, you will be able to find the absolute path of a file or directory.
To find a file or directory it is very necessary to know the path of the file or directory so that you can access it. If you know
the path then it is very easy to work on it. Suppose a situation where a problem comes in front you where you don't know the
path of the file, then what will you do. Then this problem can be solved by using a method getAbsolutePath(). The
method getAbsolutePath() should be used where we don't know the exact path of the file.
To find an absolute path of a file, Firstly we have to make a class GetAbsolutePath. Inside this class define the main
method. Inside this method define a File class of java.io package. Inside the constructor of a File class pass the name of the
file whose absolute path you want to know. Now call the method getAbsolutePath() of the File class by the reference
of File class and store it in a String variable. Now print the string, you will get a absolute path of the file.
In this class we have make use of the following things by which this problem can be solved.
import java.io.*;
If you are new in Java programming then our tutorials and examples will be helpful in understanding Java programming in
the most simplest way. Here after reading this lesson, you will be able to break java program into tokens.
The use of token is just like as we take tokens for getting a milk or get into a metro, so that the one token can be read at a
time.
Suppose if we have to make a token of a java file then we will do. Firstly we have to make a
classTokenizingJavaSourceCode. Declare a main method in it . Now make a object of BufferedReaderclass and pass
the InputStream class object into it which will read the name of the java file at run time. Now we need to read the file so we
use FileReader class ,after reading a file we need to generate a tokens out of that file so, we use
class StreamTokenizer and pass reference of a Reader class in its constructor. In this program we are using one method
of StreamTokenizer class.
To solve this problem we have make use of the following classes and methods.
InputStream: It is a abstract class and the parent class of all the Stream classes.
BufferedReader: This class reads the text from the input stream. This class extends Reader class.
FileReader: This class reads the file in the character format. It extends InputStreamReader.
StreamTokenizer: This class takes a input stream and break it into tokens so that one token can be read at a time. It
takes FileReader instance as a input in its constructor.
import java.io.*;
import java.util.*;
In this section, you will learn how to add two big numbers. For adding two numbers implement two big decimal numbers then
apply the Sum() method that takes both numbers. Now, you will have to define it and use the add() method to add both
numbers. Finally, the result will be displayed on the command prompt (DOS prompt).
BigDecimal():
This is the constructor of BigDecimal class. It translates the data into BigDecimal.
BigDecimal.add(BigDecimal big):
This method is used to add the two BigDecimal numbers.
import java.math.BigDecimal;
Output of program:
C:\vinod\Math_package>javac AddTwoBigNumbers.java
C:\vinod\Math_package>java AddTwoBigNumbers
Sum of two BigDecimal numbers:
150.002849999999995134203345514833927154
In this section, you will learn how to work with StringBuffer and append data to it. The StringBuffer is a class that
implements multiple sequence of characters. The following program construct a string buffer that has '0' capacity. This
program inserts the data in the string buffer using the insert() method that provides the facility for adding the data in any
positions. But the append() method also add data in string buffer in ending position. This method inserts always last or end
position.
Description of code:
StringBuffer(int len):
This is the constructor of StringBuffer class that implements multiple sequence of characters. This constructor constructs a
string buffer that have no characters. It takes initial capacity that have to initialized.
pos: This is the position that have to be used for inserting the data.
str: This is the string that have to inserted.
append(String str):
This is the method that inserts the string into string buffer. It always inserts a string at last position.
import java.lang.*;
Output of program:
C:\vinod\Math_package>javac
AppendInsert.java
C:\vinod\Math_package>java AppendInsert
StringBuffer insert and append example!
vinod
vinodDeepak
vinodDRajeepak
vinodDRajeepakMohit
In this section, you will learn how to compare characters in Java. The java.langpackage provides a method for comparing
two case sensitive strings. The compareTo() method compares two strings on the basis of Unicode of each character of
the given strings. This method returns integer type value. If it will return '0' it means the given string is equal otherwise not
equal.
Description of program:
This program helps you to compare characters with cases and sequence. For comparing the string you will need those
string that have to be compared. Here the CharComp() method is applied for comparing the string. At the time of defining,
you will use the compareTo() method that compares both strings and shows an appropriate given message.
Description of code:
compareTo(String str):
Above method is used to compare two strings with its cases. If it returns '0', an argument of the given string is equal
otherwise not. It takes string type parameter as following:
import java.lang.*;
Output of program:
C:\vinod\Math_package>javac
CharComparation.java
C:\vinod\Math_package>java
CharComparation
Character comparation example!
String1 = Vinod
String2 = Vinod
String2 = vinod
String1 and String2 are equal!
String1 and String3 are not equal!
String2 and String3 are not equal!
In this section, you will learn how to combine or merge two strings in java. Thejava.lang package provides the method that
helps you to combine two strings and making into single string. The following program is used for concatenating two string
through using the concat() method that concatenates the specified string to the end of string and finally, you will get the
combined string.
Description of code:
concat(String str):
This is the method that concatenates the two specified strings.
import java.io.*;
C:\vinod\Math_package>javac
CombinString.java
C:\vinod\Math_package>java CombinString
Enter First String:
RoseIndia
Enter Second String:
NewstrackIndia
Combin string example!
Combined string: RoseIndiaNewstrackIndia
Compare strings
example
Description of code:
equals():
This is the method that compares an
object values and returns Boolean type
value either 'true' or 'false'. If it returns
'true' for the both objects, it will be equal
otherwise not.
import java.lang.*;
import java.io.*;
Output of program:
C:\vinod\
Math_package
>javac
CompString.ja
va
C:\vinod\
Math_package
>java
CompString
String equals
or not
example!
Please enter
first string:
Rose
Please enter
second string:
Rose
The given
string is equals
C:\vinod\
Math_packa
ge>java
CompString
String
equals or not
example!
Please enter
first string:
Rose
Please enter
second
string:
rose
The given
string is not
equals
Replace Character in
String
C:\
replace>javac
Replace.java
C:\
replace>java
Replace
Your String
before
repalce
rajesh raju
raja rahul
ray rani ram
Your String
after
repalceing
'h' with 'j'
gajesh gaju
gaja gahul
gay gani gam
Your char has
been replaced
Description of code:
trim():
This method removes the blank spaces
from both ends of the given string (Front
and End).
import java.lang.*;
Output of program:
C:\vinod\
Math_packag
e>javac
StringTrim.jav
a
C:\vinod\
Math_packag
e>java
StringTrim
String trim
example!
Given String :
RoseIndia
After
trim :RoseIndi
a
Description of code:
startsWith(String start):
This is a Boolean type method that
returns either 'true' or 'false'. It checks the
given string that begins with specified
string in the beginning. It takes a string
type parameter such as:
import java.lang.*;
Output of program:
C:\vinod\
Math_package
>javac
StrStartWith.ja
va
C:\vinod\
Math_package
>java
StrStartWith
String start
with example!
Given String :
Welcome to
RoseIndia
Start with : Wel
The given
string is start
with Wel
C:\
convert
\
rajesh\
complet
ed>java
c
Argumen
tPassin
gExampl
e.java
C:\
convert
\
rajesh\
complet
ed>java
Argumen
tPassin
gExampl
e
rajesh
kumar
rahul
The
values
enter
at
argumen
t
command
line
are:
Argumen
t 1 =
rajesh
Argumen
t 2 =
kumar
Argumen
t 3 =
rahul
Decimal Format
Example
C:\
convert
\
rajesh\
complet
ed>java
c
Decimal
FormatE
xample.
java
C:\
convert
\
rajesh\
complet
ed>java
Decimal
FormatE
xample
The
Decimal
Value
is:2192
.015
getLineNumber():
This method is used to get the number of
line.
readLine():
This method is used to read the data line
by line. Then returns the data of a line as
a single string.
import java.io.*;
public class LineNumberReaderExample{
public static void main(String[]
File file = null;
FileReader freader = null
LineNumberReader lnreader
try{
file = new File("LineNumberReaderExample.java"
freader = new FileReader(file);
lnreader = new LineNumberReader(freader);
String line = "";
while ((line = lnreader.readLine())
System.out.println("Line:
getLineNumber() + ": " + line);
}
}
finally{
freader.close();
lnreader.close();
}
}
}
C:\
convert
\
rajesh\
complet
ed>java
c
LineNum
berRead
erExamp
le.java
C:\
convert
\
rajesh\
complet
ed>java
LineNum
berRead
erExamp
le
Line:
1:
import
java.io
.*;
Line:
2:
public
class
LineNum
berRead
erExamp
le{
Line:
3:
public
static
void
main(St
ring[]
args)
throws
Excepti
on{
Line:
4:
File
file =
null;
Line:
5:
FileRea
der
freader
= null;
Line:
6:
LineNum
berRead
er
lnreade
r =
null;
Line:
7:
try{
Line:
8:
file =
new
File("
LineNum
berRead
erExamp
le.java
");
Line:
9:
freader
= new
FileRea
der(fil
e);
Line:
10:
lnreade
r = new
LineNum
berRead
er(frea
der);
Line:
11:
String
line =
"";
Line:
12:
while
((line
=
lnreade
r.readL
ine())
!=
null){
Line:
13:
System.
out.
println
("Line:
" +
lnreade
r.
getLine
Number(
) + ":
" +
line);
Line:
14:
}
Line:
15:
}
Line:
16:
finally
{
Line:
17:
freader
.close(
);
Line:
18:
lnreade
r.close
();
Line:
19:
}
Line:
20:
}
Line:
21: }
Operating System
Information
S/ Key
Descrip
No
tion
.
The
version
of Java
1 java.version
Runtime
Environ
ment.
2 java.vendor The
name of
Java
Runtime
Environ
ment
vendor
The
java.vendor.u URL of
3
rl Java
vendor
The
directory
4 java.home of Java
installati
on
The
specific
java.vm.speci ationver
5 fication.versio sion of
n Java
Virtual
Machine
The
name of
specific
java.vm.speci
ation
6 fication.vendo
vendor
r
of Java
Virtual
Machine
Java
Virtual
java.vm.speci Machine
7
fication.name specific
ation
name
JVM
java.vm.versi impleme
8
on ntation
version
JVM
java.vm.vend impleme
9
or ntation
vendor
JVM
java.vm.nam impleme
10
e ntation
name
The
name of
specific
ation
java.specifica
11 version
tion.version
Java
Runtime
Environ
ment
JRE
java.specifica specific
12
tion.vendor ation
vendor
JREspe
java.specifica
13 cificatio
tion.name
n name
Java
class
java.class.ver
14 format
sion
version
number
Path of
ava.class.pat
15 java
h
class
16 java.library.p List of
ath paths to
search
when
loading
libraries
The
17 java.io.tmpdir path of
temp file
The
Name of
18 java.compiler JIT
compiler
to use
The
path of
extensio
n
19 java.ext.dirs
directory
or
directori
es
The
name of
20 os.name
OS
name
The OS
21 os.arch architect
ure
The
22 os.version version
of OS
The File
23 file.separator separat
or
The
path.separato path
24
r separat
or
The
name of
26 user.name account
name
user
The
home
27 user.home
directory
of user
The
current
working
28 user.dir
directory
of the
user
C:\
convert
\
rajesh\
complet
ed>java
c
Opertin
gSystem
Info.ja
va
C:\
convert
\
rajesh\
complet
ed>java
Opertin
gSystem
Info
The
informa
tion
about
OS
Name of
the OS:
Windows
2000
Version
of the
OS: 5.0
Archite
cture
of The
OS: x86
Taking Substring
C:\
convert
\
rajesh\
complet
ed>java
c
Substri
ngExamp
le1.jav
a
C:\
convert
\
rajesh\
complet
ed>java
Substri
ngExamp
le1
String
:
Rajesh
kumar
String
after
3rd
index:
esh
kumar
Substri
ng
(1,2):
a
We are
using getProperty(String key)method to
find the current temp directory.
The getProperty(String key) is defined
into System class. System class extends
directly Objectclass. System class is
defined final so any class never
extends System class. System class
allow us to get or set system information.
In this example we are pasing
"java.io.tmpdir" as key to get the current
temp directory into getProperty() method.
System.out.println("OS current
+ System.getProperty("java.io.tmpdir"
}
}
C:\convert\rajesh\
completed>javac
TempDirExample.java
C:\convert\rajesh\
completed>java
TempDirExample
OS current temporary
directory is C:\
DOCUME~1\ADMINI~1\
LOCALS~1\Temp\
getProperty(String Key):
This method is used to get the property of
system for passing Key values.
System.out.println("User
System.getProperty("user.home"
}
}
C:\convert\rajesh\completed>javac UserHomeExample.java
C:\convert\rajesh\completed>java UserHomeExample
User Home Path: C:\Documents and Settings\Administrator
We need java.io.* package import first. The create a .txt file with name "write.txt". We are using FileWriter class to read
file for modification.BufferedWriter class is used for buffering the file which will store into an object of Writer class .Then
we are using write() method to write text into file. At last close output file using close() method.
import java.io.*;
This example counts the number of occurrences of a specific word in a string. Here we
are counting the occurrences of word "you" in a string. To count it we are
using countMatches() method.
countMatches(String str,String sub): This method counts how many times the
string sub appears in the String str. This method returns zero
if StringUtils.countMatches(null, *),StringUtils.countMatches("",
*) ,StringUtils.countMatches("abba", null),StringUtils.countMatches("abba", "") ,
and StringUtils.countMatches("abba", "x"). The parameters used as "str" is String to
be checked and "sub" is substring to be count.
import org.apache.commons.lang.StringUtils;
C:\rajesh\kodejava>javac
WordCountExample.java
C:\rajesh\kodejava>java
WordCountExample
3 occurrences of the word 'you' in
'How r you?R you fine?
Where are you going?' is found.
In this example we are going to reverse a given string using StringUtils api. In this
example we are reversing a string and the reversed string is delimited by a specific
character.
reverse(String str): This method is used to reverse the order of a buffered string. It
returns a null value if no string is passed i.e StringUtils.reverse(null) = null
or StringUtils.reverse("") = "" otherwise reverse order will returns
e.g. StringUtils.reverse("bat") = "tab".
import org.apache.commons.lang.StringUtils;
C:\rajesh\kodejava>javac
StringReverseUsingString
Utils.java
C:\rajesh\kodejava>java
StringReverseUsingString
Utils
The original String: Hi,
How R YOU?
The reversed string: ?
UOY R woH ,iH
The delimited Reverse
string: YOU? R How Hi,
The Singleton design pattern ensures that only one instance of a class is created, it
provides a global point of access to the object and allow multiple instances in the future
without affecting a singleton class's clients. To ensure that only one instance of a class is
created we make SingletonPattern as static. getInstance() method returns a single
instance of the class. We create a private default constructor to avoid outside
modification.
C:\rajesh\
kodejava>javac
SingletonPattern.java
C:\rajesh\
kodejava>java
SingletonPattern
The output of two
instance:
First Instance:
SingletonPattern@3e25a
5
Second
Instance:SingletonPatt
ern@3e25a5
The Runtime.exec() method may not work well for windowing processes, daemon
processes, Win16/DOS processes on Microsoft Windows, or shell scripts.
The class Runtime contained in java.lang package and extends the Object class. Every
Java application has a single instance of class Runtime. The current runtime can be
obtained by using thegetRuntime() method. Any application cannot create its own
instance of runtime class.
import java.io.IOException;
public class RuntimeExec{
public static void main(String[] args){
try
{
Process process = Runtime.getRuntime()
.exec("notepad.exe");
}catch (IOException e)
{
e.printStackTrace();
}
}
}
This example explores how to find the day of a month and the day of a week This
example sets the year as 2007 and the day as 181. The example finds the day of a
month and the day of a week by usingget(field_name) method.
The Calendar class extends Object class. It is an abstract base class and converts
a Date object into a set of integer fields. Calendar class provides a getInstance()
method that returns a Calendarobject whose time fields are initialized with the current
date and time.
C:\rajesh\
kodejava>javac
DayYearToDayMon
th.java
C:\rajesh\
kodejava>java
DayYearToDayMon
th
The date of
Calendar is:
Sat Jun 30
17:03:01
GMT+05:30 2007
The day of
month: 30
The day of
week: 7
The Calendar class is an abstract base class that extends Object class and converts
a Date object into a set of integer fields. Calendar class provides a getInstance()
method for returning a Calendar object whose time fields have been initialized with the
current date and time.
setTimeInMillis(long millis): This method sets the current time in a calendar object.
getInstance(): This method gets a calendar object containing the default time zone,
locale and current time.
DAY_OF_YEAR: This field gets and sets the day to indicate the day number within a
current year. e.g. The first day of the year has value 1.
YEAR: This field is used to get and set the year for indicating the year.
import java.util.Calendar;
public class DayOfYearToDayOfWeek{
public static void main(String[] args){
Calendar calendar = Calendar.getInstance();
for(int i=2000;i<2005;i++){
calendar.set(Calendar.YEAR, i);
calendar.set(Calendar.DAY_OF_YEAR,0);
System.out.println(calendar.getTime().toString());
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
System.out.println("Weekday: " + weekday);
System.out.println();
}
}
}
Calendar Example
In this section, we are discussing the entire functionality of java.util.Calender class. In the
following code segment we are performing various operations on Date object using its
methods. The methodgetTime() of the calendar class returns a Date object that is then
passed to the println() method just to print today's date. The arithmetic function of the
date class adds specific amount of time to the given time field following the calendar's
rule. This example subtracts two years from the current date of the calendar and also
add 3 days to the current date of the calendar.
Description of program:
In the following code segment, first we are getting the current date and time into the date
object by using the getInstance() and getTime() methods of the calendar class in a
methodCalendarTimemethod() and printing this current date and time on the console.
Now we are taking another method Adddates() that adds two different dates. In this
method we are taking an instance date of the calendar class into a reference
variable cldr and an objectdateformatter of the SimpleDateFormat class. Now we are
taking the clone of the calendar class and passing the reference of this clone into cldr.
Now we are getting the dates of two years ago and five years after, by using
the add() method and printing these values on the console.
Now we are taking another method that is DateDifference(). In this method we are
taking date and time from an object of the GregorianCalendar class and passing it into
an object startDate1 of the Date class and also taking an another object endDate1 of
the date class. Now we are taking the difference of times of these two objects and
printing it on the console.
import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.*;
System.out.println("Performing
System.out.println();
}
System.out.println("Year : "
+ calender.get(Calendar.YEAR));
System.out.println("Month : "
+ calender.get(Calendar.MONTH));
System.out.println("Day of Month : "
+ calender.get(Calendar.DAY_OF_MONTH));
System.out.println("Day of Week : "
+ calender.get(Calendar.DAY_OF_WEEK));
System.out.println("Day of Year : "
+ calender.get(Calendar.DAY_OF_YEAR));
System.out.println("Week of Year : "
+ calender.get(Calendar.WEEK_OF_YEAR));
System.out.println("Week of Month : "
+ calender.get(Calendar.WEEK_OF_MONTH));
System.out.println
("Day of the Week in Month : "
+ calender.get(Calendar.DAY_OF_WEEK_IN_MONTH));
System.out.println("Hour
: " + calender.get(Calendar.HOUR));
System.out.println("AM PM
: " + calender.get(Calendar.AM_PM));
System.out.println("Hour of the Day
: " + calender.get(Calendar.HOUR_OF_DAY));
System.out.println("Minute
: " + calender.get(Calendar.MINUTE));
System.out.println("Second
: " + calender.get(Calendar.SECOND));
System.out.println();
}
C:\Examples>java CalendarExample
Current date and time is: Mon Dec 10
18:37:06 GMT+05:30 2007
Date Comparison
In this section we are discussing the comparison of two dates, whether they are equal or
not, the first date comes before the other or not, the first date comes after the other or
not, by using the equals(), before() and after() methods of the date class.
Description of program:
In this program first we are write the method DateComparison() in which we create an
objectcomparetodaydate of the Date class that have current date and time and a clone
of this object. We also create one more object comparedate1970 of the Date class that
contains a date of 1970. Now we are comparing these two dates whether they are equal
or not by using the equals() method, comparison of the date contained in the
object comparetodaydate comes before the date contained in the
object comparedate1970 or not, and date contained in the
object comparetodaydate comes after the date contained in the
object comparedate1970 or not and then printing all the values on the console.
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
if (comparetodaydate.equals(comparedate)) {
System.out.println("The two dates are equal");
}
else {
System.out.println("The two dates are not equal");
}
System.out.println();
System.out.println("Comparison of two dates by using the
equals() method:");
System.out.println();
System.out.println("Today's date: " + comparetodaydate);
System.out.println("Compairing date: " + comparedate1970);
if (comparetodaydate.equals(comparedate1970)) {
System.out.println("The two dates are equal");
}
else {
System.out.println("The two dates are not equal");
}
System.out.println();
System.out.println("Comparison of two dates by using the
before() method:");
System.out.println();
System.out.println("Today's date: " + comparetodaydate);
System.out.println("Compairing date: " + comparedate1970);
if (comparetodaydate.before(comparedate1970)) {
System.out.println("Today's date comes before the
compairing date");
}
else {
System.out.println("Today's date does not come before
the comparing date");
}
System.out.println();
System.out.println("Comparison of two dates by using the
after() method::");
System.out.println();
System.out.println("Today's date: " + comparetodaydate);
System.out.println("Comparing date: " + comparedate1970);
if (comparetodaydate.after(comparedate1970)) {
System.out.println("Today's date comes after the
comparing date");
}
else {
System.out.println("Today's date does not come after
the comparing date");
System.out.println();
}
System.out.println();
}
int blankdays = 0;
System.out.println(" " + monthcalender[month] + " " +
month, 1);
System.out.println("Sunday Monday Tuesday Wednesday
blankdays = cldr.get(Calendar.DAY_OF_WEEK)-1;
int daysInMonth = daysinmonths[month];
if (cldr.isLeapYear(cldr.get(Calendar.YEAR))
&& month == 1) {
++daysInMonth;
}
/**
* Sole entry point to the class and application.
* @param args Array of String arguments.
*/
public static void main(String[] args) {
if (args.length == 2) {
moncldr.displayMonth(Integer.parseInt(args[0])-1,
Integer.parseInt(args[1]));
}
else {
Calendar todaycldr = Calendar.getInstance();
moncldr.displayMonth(todaycldr.get(Calendar.MONTH)
, todaycldr.get(Calendar.YEAR));
}
}
}
Here is the output:
C:\Examples>java MonthCalender
December 2007
Sunday Monday Tuesday Wednesday
Thursday Friday Saturday
1
2345678
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
C:\convert\rajesh\completed>javac
WriteTextFileExample.java
C:\convert\rajesh\completed>java WriteTextFileExample
Your file has been written
Garbage Collection
In the example given below, first we are creating three objects to give the garbage collector something to do, then we are
assigning some values to these variables and then appending values to the StringBuffer variable strbuf and setting the null
values to these objects so that they can be garbage collected. Now we are taking the system's current time in milliseconds
into a long type variable then calling the garbage collector method gc() of the System class and then system's current time
after the garbage collection operation completes and subtracts the previous time from the last one to determine the time
taken by the garbage collector to complete its operation and prints this time on the console.
import java.util.Vector;
strbuf= null;
vctr = null;
System.out.println("Staring explicit Garbage Collection.");
long time = System.currentTimeMillis();
System.gc();
C:\Examples>java
GarbageCollection
Staring explicit Garbage
Collection.
Garbage Collection took 984 ms
Staring explicit Garbage
Collection.
Garbage Collection took 16 ms
In this example we are checking a sting object containing empty or null value. Apache has provided two
methodsisBlank() and isNotBlank() for checking the strings..
The classorg.apache.commons.lang.StringUtils extends Object class and provides methods that operate on null safe
string.
isNotBlank(String str): This method is used to check whether a string is not empty (""), not null or not a whitespace .
import org.apache.commons.lang.StringUtils;
C:\rajesh\kodejava>javac
CheckEmptyStringExample.java
C:\rajesh\kodejava>java
CheckEmptyStringExample
String one is empty? true
String one is not empty? false
String two is empty? true
String two is not empty?false
String three is empty?true
String three is not empty?false
String four is empty?true
String four is not empty?false
String five is empty?false
String five is not empty?true
Static methods are special type of methods that work without any object of the class.
Static methods are special type of methods that work without any object of the class. Static methods are limited to calling
other static methods in the class and to using only static variables. The following example shows both ways to access static
method (through simply class name and through object).
StaticMemberClass.java
/**
* Access static member of the class through object.
*/
import java.io.*;
class StaticMemberClass {
// Declare a static method.
public static void staticDisplay() {
System.out.println("This is static method.");
}
// Declare a non static method.
public void nonStaticDisplay() {
System.out.println("This is non static method.");
}
}
class StaticAccessByObject {
A string is a contiguous sequence of symbols or values, such as a character string (a sequence of characters) or a binary
digit string (a sequence of binary values). In the example given below takes string value from user and reverse that string by
using String reverse(String str) method and set in alphabetical order by String alphaOrder(String str) method. Note that
passed string by user must be in upper case or in lower case but mixed cases are not permitted for this example.
Program asks the user to enter the input string. Once it is entered by the user, the program performs the reverse operations.
/**
* read a string and reverse it and then write in alphabetical order.
*/
import java.io.*;
import java.util.*;
class ReverseAlphabetical {
Array to Collection
List interface is a member of the JavaCollection Framework and extendsCollection interface. List interface is an ordered
collection which follows insertion order, typically allow duplicate elements. The List interface provides a special iterator,
called ListIterator for insertion, replacement and bi-directional access.
The Arrays class contains various methods for manipulating arrays (e.g. sorting and searching etc.) and extends
the Object class. The Iterator class allows access to the elements of a collection.
Methods used:
hasNext(): This method is used to get more elements. If the element at the next position is found then returns true otherwise
throws an exception.
asList(Object[] a): This method acts as a bridge between array and collection. This method converts array into Arrays by
internally using Colletion.toArray() method .
import java.util.Arrays;
import java.util.List;
import java.util.Iterator;
In this section you will be introduced to the concept of Arrays in Java Programming language. You will learn how the Array
class in java helps the programmer to organize the same type of data into easily manageable format.
Program data is stored in the variables and takes the memory spaces, randomly. However, when
we need the
data of the same type to store in the contiguous memory allocations we use the data
structures like arrays. To meet this feature java has provided an Array class which
abstracts the array data-structure.
The java array enables the user to store the values of the same type in contiguous memory allocations. Arrays
are always a fixed length abstracted data structure which can not be altered when required.
Now lets study the structure of Arrays in java. Array is the most widely used data structure in java. It can contain multiple
values of the same type. Moreover, arrays are always of fixed length i.e. the length of an array cannot be increased or
decreased.
Lets have a close look over the structure of Array. Array contains the values which are implicitly referenced through the
index values. So to access the stored values in an array we use indexes. Suppose an array contains "n" integers. The first
element of this array will be indexed with the "0" value and the last integer will be referenced by "n-1" indexed value.
Presume an array that contains 12 elements as shown in the figure. Each element is holding a distinct value. Here the first
element is refrenced by a[0] i.e. the first index value. We have filled the 12 distinct values in the array each referenced as:
a[0]=1
a[1]=2
...
a[n-1]=n
...
a[11]=12
By array's name, we mean that we can give any name to the array, however it should follow the predefined conventions.
Below are the examples which show how to declare an array :-
It is essential to assign memory to an array when we declare it. Memory is assigned to set the size of the declared array. for
example:
After declaring an array variable, memory is allocated to it. The "new" operator is used for the allocation of memory to the
array object. The correct way to use the "new" operator is
String names[];
In this example, a variable 'x' is declared which has a type array of int, that is, int[]. The variablex is initialized to
reference a newly created array object. The expression 'int[] = new int[50]' specifies that the array should
have 50 components. To know the length of the Array, we use field length, as shown.
C:\tamana>javac Sum.java
C:\tamana>java Sum
5050
C:\tamana>
We have already discussed that to refer an element within an array, we use the [] operator. The [] operator takes an "int"
operand and returns the element at that index. We also know that the array indices start with zero, so the first element will
be held by the 0 index. For Example :-
int month = months[4]; //get the 5th month (May)
Most of the times it is not known in the program that which elements are of interest in an array. To find the elements of
interest in the program, it is required that the program must run a loop through the array. For this purpose "for" loop is used
to examine each element in an array. For example :-
String months[] =
{"Jan", "Feb", "Mar", "Apr", "May",
"Jun",
"July", "Aug", "Sep", "Oct", "Nov",
"Dec"};
//use the length attribute to get
the number
//of elements in an array
for (int i = 0; i < months.length;
i++ ) {
System.out.println("month: " +
month[i]);
String months[] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"July", "Aug", "Sep", "Oct", "Nov", "Dec"};
Now, we run a for loop to print each element individually starting from the month "Jan".
In this loop int i = 0; indicates that the loop starts from the 0th position of an array and goes upto the last position which is
length-1, i < months.length; indicates the length of the array and i++ is used for the increment in the value of i which is i =
i+1.
Copying Arrays
After learning all about arrays, there is still one interesting thing left to learn i.e. copying arrays. It means to copy data from
one array to another. The precise way to copy data from one array to another is
Thus apply system's arraycopy method for copying arrays.The parameters being used are :-
The following program, ArrayCopyDemo(in a .java source file), uses arraycopy to copy some elements from the copyFrom
array to the copyTo array.
C:\tamana>javac
ArrayCopyDemo.java
C:\tamana>java ArrayCopyDemo
cdefg
C:\tamana>
In this example the array method call begins the copy of elements from element number 2. Thus the copy begins at the
array element 'c'. Now, the arraycopy method takes the copied element and puts it into the destination array. The
destination array begins at the first element (element 0) which is the destination array copyTo. The copyTo copies 5
elements : 'c', 'd', 'e', 'f', 'g'. This method will take "cdefg" out of "abcdefghij", like this :
Following image illustrates the procedure of copying array from one to another.
Two-Dimensional Arrays
Two-dimensional arrays are defined as "an array of arrays". Since an array type is a first-class Java type, we can have an
array of ints, an array of Strings, or an array of Objects. For example, an array of ints will have the type int[]. Similarly we can
have int[][], which represents an "array of arrays of ints". Such an array is said to be a two-dimensional array.
The command
declares a variable, A, of type int[][], and it initializes that variable to refer to a newly created object. That object is an array of
arrays of ints. Here, the notation int[3][4] indicates that there are 3 arrays of ints in the array A, and that there are 4 ints in
each of those arrays.
To process a two-dimensional array, we use nested for loops. We already know about for loop. A loop in a loop is called
a Nested loop. That means we can run another loop in a loop.
Notice in the following example how the rows are handled as separate objects.
Code: Java
int[][] a2 = new int[10][5];
// print array in rectangular form
for (int i=0; i<a2.length; i++) {
for (int j=0; j<a2[i].length; j++)
{
System.out.print(" " + a2[i]
[j]);
}
System.out.println("");
}
In this example, "int[][] a2 = new int[10][5];" notation shows a two-dimensional array. It declares a variable a2 of type int[]
[],and it initializes that variable to refer to a newly created object. The notation int[10][5] indicates that there are 10 arrays of
ints in the array a2, and that there are 5 ints in each of those arrays.
C:\tamana>javac
twoDimension.java
C:\tamana>java twoDimension
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
6 6 6 6 6
7 7 7 7 7
8 8 8 8 8
9 9 9 9 9
C:\tamana>_
Multi-dimensional arrays
So far we have studied about the one-dimensional and two-dimensional arrays. To store data in more dimensions a multi-
dimensional array is used. A multi-dimensional array of dimension n is a collection of items. These items are accessed
via n subscript expressions. For example, in a language that supports it, the element of the two-dimensional array x is
denoted by x[i,j].
The Java programming language does not really support multi-dimensional arrays. It does, however, supports an array of
arrays. In Java, a two-dimensional array 'x' is an array of one-dimensional array. For instance :-
The expression x[i] is used to select the one-dimensional array; the expression x[i][j] is ued to select the element from that
array. The first element of this array will be indexed with the "0" value and the last integer will be referenced by "length-1"
indexed value. There is no array assignment operator.
Introduction
In this example we are going to sort integer values of an array using bubble sort.
Bubble sort is also known as exchange sort. Bubble sort is a simplest sorting algorithm. In bubble sort algorithm array is
traversed from 0 to the length-1 index of the array and compared one element to the next element and swap values in
between if the next element is less than the previous element. In other words, bubble sorting algorithm compare two values
and put the largest value at largest index. The algorithm follow the same steps repeatedly until the values of array is sorted.
In worst-case the complexity of bubble sort is O(n2) and in best-case the complexity of bubble sort is Ω(n).
Code description:
Bubble Sorting is an algorithm in which we are comparing first two values and put the larger one at higher index. Then we
take next two values compare these values and place larger value at higher index. This process do iteratively until the
largest value is not reached at last index. Then start again from zero index up to n-1 index. The algorithm follows the same
steps iteratively unlit elements are not sorted.
Say we have an array unsorted A[0],A[1],A[2]................ A[n-1] and A[n] as input. Then the following steps are followed by
bubble sort algorithm to sort the values of an array.
1.Compare A[0] and A[1] .
2.If A[0]>A[1] then Swap A[0] and A[1].
3.Take next A[1] and A[2].
4.Comapre these values.
5.If A[1]>A[2] then swap A[1] and A[2]
...............................................................
................................................................
at last compare A[n-1] and A[n]. If A[n-1]>A[n] then swap A[n-1] and A[n]. As we see the highest value is reached at
nth position. At next iteration leave nth value. Then apply the same steps repeatedly on A[0],A[1],A[2]................ A[n-1]
elements repeatedly until the values of array is sorted.
Compare these two values .As 12>4 then we have to swap these values.
Then the new sequence will be
9 4 12 99 120 1 3 10
When we reached at last index .Then restart same steps unlit the data is not sorted.
Introduction
In this example we are going to sort integer values of an array using heap sort.
There are two types of heap. First one is Max heap and second one is min heap. Max heap is a special type of binary
tree .The roots of the max heap is greater than its child roots. Other heap is min heap it is also a special type of heap which
has minimum root than his child. We can sort the array values using heap sorting algorithm. In this algorithm the heap build
is used to rebuild the heap.
In this example we sorting all elements of an array. The complexity of the heap sort is O(n.log(n)). Heap sort is slowest but
it is better option for large data sets.
Step4:Swap 2 and 4
Step5:Swap 2 and 3.
Step6:Remove 4 and replace 2 at position of 4 and add 4 in array
Step7:Swap 2 and 3
C:\array\sorting>Javac heap_Sort.java
C:\array\sorting>java heap_Sort
Heap Sort
---------------
Unsorted Array
1 3 4 5 2
Sorted array
---------------
1 2 3 4 5
C:\array\sorting>_
Introduction
In this example we are going to sort integer values of an array using insertion sort.
Insertion sorting algorithm is similar to bubble sort. But insertion sort is more efficient than bubble sort because in insertion
sort the elements comparisons are less as compare to bubble sort. In insertion sorting algorithm compare the value until all
the prior elements are lesser than compared value is not found. This mean that the all previous values are lesser than
compared value. This algorithm is more efficient than the bubble sort .Insertion sort is a good choice for small values and for
nearly-sorted values. There are more efficient algorithms such as quick sort, heap sort, or merge sort for large values .
Positive feature of insertion sorting:
1.It is simple to implement
2.It is efficient on (quite) small data values
3.It is efficient on data sets which are already nearly sorted.
The complexity of insertion sorting is O(n) at best case of an already sorted array and O(n2) at worst case .
Code description:
In insertion sorting take the element form left assign value into a variable. Then compare the value with previous values.
Put value so that values must be lesser than the previous values. Then assign next value to a variable and follow the
same steps relatively until the comparison not reached to end of array.
Working of insertion sorting:
C:\array\sorting>javac InsertionSort.java
C:\array\sorting>java InsertionSort
RoseIndia
Selection Sort
Values Before the sort:
12 9 4 99 120 1 3 10
Values after the sort:
1 3 4 9 10 12 99 120
PAUSE
C:\array\sorting>_
In this example we are going to sort integer values of an array using merge sort.
In merge sorting algorithm unsorted values are divided into two equal parts iteratively. Then merge both parts and sort it.
Then again merge the next part and sort it. Do it iteratively until the values are not in sorted order. In merge sorting the
number of elements must be even. The merge sorting is invented by John von Neumann in 1945 .
The complexity of the merge sorting is in worst-case O(n log n) and in average case O(n log n).
Code description:
In merge sort split the array values in halves recursively until each half has only single element. Merge the two 1/2 values
together and sort the values. Do same steps iteratively until the values are not sorted.
Say we have an array unsorted A[0],A[1],A[2]................ A[n-1] and A[n] as input. Then the following steps are followed by
merge sort algorithm to sort the values of an array.
C:\array\sorting>javac mergeSort.java
C:\array\sorting>java mergeSort
RoseIndia
Selection Sort
Values Before the sort:
12 9 4 99 120 1 3 10
Values after the sort:
1 3 4 9 10 12 99 120
PAUSE
C:\array\sorting>_
Introduction
In this example we are going to sort integer values of an array using odd even transposition sort.
Odd even transposition sort is a parallel sorting algorithm. Odd Even is based on the Bubble Sort technique of comparing
two numbers and swapping them and put higher value at larger index .In each parallel computational steps can pair off
either the odd or even neighboring pairs. Each number (In Processing Element-PE) would look to it's right neighbor and if it
were greater, it would swap them.
Code description:
The odd even transposition sort is a parallel sorting algorithm. That mean more than one compression can made at one
iteration. The comparison is same as bubble sort.
System.out.println("\n\n RoseIndia\n\n");
System.out.println(" Odd Even Transposition Sort\n\n");
System.out.println("Values Before the sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
odd_even_srt(array,array.length);
System.out.print("Values after the sort:\n");
for(i = 0; i <array.length; i++)
System.out.print(array[i]+" ");
System.out.println();
System.out.println("PAUSE");
}
C:\array\sorting>javac
OddEvenTranspositionSort.java
C:\array\sorting>java OddEvenTranspositionSort
RoseIndia
Odd Even Transposition Sort
Values Before the sort:
12 9 4 99 120 1 3 10 13
Values after the sort:
1 3 4 9 10 12 13 99 120
PAUSE
C:\array\sorting>_
Introduction
In this example we are going to sort integer values of an array using quick sort.
Quick sort algorithm is developed by C. A. R. Hoare. Quick sort is a comparison sort. The working of quick sort algorithm is
depending on a divide-and-conquer strategy. A divide and conquer strategy is dividing an array into two sub-arrays. Quick
sort is one of the fastest and simplest sorting algorithm. The complexity of quick sort in the average case is Θ(n log(n)) and
in the worst case is Θ(n2).
Code description:
In quick sort algorithm pick an element from array of elements. This element is called the pivot. Then compare the the
values from left to right until a greater element is find then swap the values. Again start comparison from right with pivot.
When lesser element is find then swap the values. Follow the same steps until all elements which are less than the pivot
come before the pivot and all elements greater than the pivot come after it. After this partitioning, the pivot is in its last
position. This is called the partition operation. Recursively sort the sub-array of lesser elements and the sub-array of greater
elements.
Output:1 3 4 10 12 13 99 120
The code of the program :
System.out.println("\n\n RoseIndia\n\n");
System.out.println(" Quick Sort\n\n");
System.out.println("Values Before the sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
quick_srt(array,0,array.length-1);
System.out.print("Values after the sort:\n");
for(i = 0; i <array.length; i++)
System.out.print(array[i]+" ");
System.out.println();
System.out.println("PAUSE");
}
C:\array\sorting>javac QuickSort.java
C:\array\sorting>java QuickSort
RoseIndia
Quick Sort
Values Before the sort:
12 9 4 99 120 1 3 10 13
Values after the sort:
1 3 4 9 10 12 13 99 120
PAUSE
C:\array\sorting>_