Java

Brief History of Object Oriented Programming

  • SIMULA 67, an extension of ALGOL, was the first PL to introduce the idea of data abstraction
    • It's influence is often not recognized
  • The frist fully object-oriented langauge was Smalltalk, which was developed in the 70's
    • Not widely adopted
  • C++ started out as C with Classes in the early 80s, and became a fully separate language
    • The first version of C++ were released in 1985
  • Since then Object Oriented Programming Languages have continued to grow in popularity

What is Object Oriented Programming (OOP) ?

  • OOP is a fuzzy concept and programming languages can adhere to it to differing degrees
  • Can be broken down into three concepts. Various languages may not support all equally well
    • Polymorphism
    • Inheritence
    • Encapsulation

Encapsulation

  • The idea of bundling and object'ss state (variables) and methods together
  • Through use of methods, access to the object's can be controlled
    • Theoretically the programmer using an existing method should need to know or care about the internals of a class
    • All functions can be handled through a method
    • Some languages, like Python, allow this bundling, but have no way to prevent direct manipulation of the state
  • When done right, can lead to cleaner code and improved reusability

Misconceptions about OOP

  • While OOP languages are often based on imperative languages, it is not a good idea to use them like one
  • The difference is in the design of a program
    • With OOP we need to figure out what objects are involved in our project
    • With imperative languages, we figure out what steps are involved

History of Java

  • Invented a Sun Microsystems in 1991 by James Gosling and others
    • Not officialy released until 1996
  • The invetors wanted to fix what they saw as problems in C++ (ie, memory management)
  • Was designed to be runnable on many different devices, not just traditional computers
  • The current version is Java 8

Java Basics

  • Java in an interpreted language
    • Compiled down to Java byte code, which is the same for every device
    • The Java Virtual Machine ( JVM ) interperets the bytes code into machine code
      • In order to run Java, a JVM must have been constructed for your type of machine
  • Every Java program must have at least one class with a method named main

Basic Program Structure

In a file named HelloWorld.java

public class HelloWorld
{
 public static void main(String[] args)
 {
  System.out.println("Hello world!");
 }
}
In [ ]:
%%bash
cd java
java HelloWorld.java
In [ ]:
%%bash
cd java
javac HelloWorld.java
java HelloWorld

Variables

  • Must start with a letter, digit, or dollar sign
  • Can consist of any letter, digit, underscore, or dollar sign
  • The variable's datatype must be specified when it is declared.
  • The scope of variable is controlled by declaring it as public or private
    • public int x
      
    • private int y
      
  • Variables can be made read-only by use of the final keyword
  • Allocated space is garbage collected when they can not be reached again

Scope Example

In [ ]:
%load java/Scope.java
In [ ]:
%load java/ScopeMain.java
In [ ]:
%%bash
cd java
javac ScopeMain.java

Datatypes

  • While, Java is an OOP language, it still has a few primitive types that do not behave like objects
    • Although since Java 5, the compiler can convert primatives to their associated objects through a process known as boxing
  • The primitive types are
    • boolean
    • char
    • 6 varities of numbers
      • float, double
      • byte, short, int , long
  • Strings, arrays, and everything else are objects

Numbers

  • Java supports compound assignment on numbers as well as increment and decrement operators
    • int x = 0
       x += 1
       x++
       x -= 20
      
  • Only five basic arithmatic operations are supported
    • + , - , * , / , %
    • Exponent is a method in the math library, Math.pow

Strings

  • While strings are objects in Java, they can be declared with out using a constructor
    • String str = "This is a fine way to do things";
      
  • The + sign has been overloaded, and is used for concatenation
    • += is also available
  • Array syntax cannot be used with strings
    • Must use the methods charAt and substring
    • Both of these methods are read-only

Arrays

  • Similarly to strings, arrays can be be declared with out using a constructor
    int[] arr = {10, 20, 30};
    
  • To create a empty array of a given length , use the new keyword, which hints at its objectness
    int [] = new int[100];
    
  • Multidimensional arrays are easy to declare!
    int [][][] tensor = new int[100][100][100];
    
  • Array indexing is done using the [] operator; slicing is not supported

Primitive Type Conversion

  • Depending on the two types involved, the type conversion may either be implicit or explicit
    • If there is no danger of loss of precision, we can directly assign to the new type and not encounter any errors
      int number;
      long bigNumber = number;
      
      • If precision could be loss, a compilation error will be thrown unless explicit conversion is done
        long bigNumber;
        int number = (int) bigNumber;
        
  • Boolean variables cannot be converted to anything else

Object Type Conversion

  • To convert a string to one of the primitve classes we must use a wrapper class.
    String numString = "100";
    int number = Integer.parseInt(numString);
    
  • What a user defined object can be casted to depends on what it inherits from
    • We will talk more about inheritence later

Boolean Operators

  • The relational operators work as expected with primitive types
    • > , < , >=, <= , == , !=
  • For objects == does not work as you might expect
    • == compares the references of objects, it will only be true when the are the same object
    • To compare objects, we use the method equals
  • Objects have an additional operator, instanceof
    String s = "String";
           s instanceof String == true
    
  • The logical operators && and || only work with booleans

Loops

  • Java provides two for loops, a while loop, and a do-while loop
  • The standard counter based foor loop has the following syntax:
    for(int i =0; i < 100; i ++){
    }
    
  • Starting with Java 5, a generic for loop was added, it is called an enhanced for loop in java
    int[] toLoop = {10,20,30,40,50,60};
    for(int number: toLoop){
    }

Loops II

  • Java also offers logic controlled looping
    while(x < 0){
    }
    
    do{
    }while(x < 0)
    

Control Statements

  • Java originally made if statement avaialable and switch partially available
  • For if statements, there is no then keyword

    int x;
    if(x > 0){
    }
    else if(x < -100){
    }
    else{
    }
    
  • Since Java 7, switch can be used with strings

    String str;
    switch(str){
      case "Monday":
          <>
          break;
      case "Tuesday":
          <>
          break;
      default:
          <>
          break;
    }