Simple Java
Simple Java
What is programming?
Today there are different user friendly and easily understandable languages
supporting different styles of programming. Some of the computer languages are
like formula translation (FORTRAN), C, C++, PASCAL, BASIC, Java, C
sharp(C#) and many other high-level languages. Further an interpretable p-code
or byte code is generated in case some advanced languages like Java and .NET.
These languages enable one to create and perform various kinds of applications.
However, in the whole process of programming it is important to understand that
a program written in any of the high-level languages needs to be converted to
machine language to run on a computer. This conversion is done with a complier
or an interpreter. In all kinds of programming languages a complier and if
required an interpreter is available. But the basic difference between these two is
that the complier converts the entire program into machine code. An interpreter,
on the other hand, converts one statement at a time to machine language and
executes it.
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.
Earlier, it was only used to design and program small computing devices but later adopted
as one of the platform independent programming language.
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.
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 is developed by Sun Microsystems in 1996. Now the Java is powerful tools for the
development of robust and scalable enterprise applications.
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
In this beginners java Tutorial ,We will first download, install and configure the J2SE
development environment.
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
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:
Microsoft Windows 2000 [Version 5.00.2195]
(C) Copyright 1985-2000 Microsoft Corp.
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.
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.
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.
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
C:\javatutorial\example>javac HelloWorld.java
C:\javatutorial\example>java HelloWorld
Hello World!
Here is the screen shot of the above steps:
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.
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.
This is a very simple example of Java that teaches you the method of comparing two
numbers and finding out the greater one.
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.
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.
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 for loop in which define an
integer i=1 and i<= num also with an increment operator. Then apply the if
condition that i/2=0 i.e. to find even numbers which are divided by the integer 2.
In the end apply the catch exception.
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(Sys
tem.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 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.
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 Java programming tutorial will teach you the methods for writing program to
calculate factorial of any given number. First of all define a class "Factorial"
under the Java I/O package. 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 is used for writing bytes. As in this program we
are going to insert certain instruction by creating buffer reader class, it is
necessary to use 'try' and 'catch' block for catching and handling exceptions
during execution of the program.
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.
The strings length and content change as soon as any object is inserted,
replaced or removed from the StringBuffer object.
Now create a buffer object that inherits properties from the string object class.
Now create an InputStreamReader that reads bytes and decodes them into
character by using certain 'charset'. Now use the ParseInt method for converting
the parses the string argument to a decimal integer and define 'a' as an integer.
Take an integer variable as fact=1 and insert the message in the System
method.
Now applying for loop with conditions as integer i=1(intializer), i<=a and i++ as
increment operator. So output result will be like fact=fact*i.
import java.io.*;
class Factorial{
public static void main(String[] args) {
try{
BufferedReader object = new BufferedReader(new InputStreamReader(Syst
em.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
int fact= 1;
System.out.println("Factorial of " +a+ ":");
for (int i= 1; i<=a; i++){
fact=fact*i;
}
System.out.println(fact);
}
catch (Exception e){}
}
}
This is the updated example of factorial that will evaluates the factorial of number
in double which is lies in the range of double data type in java.
import java.io.*;
class Factorial1{
public static void main(String[] args) {
try{
BufferedReader object = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
double fact= 1;
System.out.println("Factorial of " +a+ ":");
for (int i= 1; i<=a; i++){
fact=fact*i;
}
System.out.println(fact);
}
catch (Exception e){
System.out.println("Array out of bounds exaception");
}
}
}
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.*;
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 lesson in Java programming will teach you the coding for constructing a
shape of triangle by using '*'. First of all make a class named 'triangle' under the
Java I/O package and as we have to use the Buffer class, the application of all
try and catch block is important for avoiding any kind of error. After creating
BufferedReader object and input stream reader define an integer 'a' and apply
parseInt method for the conversion of string into integer.
Now apply the for loop and define an integer 'i' and it should be either less than
or equal to the integer "a" (the input number). Again define another integer type
variable "j" in another for loop. Here in the second for loop "j" the number of
times we have to print *.
Now compile and run the program and insert any number on your command
window and surely you will get a triangle shape with star *. You can take any
other object instead of *.
import java.io.*;
class triangle{
public static void main(String[] args) {
try{
BufferedReader object = new BufferedReader(new InputStreamReader(Syst
em.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
for (int i=1; i<a;i++ ){
for (int j=1; j<=i;j++ ){
System.out.print("*");
}
System.out.println("");
}
}
catch(Exception e){}
}
}
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");
}
}
}
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.
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.
Here is the code program:
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.
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);
}
}
}
}
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.
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.
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 that ex.getMessage() prints
the information about the error occurring causes.
import java.io.*;
In this example you will learn what is identifier and primitive data types of a
identifier. This tutorials will teach you how to use these identifier in you java
programming. Identifier is is a simple variable name which is defined as the value
container. The type of value stored by identifier is defined by the special java
keyword is termed as primitive data type.
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 and String.
All the data type has it's own capacity to keep the maximum value. Which have
been mentioned below :
Source: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html
In this example you will see that how you can use variables, constants and literals in your
program easily.
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
The buffer size may be specified, or the default size may be used. The default is
large enough for most purposes.
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.
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) of java.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
and then create a byte type buffer for buffering the contents of one file and write
to another specified file from the first one specified file.
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
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.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.
Explanation
This program deletes the specified file if that exists. We will be declaring a
function called deletefile which 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 returns true 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 list files and folders present in the specified
directory. This topic is related to the I/O (input/output) of java.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 list the file of the specified directory. We will be declaring a function
called dirlist which lists the contents present in the specified directory.
dirlist(String fname)
The function dirlist(String fname) takes directory name as parameter. The
function creates a new File instance for the directory name passed as parameter
and retrieves the list of all the files and folders present in the directory by calling
list() method on it.
Then it prints the name of files and folders present in the directory.
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.
Inthis 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 using arrayname.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.*;
This example introduces you with the Applet in Java. You will learn how to
develop applet code and run in the browser.
Applet is a program provided by java which is designed for execution within the
web browser. Applets are mostly used for a small internet and intranet
applications because of small size and it's compatibility among almost all web
browsers. Applets are also very secure. For example, Applets can be used to
serve animated graphics on the web.
This example creates a simple applet that displays Hello World message.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
Compiling Applets:
javac HelloWorldApplet.java
java HelloWorldApplet
Running applet in browser is very easy job, create an html file with the following
code:
<html>
<head>
<title>A Simple Applet program</title>
</head>
<body>
<APPLET CODE="HelloWorldApplet.class"
WIDTH=700 HEIGHT=500>
</APPLET>
</body>
</html>
The Applet tag in html is used to embed an applet in the web page.
Boolean expression performs the relational or logical operations and returns the
boolean value (True/False).
In this example you will see that how the expression returns a boolean value
which is either true or false. This example illustrates you how to make a boolean
expression by using relational operators and how to use the returned value of the
expression.
This program reads two int type value and print the message with the returned
boolean value for the boolean expression in which many types of relational
operators are used.
import java.io.*;
public class booleanOperation{
public static void main(String[] args) throws Exception{
try{
int a;
int b;
BufferedReader in = new BufferedReader(new InputStreamReader(System.i
n));
a = Integer.parseInt(in.readLine());
b = Integer.parseInt(in.readLine());
System.out.println("a = " + a + "and\nb = " + b);
System.out.println(a + " is greater than " + b + " : " + (a > b));
System.out.println(a + " is less than " + b + " : " + (a < b));
System.out.println(a + " is equal to " + b + " : " + (a == b));
System.out.println(a + " is greater or equal to " + b + " : " + (a >=
b));
System.out.println(a + " is less than or equal to " + b + " : " + (a
<= b));
System.out.println(a + " is not equal to " + b + " : " + (a != b));
System.out.println(a + " is equal to " + b + " : " + (a == b));
}
catch(IOException e){
System.out.println(e.getMessage());
System.exit(0);
}
}
}
In this example you will learn about Math class. 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 :
E
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, capacity etc.
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.*;
//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.
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 of
String class. We are going for using charAt() 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 use length() 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. We are going for using toUpperCase() method. This method is explained
as follows:
Description of program:
Here, you will see the procedure of converting letters of the string in uppercase
letter. So, we are using toUpperCase() method of the String class for the
purpose.
The following program convert the string "india" into "INDIA" by using
toUpperCase() method.
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 use string 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.
Output of program:
C:\>javac StringCharacter.java
C:\>java StringCharacter
chanan
tapan
Amar
santosh
deepak
C:\>
Average of Array
Posted on: June 5, 2007 at 12:00 AM
In this section, we will learn how to get an average of array.
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 method outputArray() 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
C:\amar work>java
MatrixSum
Number of Row= 2
Number of Column= 3
Matrix 1 :
456
689
Matrix 2 :
546
567
Addition of both matrix :
9 9 12
11 14 16
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
Posted on: June 5, 2007 at 12:00 AM
Now, you have to learn about the syntax of If-Else construct.
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.*;