Java for Python Developers 1 – Basics

The intention of this blog is to talk about the similarities and differences between Python and Java. This will be a series of blogposts, this being the first. Through this blog I plan to help myself and other Python developers learn Java easily by relating it to similar concepts in Python. The focus of this post will be on learning Basic concepts and writing some simple code in Java.

Why learn Java?

  • Java is a very popular and a widely used Programming language. It is used in building large systems due to it’s powerful JVM that leads to faster execution. When an Application needs to scale-up, Java is the most popular choice in the industry.
  • It supports Concurrency.
  • Java has a good cross platform support.
  • It has a very strong IDE support making the developer’s life easier.
  • It imposes certain best practices. There is most likely, a single way of doing stuff and hence a bad programmer can only harm so much. :\ But in case of languages like Python, there are several ways of writing a piece of code and the onus is completely on the developer to use the most optimized one.

Classes and Objects:

The concept of Classes, Objects and Object Oriented programming is similar to Python. But here’s the catch:

googleapisjavapython

Each .java file can only have a single public class that contains the main function. This is to know the exact point in the file from which the application is supposed to be launched. The name of this public class should be same as the name of the .java file.

Variables:

Again, the concept is very similar to Python including the naming conventions.

Java cares about Type. An Elephant cannot be put in a basket meant for vegetables. This is very much unlike Python, which decides if we need a Basket or a Cage based on whether the source is an Elephant or a vegetable that we are dealing with. 🙂 Moreover,

  • variables declared as final cannot be reassigned, once assigned to some value.
  • A variable of a particular type can be assigned to another of the same type. Example, a variable of the type Tiger (Tiger t1 = new Tiger()) can be assigned to any another variable of the type Tiger. (Tiger t2 = new Tiger(); t2 = t1;)
  • Java is PASS-BY-VALUE.

Global Variables in Python can be used as global x = 3. Java has no concept of global variables as such. However, a variable marked as public, static and final acts as a globally available constant.

Conditional Statement:

if(var1 == var2) { <do this>
}

Iteration:

WHILE Loop:

Use while loop when we do not know the exact number of times to loop, in advance. In other words, when we have to loop until a condition is satisfied.

while(boolean condn) { <repeat this>
}

FOR Loop:

for(int i=0;i<anArray.length;i++){
<repeat array-length number of times>
}

Enhanced FOR loop: (For each loop)

String[] AnArray = {"John","Bob","Andy","George","Rachel"};
System.out.println("Names: ");
for(String name: AnArray) {
    System.out.println(name);
}
teach-2562905_1280

DO NOT forget the SEMICOLON;

Java Library or Java API

Let’s now writing some simple code in Java to achieve certain redundant tasks using the built-in Libraries.

ArrayList:

ArrayList can perform some frequently used operations on Lists which otherwise takes multiple lines of code and iterations to achieve the same. Similar to the built-in functions for a List in Python, elements can be added to the list, removed, check if an element is present in a list, get the size of the list, get the index of an element etc. as follows:

import java.util.ArrayList;
ArrayList<String> ListPlaces = new ArrayList<String>();
String p1 = new String("Switzerland");
String p2 = new String("Singapore");
ListPlaces.add(p1);
ListPlaces.add(0,p2); //0 - index where p1 should be added
System.out.println(ListPlaces);
System.out.println(ListPlaces.size());
System.out.println(ListPlaces.get(0));
System.out.println(ListPlaces.indexOf(p1));
System.out.println(ListPlaces.remove(1));
System.out.println(ListPlaces.contains(p2));
System.out.println(ListPlaces.isEmpty());

Generating a random number:

int Rand = (int) (Math.random() * 10);

*(int) -> Type casting the return value of the random() function to an integer.

Obtaining user input from command line:

import java.util.Scanner;
System.out.println("Please enter your name: ");
Scanner sc = new Scanner(System.in);
String username = sc.nextLine();

Let’s play Battleship

Here’s an example program, the battleship game written in Java. We will play this on command-line. The game randomly assigns 3 Battleships on a 7×7 board. It allows the user to guess the location. On successful identification of each ship, it says “kill”. When all the ships sink, games ends with a score.

There may be better ways of writing this code but at this stage, we are just trying to get a step closer to learning Java. Here’s an implementation of the battleship game.

This code is also available on Github: https://github.com/shilpavijay/Battleship

import java.util.*;
import java.io.*;

public class Battleship {
    private GameHelper helper = new GameHelper();
    private ArrayList<PlayBattleship> battleList = new ArrayList<PlayBattleship>();
    private int noOfGuesses = 0;

    private void setUpGame() {
        PlayBattleship ship1 = new PlayBattleship();
        ship1.setName("Maximus");
        PlayBattleship ship2 = new PlayBattleship();
        ship2.setName("Aloy");
        PlayBattleship ship3 = new PlayBattleship();
        ship3.setName("Agnes");
        battleList.add(ship1);
        battleList.add(ship2);
        battleList.add(ship3);
        System.out.println(battleList);

        System.out.println("Your goal is to sink the three ships: Maximus, Aloy and Agnes with the least number of guesses.");
        for (PlayBattleship shipToset : battleList) {
            ArrayList<String> newLocation = helper.placeShip(3);
            shipToset.setLocation(newLocation);
        }
    }

    private void startPlaying() {

        while(!battleList.isEmpty()) {
            String userGuess = helper.getUserInput("Enter a guess");
            checkUserGuess(userGuess);
        }
        finishGame();
    }


    private void checkUserGuess(String userGuess) {
        noOfGuesses++;
        String result = "miss";

        for(int i=0;i<battleList.size();i++) {
            result = battleList.get(i).checkTheGuess(userGuess);
            if(result.equals("hit")) {
                break;
            }
            if(result.equals("kill")) {
                battleList.remove(i);
                break;
            }
        }
        System.out.println(result);
    }

    void finishGame() {
        System.out.println("Wow!!! You sunk all the ships! Congrats!");
        if(noOfGuesses <= 18) {
            System.out.println("Score: Congrats, you sunk all ships in " + noOfGuesses + " guesses!");
        }
        else {
            System.out.println("You have exhausted your options! Sorry! Please try again!");
        }
    }

    public static void main(String[] args) {
        Battleship game = new Battleship();
        game.setUpGame();
        game.startPlaying();
    }
}
class PlayBattleship {
    private ArrayList<String> location;
    private String name;

    public void setLocation(ArrayList<String> battleList) {
        location = battleList;
    }

    public void setName(String n){
        name = n;
    }
    public String checkTheGuess(String choice) {
        String result = "miss";
        int index = location.indexOf(choice);
        if(index>=0) {
            location.remove(index);
            if (location.isEmpty()) {
                result = "kill";
                System.out.println("You sunk " + name + ":|");
            }
            else {
                result = "hit";
            }
        }
        return result;
    }
}
class GameHelper {
    private static final String alphabet = "abcdefg";
    private int gridlength = 7;
    private int gridSize = 49;
    private int[] grid = new int[gridSize];
    private int comcount = 0;

    public String getUserInput(String prompt) {
        String inputLine = null;
        System.out.println(prompt);
        try {
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
            inputLine = input.readLine();
            if(inputLine.length() == 0) return null;
        }
        catch(IOException e){
            System.out.println("IOException: " + e);
        }
        return inputLine.toLowerCase();
    }

    public ArrayList<String> placeShip(int size) {
        ArrayList<String> cells = new ArrayList<String>();
        String temp = null;
        int [] curr = new int[size];
        int attempts = 0;
        boolean success = false;
        int location = 0;

        comcount++;
        int incr = 1;
        if((comcount % 2) == 0) {
            incr = gridlength;
        }

        while(!success & attempts++ < 200) {
            location = (int) (Math.random() * gridSize);
            int x = 0;
            success = true;
            while(success && x<size) {
                if(grid[location] == 0) {
                    curr[x++] = location;
                    location += incr;
                    if (location >= gridSize) {
                        success = false;
                    }
                    if (x>0 && (location % gridlength == 0)) {
                        success = false;
                    }
                }
                else {
                    success = false;
                }
            }
        }

        int x = 0;
        int row = 0;
        int column = 0;

        while (x < size) {
            grid[curr[x]] = 1;
            row = (int) (curr[x]/gridlength);
            column = curr[x] % gridlength;
            temp = String.valueOf(alphabet.charAt(column));

            cells.add(temp.concat(Integer.toString(row)));
            x++;
//            System.out.print(" co-ord "+x+" = " + cells.get(x-1).toUpperCase());
        }
        return cells;
    }
}

Conclusion:

In this blogpost we learnt how to use Variables, write Classes, conditional statements, loops in Java. We also glanced at some basics APIs or built-in libraries in Java that help perform certain redundant operations easily. We also put these concepts in action by coding a game.

Advertisement

One thought on “Java for Python Developers 1 – Basics

  1. Pingback: Java For Python Developers 2 – OOP – Reverie

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 )

Connecting to %s