Object Oriented Programming

Intro to Java

Intro to Java

Table of Contents

Overview

Java Features

  1. Compiled and interpreted
    • Compiled language (e.g. C)

compile

java_compiled_and_interpreted

  1. Platform independent

platform_independence

  1. Object oriented

Compilers, Interpreters, etc.

Drawn from python interpreter and Absolute Java Ch 1.

Java Virtual Machine

JVM

Just-in-time compilation

JIT compilation

Hello world!

// HelloWorld.java: Display "Hello World!" on the screen
import java.lang.*;             // imports java.lang.* package; optional
public class HelloWorld{        // name of class must be same as filename
    public static void main(String args[]) {    // standalone program must have main defined
        // args[] contain command-line arguments
                                              
        System.out.println("Hello World!");     // out is an object
        return;                                 // optional; usually excluded
    }
}

Compiling and running

# compile
$ javac HelloWorld.java
# compiler outputs 
$ ls HelloWorld*

# run: note absence of extension
$ java HelloWorld

Comments

Command Line args

Java vs C

identifiers

Data types

Java Primitives

Type Size (bytes) Values
boolean 1 false, true
char 2 All UTF-16 characters (e.g. ‘a’, ‘ρ’, ‘™’)
byte 1 −27 to 27 − 1 (-128 to 127)
short 2 −215 to 215 − 1 (-32768 to 32767)
int 4 −231 to 231 − 1 (≈ ±2 × 109 )
long 8 −263 to 263 − 1 (≈ ±1019)
float 4 ≈ ±3 × 1038 (limited precision)
double 8 ≈ ±10308 (limited precision)

java_data_types

java_numeric_data_types

Variables

<type> <variable name> = <initial value>;
byte -> short -> int -> long -> float -> double
char -> int
int x = 2.99; // invalid assignment
int y = (int)2.99; // valid assignment; x will be 2

Variable classes

  1. instance
  2. static (or class)
  3. local: define in a Java method

Constants

final int MAX_LENGTH = 420;

Operators

Arithmetic

Operator Meaning
+ addition, unary plus
- subtraction, unary minus
* multiplication
/ division
% modulo division

Relational

Operator Meaning
< Is less than
<= Is less than or equal to
>  
>= Is greater than or equal to
== Is equal to
!= Is not equal to

Floating point comparisons

Operator Meaning
&& AND
|| OR
! NOT

Bitwise

operator Meaning
& bitwise AND
! bitwise OR
^ bitwise exclusive OR
~ one’s compliment
<< shift Left
>> shift Right
>>> shift Right with zero fill

Other operators

Mathematical functions

Math.PI; Math.sin(15); Math.toDegrees(Math.PI/2.0); Math.pow(5, 2);


## Control flow

### Branching

- `if-else`:

  ```java
  if (boolean_expression) {
    // statements
  } else if (boolean_expression_2) {
    // statements
  } else {
    // otherwise statements
  }

Loops

Operator Precedence

Symbol Definition
. (dot) Method invocation, member access
++ -- Increment and decrement
- ! Unary negation
(type) Type casting
* / % Multiplicative
+ - Additive
< > <= >= Relational
== != Equality
&& Boolean and
|| Boolean or
= += *= Assignment

Wrapper classes

primitive wrapper Class
boolean Boolean
byte Byte
char Character
int Integer
float Float
double Double
long Long
` short ` Short

Example: Integer wrapper class

Integer.reverse(10);    // reverses bit sequence of a number
// -> 1342177280
Integer.rotateLeft(10, 2); // shifts bit sequence
// -> 40
Integer.signum(-10);    // indicates sign of number
// -> -1
Integer.parseInt("10"); // parses string as integer
// -> 10

String parsing

Every wrapper class has a parseXXX method that converts a string into that type

int i = Integer.parseInt("10"); // -> 10
double d = Double.parseDouble("10"); // -> 10.0
boolean b = Boolean.parseBoolean("TrUe"); // -> true

Boxing and Unboxing

boxing_unboxing

String Comparison

Use string1.equals(string2)

IO

Input

import java.util.Scanner;

public class Program {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // read next line of input: NB this is the only one to eat newline characters
        String inputLine = scanner.nextLine(); 
        // read next word of input
        String input = scanner.next();
        // read next int
        int i = scanner.nextInt();
        // read next double
        double d = scanner.nextDouble()
        // read next bool
        boolean b = scanner.nextBoolean() 
        
    }

Use scanner.hasNextXXX() to determine if there is input of type XXX ready to be read

Output

System.out.print(...) // outputs without newline character
System.out.format(...) // format and print to terminal
String.format(...) // returns formatted string

String Formatting

String.format("%3.2f", 4.56789); // min width 3, 2 decimal points, float
// output: 4.57

String.format("%+05d", 10);  // always include a sign, pad with zeroes, min width 5, integer
// output: +0010

String.format("%2$d %<05d %1$d %3$10s", 10, 22, "Hello");
// %2$d: 2nd arg, integer 
// %<05d: use previous arg (2nd arg), pad with zeroes, min width 5, integer
// %1$d: use 1st arg, integer
// %3$10s: use 3rd arg, min width 10, string
// output: 22 00022 10 Hello

Edit this page.