Java vs. Python Programming Language Comparison

Java and Python are two popular programming languages that represent two very different approaches to structure and syntax. Java has a more formal, strict syntax. Python syntax is more forgiving and provides many shortcuts and abbreviations. Java is compiled and Python is interpreted.

The table below shows a sampling of Java and Python programming language elements that highlight these differences.

JavaPython
Block {
   . . .
}
def my_block( ):
      . . .
      CR
Class
Definition
public class Hello {
   . . .
}
class Hello:
      . . .
      CR
Class
Constructor
public Hello(Strng msg) {
    defaultMsg=msg;
}
def __init__(self, param1, param2, ...)
      self.p1=param1
      self.p2=param2
      CR
Class
Instantiation
Hello mHello=new Hello();
mHello=Hello( )
Class
Variable
static String myVariable; class MyClass:
      my_class_variable = 0
Comment // Comment text. # Comment text.
Constant final static MY_CONSTANT; MY_CONSTANT
Conditional if (a>b) {
   . . .
}  else {
   . . .
}
if (a>b):
      . . .
else:
      . . .
Exception
Handling
try { . . . }
catch { . . . }
try:
      . . .
except Error, e:
      . . .
Global
Variable
public class MyGlobals {
   public static String mG1
}
global my_global_variable
Importing import java.sql.*; import apackage as ap
from apackage import amodule
Inheritance class Child extends Parent{...} class Child(Parent):
Instance
Variable
// Declared outside methods
String mVariable;
class Hello:
      def __init__(self, param1)
            self.param1=param1
Iteration for (i=0; i<5; i++) {
    . . .
}

for (myElement : myCollection){
    . . .
}
for x in range(0, 5):
      . . .

for my_element in my_collection:
       . . .

for key, value in my_dictionary:
       . . .
Local
Variable
String myVariable; my_variable
Method
Definition
public void myIdea(String param) {
   . . .
}
def my_idea(my_parameter):
      . . .
      CR
Method
Use
myIdea(mParameter); my_idea(my_parameter)
Namespace
Reference
packageName;
my_namespace={'a':a_object, ...}
Null Value null
None
Statement
Separator
;
new line
Variable String mString="Hello Java";
my_string="Hello Python"

Software Components Overview

Below is a list of links to and brief descriptions of common software components. It's useful to keep these in mind and reference them during software design as a shorthand for code that will be written to implement the design. Implementing a component could involve just a few or many lines of code.

A suggested way to use these components in solving/coding a computing problem is to include them using a Separation of Concerns design pattern folded into what I call Layered Logic Problem Solving that includes these steps:

  1. Describe in words the problem to be solved. This might include references to software components listed below. You might also include solution acceptance criteria, possibly in the form of formal acceptance tests.
  2. Draw a block diagram of the main problem solution pieces. For more complex problems, other types of diagrams can be used.
  3. Annotate the block diagram with references to components such as those below.
  4. Code the solution in your chosen programming language.

Communications

  • Client-Server Architecture: components include:
  • HTTP Requestindicates the desired action to be performed on an identified resource - actions include: 
    • GET: retrieve data
    • HEAD: retrieve without response body
    • POST: create new subordinate data
    • OPTIONS: retrieve supported actions
    • PUT: create/replace data
    • DELETE: delete the resource
    • CONNECT: convert connection to TCP/IP tunnel, usually to facilitate HTTPS SSL
  • Internet Protocol Suite:
    • Layers: Application/Transport/Internet/Link
    • Levels: Send/Receive, Controls/Routing, Values/Translations
  • Firewall: monitor/control of incoming/outgoing traffic
  • JSON: JavaScript Object Notation, Human Readable, Attribute-Value Pairs, Java JsonObject
  • Load Balancer: distributes workload across computing resources
  • Message: data sent across processes
  • Network: allows computers to exchange data
  • Protocol: Data Formats, Address Formats, Address Mapping, Routing, Error Detection, Acknowledgements, Sequence Control, Flow Control
  • REST: Representational State Transfer, Stateless, Client-Server, JSON data
  • Socket: endpoint of a connection across a computer network

Data

Algorithms & Processes

Objects

  • Class: object template
  • Container: collection of other objects
  • Design Patterns: reusable solutions to common software problems  
  • Object Oriented Design Patternsreusable solutions to common object oriented software problems
  • Generics: specify type or method to operate on objects
  • Cloud Computing: internet based computing that provides shared processing resources
  • Interface : all abstract methods
  • Mutability: mutable, immutable, strong vs. weak
  • Objects: variables, data structure or function referenced by an identifier
  • OOD: uses inheritance, abstraction, polymorphism, encapsulation, other design patterns

Views

  • Ajax: groups of technologies for client-side asynchronous web applications
  • Android Fragments: UI segmenting, own lifecycle, FragmentManager
  • HTML5 Canvas:  bitmap, javascript
  • CSS:  describes the presentation of information
  • HTML:  head, body, div, script
  • Widget: simple, easy to use applicator
  • XML: markup language that defines a set of rules for encoding documents

Type System

A type system is a collection of rules that assign a property called type to constructs such as variables, functions, expressions and modules. Here are the two main dimensions of typing and some programming language examples:

Static vs. Dynamic

  • static:  type is set during compile
  • dynamic: type is set during execution

Strong vs. Weak

  • strong: type cannot change during execution
  • weak: type can change during execution

Language Examples

Java vs. Ruby Programming Language Comparison

Java and Ruby are two popular programming languages that represent two very different approaches to structure and syntax. Java has a more formal, strict syntax. Ruby syntax is more forgiving and provides many shortcuts and abbreviations. Java is compiled and Ruby is interpreted.

The table below shows a sampling of Java and Ruby programming language elements that highlight these differences.

JavaRuby
Block {
   . . .
}
def/class/do/if...
   . . .
end
Class
Definition
public class Hello {
   . . .
}
class Hello
   . . .
end
Class
Constructor
public Hello(Strng msg) {
    defaultMsg=msg;
}
def initialize(msg)
   . . .
end
Class
Instantiation
Hello mHello=new Hello();
mHello=Hello.new("Hello Ruby")
Class
Variable
static String myVariable; @@myVariable
Comment // Comment text. # Comment text.
Constant final static MY_CONSTANT; MY_CONSTANT
Conditional if (a>b) {
   . . .
}  else {
   . . .
}
if a>b
   . . .
else
   . . .
end
Exception
Handling
try { . . . }
catch { . . . }
raise . . .
 
Global
Variable
public class MyGlobals {
   public static String mG1
}
$mG1
 
 
Importing import java.sql.*; require 'extensions'
Inheritance extends MyClass < MyClass
Instance
Variable
// Declared outside methods
String mVariable;
@mVariable
 
Iteration for (i=0; i<5; i++) {
    . . .
}

for (myElement : myCollection){
    . . .
}
5.times do | i |
   . . .
end
Local
Variable
String myVariable; my_variable
Method
Definition
public void myIdea(String param) {
   . . .
}
def myIdea(param="Starter")
   . . .
end
Method
Use
myIdea(mParameter) myIdea m_parameter
Namespace
Reference
packageName;
: :
Null Value null
nill
Statement
Separator
;
new line
Variable String mString="Hello Java";
mString="Hello Ruby"

Programming Language Constructs

There are hundreds of programming languages. Although most aren't commonly used, a software developer might use a number of them during their career. It's useful to understand the concepts that underlie these languages. Click here for a comparison of programming languages

Below are brief descriptions of some common and important programming constructs with links to more details.

Abstraction

Separating ideas from specific instances of those ideas. Click here for more details.

Access Modifier

Define characteristics of constructs such as classes and methods. Examples of modifiers are: public, private, package and protected:  Click here for more details.

Array

A data structure consisting of a collection of elements, each identified by at least one array index or key. Click here for more details.

Attribute

Defines a property of an object, element, or file. Click here for more details.

Block

Section of code grouped together. Click here for more information.

Branch

Sequence of statements triggered by a conditional. Click here for more information.

Callback

Pointer to a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some appropriate time. Click here for more details.

Class

Code template for creating objects. Think of architect's drawings. Click here for more details.

Conditional

Performs different actions depending on whether a condition is true or false. Click here for more details.

Constructor

In Object Oriented Programming, a block of code that's executed when an object is created. Click here for more details.

Container / Collection

An object made up of other objects. Click here for more details.

DOM (Document Object Module)

Convention for representation and interaction between objects in HTML documents. Click here for more details.

Dynamic Array

Variable sized data structure that allows adding and deleting elements. In Java, an ArrayList is one type of Dynamic Array. Click here for more information.

Encapsulation

Packing of data and functions into a single component. Click here for more details

Exception

Anomalous or failure event that may require special handling. Click here for more details

Expression

Combination of elements that produces a result. Click here for more details.

Garbage Collection

Reclaiming of unused memory. In some operating systems, such as Android, Garbage Collection is automatic. Click here for more details.

Hash

Used to provide direct access to data based on a calculated key. Click here for more details.

HTML (HyperText Markup Language)

A set of elements that can read by web browsers for displaying web pages. Click here for more details.

HTML Element

Individual component of an HTML document. Click here for more details.

HTTP Request

Indicates the desired action to be performed on an identified resource. Actions include: GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE, PATCH and CONNECT. Click here for more details.

Identifier

Names for objects and entities. Click here for more details.

Inheritance

Obtaining the capabilities on an object. Click here for more details.

Inner Class

A Class that is declared entirely within the body of another class or interface. An inner class cannot be instantiated without being bound to a top-level class. Click here for more details.

Instance

Specific realization of an object. Think of a house vs. the plans for a house. Click here for more details.

Iterator

An object that enables traversing a container, such as lists. Click here for more details.

JSON (JavaScript Object Notation)

Human-readable text used to transmit data objects consisting of attribute–value pairs. Often used to transmit data between a server and web application. Click here for more details.

Keyword

Word with a special meaning. Click here for more details.

List

A sequence of values, where the same value may occur more than once. Click here for more details.

Linked List

A data structure consisting of a group of nodes which together represent a sequence. Click here for more details.

Literal

Notation representing a fixed value. Click here for more details.

Loop

A sequence of statements which is specified once but can be carried out multiple times in succession. Click here for more details.

Metaclass

A class whose instances are classes. Click here for more details.

Method

Code that defines the run time behavior of objects. Click here for more details.

Mixin

A class which contains a combination of methods from other classes without using inheritance. Click here for more details. Not available in pure Java.

Object

In Object Oriented Programming, an object is an instance of a class. Click here for more details.

Operator

Perform actions on elements such as variables. Click here for more details.

Overloading

Ability to create multiple methods of the same name with different implementations. Click here for more details.

Overriding

In object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. Click here for more details.

Package

A Java package is a mechanism for organizing Java classes into namespace groups. Click here for more information.

Parameter

A reference or value passed to a function, procedure, subroutine, command, or program. Click here for more details.

Polymorphism

Provision of a single interface to entities of different types. Click here for more details.

Primitive

Smallest 'unit of processing' available to a programmer of a particular machine, or can be an atomic element of an expression in a language. Click here for more details. For example, in Java, primitive data types are: byte, short, int, long, float, double, boolean and char.

Reflection

Ability to modify an object's own properties at runtime. Click here for more details.

Regular Expression

Sequence of characters that can be used as a search pattern. Sometimes referred to as Regex or Regexen. Click here for more details.

Reserved Word

A word that cannot be used as an identifier, such as the name of a variable or function. Click here for more details.

Return

A value that is passed from a calculating function to an invoking function. Click here for more details.

Sort

Functions that put elements in a certain order. Sorting is used so often that many programming languages have built-in sort functions. Click here for more information.

Statement

Expresses some action to be carried out. Click here for more details.

Switch

Control mechanism used to allow the value of a variable or expression to change the control flow of program execution. Click here for more details.

Table

A collection of related data held in a structured format within a database. It consists of fields (columns), and rows. Click here for more details.

This

Refers to the object, class, or other entity that the currently running code is part of. Click here for more details.

Token

An object which represents the right to perform an operation. Click here for more details.

Type

Collection of rules for constructs such as variables and functions. Untyped languages allow any operation to be performed on any data type.  Click here for more details.

Variable

A storage location and associated name which contains a modifiable value. Click here for more details.

Algorithm Design

An algorithm is a step-by-step procedure for performing calculations. Types of algorithms include:

Sometimes it's hard to know where to start in designing an algorithm for a task at hand. Below are some elements to consider during algorithm design.

Performance

Consider factors such as the average and worst case performance of your algorithm.

Design Patterns

Find a code design pattern that fits the problem you're solving.

Data Structure

The data structure you choose should reflect your data access needs.

Database Structure

A database is often a good data storage choice when the data needs to be accessed using a variety of search, sort and display options.

Data Sort

There's a large selection of sorting algorithms to select from. See which one most closely fits the nature of your data and access requirements.

Big O Notation

Big O notation is a way to characterize the time or resources needed to solve a computing problem.  It's particularly useful in comparing various computing algorithms under consideration. Below is a table summarizing Big O functions. The four most commonly referenced and important to remember are:

  • O(1)              Constant access time such as the use of a hash table.
  • O(log n)        Logarithmic access time such as a binary search of a sorted table.
  • O(n)              Linear access time such as the search of an unsorted list.
  • O(n log(n))   Multiple of log(n) access time such as using Quicksort or Mergesort.

Sorting Algorithms

Before delving into the large variety of sorting algorithms, it's important to understand that there are simple ways to perform sorts in most programming languages. For example, in Java, the Collections class contains a sort method that can be implemented as simply as:

Collections.sort(list);

where list is an object such as an ArrayList. Some aspects of the Java sort() method to note are:

  • You can also use the Java Comparator class methods to implement your own list item comparison functions for specialized sorting order needs.
  • The Java Collections class (plural) is different than the Collection class (singular).
  • Which sorting algorithm (see below) is used in the Collections.sort() implementation depends on the implementation approach chosen by the Java language developers. You can find implementation notes for Java Collections.sort() here. It currently uses a modified merge sort that performs in the range of Big O O(n log(n)).

If you don't want to use a built-in sort function and you're going to implement your own sort function, there's a large list of sorting algorithms to choose from.  Factors to consider in choosing a sort algorithm include:

  • Speed of the algorithm for the best, average and worst sort times. Most algorithms have sort times characterized by Big O functions of O(n), O(n log(n)) or O(n^2).
  • The relative importance of the best, average and worst sort times for the sort application.
  • Memory required to perform the sort.
  • Type of data to be sorted (e.g., numbers, strings, documents).
  • The size of the data set to be sorted.
  • The need for sort stability (preserving the original order of duplicate items).
  • Distribution and uniformity of values to be sorted.
  • Complexity of the sort algorithm.

For a comparison of sorting algorithms based on these and other values see: https://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms.

Here's a quick reference for the major algorithms:

  • Exchange Sorts: based on swapping items
    • Bubble sort: for each pair of indices, swap the items if out of order, loop for items and list.
    • Cocktail sort: variation of bubble sort, passes alternately from top to bottom and bottom to top.
    • Comb sort: variation of bubble sort, selective swap of values
    • Gnome sort: also called the stupd sort, moves values back to just above a value less than it
    • Odd-even sort: developed originally for use with parallel processors, examines odd-even pairs and orders them, alternates pairs until list is ordered
    • Quicksort: divide list into two, with all items on the first list coming before all items on the second list.; then sort the two lists. Repeat. Often the method of choice. One of the fastest sort algorithms
  • Hybrid Sorts: mixture of sort techniques
    • Flashsort: Used on data sets with a known distribution, estimates used for where an element should be placed
    • Introsort: begin with quicksort and switch to heapsort when the recursion depth exceeds a certain level
    • Timsort: adaptative algorithm derived from merge sort and insertion sort. 
  • Insertion sorts: builds the final sorted array one item at a time
    • Insertion sort: determine where the current item belongs in the list of sorted ones, and insert it there
    • Library sort: like library shelves, space is created for new entries within groups such as first letters, space is removed at end of sort
    • Patience sorting: based on the solitaire card game, uses piles of "cards"
    • Shell sort: an attempt to improve insertion sort
    • Tree sort (binary tree sort): build binary tree, then traverse it to create sorted list
    • Cycle sort: in-place with theoretically optimal number of writes
  • Merge sortstakes advantage of the ease of merging already sorted lists into a new sorted list
    • Merge sort: sort the first and second half of the list separately, then merge the sorted lists
    • Strand sort: repeatedly pulls sorted sublists out of the list to be sorted and merges them with the result array
  • Non-comparison sorts
    • Bead sort: can only be used on positive integers, performed using mechanics like beads on an abacus
    • Bucket sort: works by partitioning an array into a number of buckets, each bucket is then sorted individually using the best technique, the buckets are then merged
    • Burstsort: used for sorting strings, employs growable arrays
    • Counting sort: sorts a collection of objects according to keys that are small integers
    • Pigeonhole sort: suitable for sorting lists of elements where the number of elements and number of possible key values are approximately the same, uses auxiliary arrays for grouping values
    • Postman sort: variant of Bucket sort which takes advantage of hierarchical structure
    • Radix sort: sorts strings letter by letter
  • Selection sorts: in place comparison sorts
    • Heapsort: convert the list into a heap, keep removing the largest element from the heap and adding it to the end of the list
    • Selection sort: pick the smallest of the remaining elements, add it to the end of the sorted list
    • Smoothsort
  • Other
  • Unknown class

 

Object Oriented Programming Design Patterns

OOP Design Patterns are development templates that give software designers and coders shorthand ways of thinking about and solving programming challenges.

A full explanation of OOP Design Patterns can (and does) fill entire textbooks. Understanding and remembering every aspect of every pattern can be a daunting task. Hopefully the brief descriptions below will help in remembering the function of some common Design Patterns.

Often programmers need to discuss pattern usage with software designers, managers and other programmers. Getting too lost in the details can distract from communicating the essence of a software solution. Design Patterns can help with these challenges.

Some commonly used Design Patterns are listed below. Click on the Design Pattern name for a full pattern description.

  • Adapter - Facilitates object interaction.
  • Bridge - Similar to the Adapter pattern but more robust.
  • Builder - Similar to the Factory pattern for returning objects as an output but used in cases where many variables of output object construction are needed.
  • Chain of Responsibility - Uses a sequence of processing code blocks, each of which handles a specific set of conditions before passing control to the next block.
  • Command - Used to store and use the information needed to call a method at a later time.
  • Composite - Describes that a group of objects is to be treated in the same way as a single instance of an object.
  • Decorator - Also known as a wrapper, allows behavior to be added to an individual object.
  • Facade - Provides a simplified interface to a larger body of code.
  • Factory - Creates objects as a return output.
  • Flyweight - Minimizes memory use by sharing as much data as possible with other objects.
  • Interpreter - Specifies how to evaluate sentences in a language.
  • Iterator - Used to traverse a container and access the container's elements.
  • Mediator - Defines an object the encapsulates how a set of objects interact. Instead of communicating directly, the encapsulated objects communicate through the Mediator.
  • Memento - Provides the ability to restore an object to its previous state, such as an undo via a rollback.
  • Null Object - Object with defined neutral ("null") behavior.
  • Object Pool - Set of initialized objects kept ready to use, rather than allocating and destroying them on demand. Thread Pools are a common Object Pool implementation.
  • Observer - Maintains a list of other objects and notifies them of any state change. Objects that perform Callbacks operate as an observer.
  • Prototype - Similar to the Factory pattern, creates objects based on prototypical instances.
  • Proxy - Functions as an interface to something else.
  • Singleton - Restricts the instantiation of a class to one object.
  • Strategy - Enables an algorithm's behavior to be selected at runtime.
  • Template - Defines the program skeleton of an algorithm and defers some steps to subclasses.
  • Visitor - Separates an algorithm from the objects on which it operates.