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.

C++ DLL Objects accessed from C#

Because there is a few things that c# cannot do compared to c++, e.g. cpu/memory management. And also there is probably allot of dll’s out there are still required for some events, c# is able to communicate with these files and use there functions within the c# language.

To create an dll within Visual Studio 2005 within the language c++, if you do the following

1. New project -> c++ -> empty project
2. Enter project name (e.g. hellocdll)
3. Right click source files ( in the solution explorer) add-> new item
enter an cpp filename.
4, Right click on the main project heading in the solution explorer -> properties
configuration properties->general inner screen project defaults -> configuration type, alter to dynamic library (.dll)
5. Copy and paste code and then compile.

#include <stdio.h>
 
extern "C"
{
  __declspec(dllexport) void DisplayMessageFromDLL()
  {
              printf ("Hi From the C DLL!\n");
  }
 
  __declspec(dllexport) int DisplayValueAndReturn(int i)
  {
         printf("Value %i\n", i);
         return i+2;
  }
}

The extern “C” means that the references within the code are going to be available externally and marco __declsepc(dllexport) is for the MS compile to inform that functions are to be available within an dll file.

To create an c# project to communicate with the above dll

1. New project -> c# -> empty project
2. Enter project name (e.g. hellodlltest)
3. Right click on the project name ( in the solution explorer) add-> new item
select class and enter a filename
4. Copy and paste the code and then compile. (you may need to change the Dllimport to the dll file name that has been created from the c dll project)

using System;
using System.Runtime.InteropServices;     // DLL support
 
namespace hellodlltest
{
    class hellodllC
    {
        [DllImport("hellocdll.dll")]
        public static extern void DisplayMessageFromDLL();
 
        [DllImport("hellocdll.dll")]
        public static extern int DisplayValueAndReturn(int i);
 
        static void Main ()
           {
                  Console.WriteLine ("C# program 'talking' to an C DLL");
            DisplayMessageFromDLL();
            Console.WriteLine(DisplayValueAndReturn(3).ToString());
           Console.ReadLine()
           }
    }
}

5. Copy the dll file from the debug directory of the c++ created dll project and place into the created bin/debug directory for this c# project

Operator

The standard class function are not able to utilize the standard operators within the c# language, for example the multiple, add, subtraction and divide in a mathematics example.

To overcome this problem, there is a ‘operator’ special syntax that allows for this to take place. The operator can work with any of the c# language standard functions of which you are able to program there functional aspects within the class. The syntax for this is

public static <return type> operator <operator type>(<parameter list of passed variables>);

for example if there was an return type of int and two integer values passed in the parameter list and using the addition operator.

public static int operator +(int a, int b)

Below is some code that will demonstrate this further within a general code development.

using System;
 
class operatorBase
{
       private int i;       // private member of the class
 
       public operatorBase() 
       {
              i = 0;       
       }
 
       public operatorBase(int init)  
       {
              this.i = init; 
       }
 
       // get and set the value for the private member i
       public int Value
       {
              get { return i;}
              set { i = value;}
       }
 
       // the operator +, parameters are the two values that you want to add, can be overloaded with different values
       // e.g. (int i2, int i3) for example.
       public static operatorBase operator +(operatorBase i2, operatorBase i3)
       {
              // create the return;
              operatorBase locali= new operatorBase();
              locali.i = i2.i + i3.i;  have access to the internals of passed parameters
              return  locali;       // return the operatorBase class
       }
}
 
class operatorTest
{
 
       public static void Main()
       {
              operatorBase opBase = new operatorBase();
 
              // set the value to 3 and also output the value;
              opBase.Value = 3;
              Console.WriteLine(opBase.Value);
 
              operatorBase opBase2 = new operatorBase(4);
 
              // to add to the operatorbases together, but will return an operatorBase, thus bracket the equation and use the .Value to get the value. 
              Console.WriteLine((opBase + opBase2).Value);
 
              // since creating two new on the fly operatorBase, then the result is an int value again.
              Console.WriteLine((new operatorBase().Value = 3) + (new operatorBase().Value = 2));
       }
}