C to Java

Well it is not an advanced topic by any means, just a place to recall some jargons of these languages (C, C++ and Java). This might be part one of two posts in a series. Some of the topics I haven’t covered are related to Generics, String, Networking, I/O (Even Google’s I/O), Concurrency etc. This post is a starter, yet complete on its own respect.

1. In C starting point is off course pointers.

What is a pointer?
A pointer is a variable that can hold the address of a variable. Here address means location in memory where the object or value of a particular variable is stored. We can get address of any variable with “&”.

E.g
int x = 5;
int *ptr = &x;

/*
int *ptr;
ptr = &x;
*/

int y = *(&x);
y = *ptr;

Lets look at above example. First we create a variable called x and gave it a value of 5. The variable can be located anywhere in the memory, the location which we don’t know. Next we create a pointer to integer called *ptr and put the address of variable x into it. Thus ptr is a pointer (a variable that can store an address). If this line makes no sense next line dissects it into two steps. First we create a pointer to integer with int *ptr and then put address of x (which we get using &x) and put it in ptr pointer. Next we create another variable y and dereference (return object or value) that is at address of x using the dereferencing operator * (don’t confuse this with our earlier pointer declaration as in int *ptr, both are different).

A pointer is thus a variable which is always the size of the underlying architecture (it does not depend upon the type of variable e.g int, char or double, because address size of first block to any of these types is same), though pointers are aware of the type they are pointing. They must know how much bytes they must occupy according to the type. E.g if integer takes 4 bytes (32-bit) and char takes 1 byte (8-bit) then if ptr is pointer to integer *(ptr + 1) will give value of next pointer location which could be four bytes ahead of current value and if ptr is pointer to  char, then it might need to go only one byte ahead to get value of next consecutive memory location.

2. Programs often crash with lvalue and rvalue, so what are they.
lvalue – Variable name
rvalue – Result of calculation

3. How to define macro in c

#define max(A, B) ((A) > (B) ? (A) : (B))

We can use

x = max (5 + 2, 6 + 3)

This expression will be replaced with something like this
x = (5 + 2, 6 + 3) ((5 + 2) > (6 + 3) ? (5 + 2) : ( 6 + 3));

4. Using reference in C++

void square(int &num)
{
num *= num;
}

It is just like passing pointers in c and c++. It has one difference with pointers is that pointers can keep on changing whom it points to, but references cannot. Here reference argument must be a variable name (lvalue). It makes sense, because it can be used to pass large data(e.g objects) just like pointers. If you choose to use pointers instead or even the reference it is always safe to pass them as constants unless required, rather than one that can be modified.

Function pointers

A pointer to a function contains the address of the function in memory. With this we can pass functions as parameters in another function, returned, stored in arrays or assigned to other function pointers. Function pointers helps us to use different functions at different times.

#include <stdio.h>

void myfunc(int a, int b, int (*needaname)(int, int))
{
int c = a + b + needaname;
printf("Total : %d\n", c);
}

int sum(int a, int b)
{
return a + b;
}

int mul(int a, int b)
{
return a * b;
}

int (*myglobal) (int, int) = NULL;

int main() {

myglobal = (int *)sum(2, 3);

myfunc(3, 5, myglobal);

// Or we could use it directly without declaring myglobal function pointer
myfunc(3, 5, mul(2, 3));

return 0;
}

It might have been fairly new concept and a annoying one, but since all modern language have this feature (except java if you don’t count anonymous inner class) as lambda function, closures or even delegates, thus it is worth noting. The concept here is to provide a door with an interface, so that people can implement all kind of crazy algorithms with it.

5. Friend function
It is a way to tell a class I trust you and you may access my private variables and methods. If one class adds another class as friend, friend class can access private variables and methods of this class and not vice versa.

class IMakeFriends {
private:
char[] privatemessage();
friend class HorribleClass;
};

class HorribleClass {
// Huhuhaha I can read privatemessage() of IMakeFriends and don't have to give anything in return, IMakeFriends has let me
// access all by not restricting me to some function
private:
IMakeFriends *friend;
};

HorribleClass::HorribleClass()
{
cout << friend->privatemessage();
}

6. Self referential class

class Node {
public:
Node(int);
void setNextPtr(Node *);
}

This type of syntax is often used in trees, linked lists. Here it does not create a variable of its own type, but creates a pointer, so it can recursively point to other nodes.

7. Standard Template Library
Standard Template Library contains many containers. There are sequence containers like vector(insertion at back), deque (insertion at front and back), list (insertion deletion anywhere), associative containers like set(no duplicate), multiset(duplicates allowed), map (key-value mapping no duplicate), multimap (duplicates allowed) and container adapters like stack (LIFO), queue(FIFO) and priority_queue (highest priority first). Some of these are used to hold objects and provide pre written methods like find, iterate, insert etc. Java has this functionality starting from J2SE 5 (late in the game) and are called Generics like List, Map, Stack, though they had similar classes like Dictionary, Vector, Properties in previous versions. Some of these old classes have been imported to new with some modifications but some are depreciated.

8. Its time to enter Java space with Object Oriented Programming

Why was java created?
Off course to make money for the enterprises. Languages are created or enhanced for two reasons: One is people develop many feature out of the standard language feature to enhance its capability. This is enhancement in art of programming, so languages tend to bring those features in the core language. Another is change in environment. E.g new hardwares come which demand some functionality that the language is unable to provide, new trends of businesses appear. Java was created to address second feature i.e platform independent nature and distribution of program via internet. Java was thus programming language of the internet. It even attracted existing C and C++ programmers to write platform independent Desktop applications. There are some buzz words java has like Simple (Simple to learn), Secure (due to JVM), Portable (platform independent), Object Oriented, Robust (multithreading, finding error fast, use exceptions), Multi-threaded, Architecture-Neutral (size of int is 32 bit even on 64 bit computers and not like c which depends on underlying architecture).

What java brought with J2SE 5?
Generis, Metadata(easy for different tools to be developed for easy coding), Autoboxing and Auto-unboxing(object wrappers for primitive types like int, short, double like Integer, Short and Double), Enumeration (it is object as opposed to enum in c), Enhanced for loop for looping generics, Variable arguments (vargars), Static Import (Static types can be imported), Formatted I/O (like printf in c), concurrency utilities (threading).

What is object oriented programming? Why do we need to care?
Programs consists of two elements code and data. Code is that part of the program that manipulates data. In process-oriented model program is executed as a series of linear steps. Here code is acting on data directly. For a large project this process can quickly get out of hand. Even large C projects tend to implement much of their functionality in object oriented fashion to provide similar experience in c programs. As opposed to code controlling data, “object oriented  programming organizes a program around its data (i.e object), and a set of well defined interfaces (public methods) to manipulate that data”. By giving data control over its code rather than code giving control over its data has several organizational benefits. Thus, we can say object oriented programming is better program organization, rather than better coding (you can always write bad programs even following object oriented methodology). Enough said, so how do we get this organization. Before getting to know more about the benefits of object orientation programming (or better program organization) we need to know a key concept that drives object oriented programming. It is called “abstraction”.

What is abstraction?
Think of a car. A car is made of thousands of components but a user is only required to know how to drive it. A user thinks car as an object, although it is made of thousands of tiny or big components. We human need thus understand complex things by using a simple interface. Similar technique of abstraction can be used in programming language. E.g When you call System.out.println(“Hello World\n”); java can call one or more read function from C and much more read function in assembly, but due to abstraction a java programmer is only required to know how to write a println function. Similarly when we create a class we can let user of that class take this as a concrete object with some functionalities(variables) and way to change them(methods). This leads us to three object oriented principles. The way to make this organization of code make the project last through inevitable changes. They are “encapsulation”, “inheritance” and “polymorphism”.

Encapsulation
First key to abstraction is encapsulation. Encapsulation binds data and code together. In java we achieve this is through class. Using encapsulation we can hide what others don’t need to see and show what others need to access and use. We can bind many data in a data(the class which eventually becomes a data itself) and provide interfaces(public methods) to access those data. With the help of encapsulation we can create a class that acts just like a car to its users (allowing methods like accelerate, brake to affect data like speed, fuel etc). Only way for a user to change speed is by using accelerate or brake. A user cannot change the speed by turning on the head light or listening to the radio. Clear, well defined interfaces(methods) to modify desired properties(variables) is the key to write non-intrusive code. I.e one part of code does not interfere with other, and if an interface does not change user can later replace that part with some other code without breaking the interface. We can use access modifiers like private, public and protected to achieve these goals.

Inheritance
Inheritance is a technique by which one object acquires the properties of another object. As we know by designing a class we can create many objects of that class that has similar properties, via inheritance we can get properties from another class and we still can add our own properties that we don’t have to share with the class from which we inherited. Moreover we can override any methods from that parent class which we don’t like as it is in this class. This feature enables us to write only those features that matters to this class and acquire the general set of features from its parent.Since its parent can again have parents, we can build an inheritance hierarchy. In case of process oriented programming we had to write all those features individually and with different names if we wanted different both.

Polymorphism
Overriding feature which we discussed above in inheritance is a way to achieve runtime polymorphism. Polymorphism is a technique in which we can use one interface for multiple methods to implement. Think of this like a person who know driving knows how to accelerate, brake. No matter which company makes a car they implement these features. Or even say no matter what vehicles companies make they implement these features. So the user only needs to know what he/she already know. When the person accelerates a toyota car it may go faster than when he applies accelerate in a tractor. Due to inheritance we can have a general class called Vehicle which has accelerate and brake methods. So both car and tractor can implement these functions on their own way. Later users needs to get a reference to any one of tractor or car using vehicle variable. This variable can through runtime polymorphism access methods overridden in its children class. When the vehicle context is car accelerate method of vehicle calls accelerate of car and when the context changes to tractor it calls accelerate of tractor.

e.g A method in a Drive class could be

take_speed(Vehicle vehicle) {
vehicle.accelerate();
}

and the vehicle class could be

class Vehicle {
protected double speed;

void accelerate() {
speed += 1.0;
}
}

class Car extends Vehicle {

@override
void accelerate() {
speed += 5.0;     // Car needs to be faster;
}

}

class Tractor extends Vehicle {
@override
void accelerate() {
speed += 0.2;       // Tractors are very slow
}
}

// We can pass appropriate vehicle as

Vehicle vehicle;

// Lets assume we are at field
context = "FIELD";

// Since J2SE 7 they have switch for String, hope this works
switch (context) {
case "FIELD":
vehicle = new Tractor();
break;
case "RACING":
vehicle = new Car();
break;
default:
vehicle = new Vehicle();
break;
}

//We can pass vehicle to take_speed method as
take_speed(vehicle);

Method Overloading
Another feature often described as polymorphism is method overloading. E.g

read(File file);
read(String file);
read(String dir, String file);

Since dynamic loading of methods is costly in terms of memory, so compilers often implement these functions with different named during compilation, so they actually don’t become a polymorphism at all. E.g three read above could be re-written by compiler as

read_fie(File file);
read_file_str(String file);
read_dir_file(String dir, String file);

Some languages don’t support method overloading at all (e.g Vala does not support method overloading to make it compatible with GObject c code). Runtime polymorphism and above code is the basis for strategy pattern.

9. Recursion

Recursion is known but often ignored technique in programming. A function calls itself until a condition is meet to solve a problem.

public class Factorial {
static int testNumber;

static {
testNumber = 5;
}

public static void main(String[] args) {
System.out.printf("Factorial of %d is %d", testNumber, factorial(testNumber));
}

private static int factorial(int n) {
int result;

if (n == 1)
return 1;
else
return factorial(n - 1) * n;
}
}

Here I used static variable (though not required) initialized it using static block and used formatted text inside printf method of out object of System class.

10. Anonymous Inner Class

As I described earlier in function pointers this is one feature that has made till jdk 7 non implement lambda or closure. It is hoped to come with jdk 8. There is no wrong in hopping.

public class MyApplet extends Applet {
public void init() {
addMouseListener(new MouseAdapeter() {
public void mousePressed(MouseEvent event) {
System.out.println("X: " + event.getX() + " , Y: " + event.getY());
}
});
}
}

MouseAdapter is actually an abstract class (a class that cannot be initiated, so the new is referring to a class inherits MouseAdapter and not MouseAdapter itself.

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s