From C to Java: an introduction to Java for C programmers

If you're programmed in C before, then you will already be familiar with some features of Java. In fact, Java was specifically designed to share many features of syntax with C (and C++). However, there are some crucial differences which we will discuss here.

Object orientation

Java is much more of a "true" object-oriented language than C. In an object-oriented language, data structures are implicitly tied to the functions or methods that deal with them. In C, it's common to write a type of object-oriented way. For example, if we were writing a patience game, we could define a struct to represent the data for a card:

typedef struct _CARD {
  unsigned int number;
  unsigned int suit;

then, possibly together in one source file, we can define a series of functions to manipulate cards:

int card_suitMatches(CARD *card1, CARD *card2) {
  return (card1->suit == card2->suit) ? 1 : 0;

In Java, structures and their methods are much more implicitly linked, into what are called classes. For example, in Java we would write something like this to create a "Card" class:

public class Card {
  private int number, suit;

  public boolean suitMatches(Card c) {
    return (c.number == this.number);

The method becomes almost like a member of the structure, and we call it as follows:

if (card1.suitMatches(card2)) {
  // do something...

A key feature of a "true" object-oriented language– and this is where things depart somewhat from C structs– is that classes can be extended. For example, we could define a JokerCard class as an extension of a normal card:

public class JokerCard extends Card {
  private int number, suit;

  public boolean suitMatches(Card c) {
    // We always pretend jokers match
    return true;

Then in our program, we can generally pass Cards around and call methods on them without necessarily worrying about what specific type of card we are dealing with. This simple concept proves to be very powerful for large, structured programs. It also allows us to program efficiently, by extending previously written units where necessary rather than having to repeat sections of code common to various versions of a type data (such as normal card vs joker card in our example).

Next, we look at differences in memory management between Java and C.

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.