Method – Add Two numbers

This tutorial uses the same code as Add Two Numbers but includes a function/method to add two numbers together and return a value. In this case the value is a integer (int) and that is why the int is just before the name of the method (addIntegers) with two parameters passed to the method, these are the values that are being added together. I have called them a and b, so that they are different names to the variables within the main method.

The source code

// just import the BufferedReader and inputstream reader
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
class addtwonumbers_function
{
       // private = local to this class
       private static int addIntegers(int a, int b)
       {
              return (a+b);
       }
 
       public static void main(String[] args)
       {
              // system.in reader (e.g. the input from the console)
              InputStreamReader ISR = new InputStreamReader(System.in);       
              // buffer the console reader
              BufferedReader BR = new BufferedReader(ISR);                     
 
              // the default values for the two numbers
              int val1 = 0;
              int val2 = 0;
              try 
              {
                     // output the question.
                     System.out.print("Enter first number : ");
                     // read in the console intput one line (BR.readLine) and then convert to a integer
                     val1 = Integer.parseInt(BR.readLine());
                     System.out.print("Enter second number : ");
                     val2 = Integer.parseInt(BR.readLine());
              }
              catch (Exception ex)
              {
                     // if the input was a string.
                     System.out.println(ex.toString());
              }
              // output the answer of adding both of the values together
              System.out.println("Answer = " + addIntegers(val1, val2));
       }
}

save as addtwonumbers_function.java, this program will function the same as the previous tutorial apart from the inner working will call the method. The method programming allows for one method to be called multiple times, e.g. Within the example above there could be a method that was 5 lines in length and instead of writing the same 5 lines each time, you just write a method that is called.

Class structure

This is a general tutorial about the class structure of programming languages.

The class is basically an object that allows public methods (accessed outside that class object) and private methods (the internal class logic) and protected with is the same as private apart from an inherited class can access the protected objects. Basically the 3 main types

Public : Access from outside the class, and internal of course, with inherited etc.
Protected : Access from inherited of the class, but not called from the class object.
Private : Access from only the class and friends of the class.

This is 3 Java source code to demonstrate

class classexample
{
       private       int value1;
       private       int value2;
       protected int value3;
 
       public int addtwo(int a, int b)
       {
              value1 = a;
              value2 = b;
              value3 = (a + b);
              return value3;
       }
 
       public int returnValue1()
       {
              return value1;
       }
}

save as classexample.java

class classexample2 extends classexample
{
       public int returnValue2()
       {
              //return value2;       // will error due to value2 is private in the inherited class
              return 0;              // to be able to compi
       }
 
       public int returnValue3()
       {
              return value3;       // fine since a protected part of the inherited class
       }
}

save as classexample2.java

class classex
{
       static public void main(String args[])
       {
              classexample example1 = new classexample();
              classexample2 example2 = new classexample2();
              System.out.println("Class 1, adding two numbers and setting the internal numbers");
              System.out.println(example1.addtwo(3,4));
              // of course will return 0, because example2 is not connected to example1 class, 
              // it just extends the definition of that class.
              System.out.println(example2.returnValue3());
       }       
}

save as classex.java

And to compile the tutorial just need to java classex because java will compile the other classes as well (and creates the class files). Once compiled the output will be

Class 1, adding two numbers and setting the internal numbers
7
0

Local variables

This is a tutorial about variable scope, a variable is a means to store data within the context of the program. For example, if you wish to store a numerical value then you would not store that number in a string, but within a integer or floating point number.

There are different types of variables, integer / string etc, but the scope of a variable is the area in which the variable is defined within block of code that it is situated.

This is some java code to demonstrate the difference between local variables and global.

class localvariable
{
       private static int value1 = 1;
 
       static public void globalVariable()
       {
              System.out.println("Global : " + value1);
       }
 
       static public void main(String args[])
       {
              int value1 = 0;
              globalVariable();
              System.out.println("Local : " + value1);
              return;
       }
       return 0;       
}

the output would be

Global : 1
Local : 0

Add two numbers

This tutorial will demonstrate how to read from the input console (console line) to answer the prompts. The prompts will need to be a integer value to add the two inputs together.

I am using the InputStreamReader to convert the System.in (console) into a stream, which into converted with a BufferedReader to get the whole line and not just one character/number.

The code

// just import the BufferedReader and inputstream reader
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
class addtwonumbers
{
       public static void main(String[] args)
       {
              // system.in reader (e.g. the input from the console)
              InputStreamReader ISR = new InputStreamReader(System.in);       
              // buffer the console reader
              BufferedReader BR = new BufferedReader(ISR);                     
 
              // the default values for the two numbers
              int val1 = 0;
              int val2 = 0;
              try 
              {
                     // output the question.
                     System.out.print("Enter first number : ");
                     // read in the console intput one line (BR.readLine) and then convert to a integer
                     val1 = Integer.parseInt(BR.readLine());
                     System.out.print("Enter second number : ");
                     val2 = Integer.parseInt(BR.readLine());
              }
              catch (Exception ex)
              {
                     // if the input was a string.
                     System.out.println(ex.toString());
              }
              // output the answer of adding both of the values together
              System.out.println("Answer = " + (val1 + val2));
       }
}

save that as addtwonumbers.java, because of course java is very picky about the class name to the java file, because Java creates a class of the same name as the class which in-turn is what the java virtual machine uses to execute.

Once compiled (javac addtwonumbers.java) and executed (java addtwonumbers) the output will be

Enter first number : 30
Enter second number : 23
Answer = 53

Read/Write Files

To read in from and file and also output to a file, java uses streams to “talk” to the files. These streams allow for communicating with different stream conversion tools, the object tool within this tutorial is the DataInputStream which “talks” to the FileInputStream.

I have attached the code within a zip file with the required input file as well.

Below is the code

import java.io.*;
 
class javareadfile
{
       public static void main(String args[])
       {
              String fileName = "country.txt";//input file
              String outFileName = "sqljavacountry.txt";//output file
 
              try
              {
                     // file input stream, basically a pointer to the stream of the input file
                     FileInputStream fStream = new FileInputStream(fileName);
                     // file output stream, basically a pointer to the stream for outputing data
                     FileOutputStream fOutStream = new FileOutputStream(outFileName);
 
                     // the input/output data streams that connect to the above streams
                     DataInputStream dInput = new DataInputStream(fStream);
                     DataOutputStream dOutput = new DataOutputStream(fOutStream);
 
                     // whilst there is data available in the input stream
                     while (dInput.available() !=0)
                     {
                            String in = dInput.readLine();// read a line from the input file
                            // output a stream of data to the output file
                            dOutput.writeBytes("insert into country(place) values (\""+in+"\");\n");
                     }
                     //close the two files.
                     dInput.close();
                     dOutput.close();
              }
              catch (Exception e)// incase of any errors
              {
                     System.err.println("There was a error : " + e.toString());
              }
       }
}

If you save this as javareadfile.java and also create a countrys.txt file with what ever text you like, e.g.

United Kingdom
France
Germany
United States
etc.

Once you have compiled the program (javac -deprecation javareadfile.java, may have to use -deprecation if using java virtual machine 1.5 over 1.4) and execute the program (java javareadfile), it will look for the file countrys.txt within the same directory as the program executable and also create outcountrys.txt within the same directory (it will write over the file if there is one present). Then within the while loop it will read the input file line by line and output to the screen what has been read and also output to the output file.

Of course to finish off to close down the files and return back to the console.

Hello world ! classic

This is the classic hello world tutorial for java, to get the java compiler and also the run-time environment you will need to goto the Java (Sun). The compiler (javac) compiles into java byte code, which means that this code is able to run on any OS with the java run-time environment (aka virtual machine).

If you save this

public class helloworld
{
	public static void main(String[] args)
	{
		System.out.println("Hello world");
	}
}

as helloworld.java

and then from the command line

javac helloworld.java

this will create the helloworld.class which is the java byte code, to run the byte code.

java helloworld

and hopefully there will be

Hello world

on the console.