Java Basics

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development
Adriana Picoral

Closing remarks on Python

Python supports multiple styles of programming as well as language unique features Object oriented programming

  • Higher-order programming
  • Decorators
  • Generators
  • Comprehension syntax

An expert can write TRULY UNREADABLE code that is VERY SHORT and POWERFUL. You can build that expertise up from the core syntax you have.

Java

  • Descendant of C++, a lot of syntax and data type overlap/reuse
  • Compiled and Interpreted mix
    • advanced error-checking from compiled
    • run-everywhere from interpreted
  • The de-facto object-oriented programming language.
  • Built for large-scale programming
    • Makes it a bit wordy
    • Has lots of “engineering” features which might be counter-intuitive

Python vs. Java

Python:

  • Wants to get out of your way and let you work
  • Do more with less
  • Never talk about types
  • Intentional effort needs to be put on to prevent bugs
  • You can build big if you want

Python vs. Java

Java:

  • Wants you to build REALLY BIG things
  • Cares deeply about types
  • Will fight you over some bugs python will ignore
  • Large scale organization is the default

Java

Java – Hello World!

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Difference between System.out.println() and System.out.print()

Java – method signature

The main method looks like this:

public static void main(String[] args) {

    }
  • public is an access modifier (private is another option)
  • static – the method belongs to the class itself rather than to an instance of that class
  • void is what the method returns (nothing)
  • String[] args is the parameter, an array of String

Typing

  • Python does dynamic typing
word = "car"
number = 3
new_list = []
names = ["Pedro", "Melissa", "Jessica"]
  • Static typing in Java
String word = "car";
int number = 3;
int[] numbers = new int[10];
String[] names = new String[]{"Pedro", "Melissa", "Jessica"};

Try it out

Modify your main method in your HelloWorld class to assign the string literal "Hello World!" to a String variable name, and then print out that variable instead.

Questions:

  • Can you use both double and single strings to create the variable?

  • Does concatenation with the + operator work?

  • Can we concatenate (glue together) String, char and int (or a combination of these)?

Java variables

Declare any time before use, and strongly-typed

public class Hello {
    public static void main(String[] args) {
        String word = "Hello World!";
        System.out.println(word);
    }
}

Java variables

  • Declare any time before use
  • Strongly-typed
  • If you don’t assign a value it’s probably a bug
    • in some context a type-specific default is used
  • Two “flavors” of variable: primitive and object

Java primitive types

  • boolean
  • char (unicode) – single quotes
  • int
    • short and byte for smaller ints
    • long for longer ints
  • double
    • float for shorter floats

Primitive type names are lower-case

Java primitive types

These act like c++ variables

  • variable literally and directly stores value

Mathematical Operations

All operators as you would expect:

  • mathematical: + * - / %
    • No // in Java. Division type will be based on input types
    • int divided by an int is an int
    • Only works for number types
  • comparison: < > <= >=
    • numbers only

Mathematical Operations

  • equality: == !=
    • behave as expected for primitives
    • behave differently for objects
  • logical: && || !
    • back to the symbols (instead of words in Python)

Style and documentation

  • variable names often camelCase

  • Java requires a lot of code to express a simple concept.

  • You need to be much more explicit when writing Java than Python (more words to type in Java)

  • Comments are extra important

// one line comment

/*
  multi-line
  comment
 */
    
/**
 * JavaDoc comments for external documentation
 * @returns description of what returns   
 */

In-class exercise

Answer the in-class exercise on gradescope

Practice

Create a Java application that determines if an integer is odd or even

Solution

public class OddsOrEvens {

    public static void main(String[] args) {
        int number;
        number = 3;
        boolean result = number % 2 == 0;
        System.out.println(result);

    }

}

Practice

Submit a java class called OddEven to Gradescope that contains two public methods:

  • isOdd(int number) takes an integer as argument and returns a boolean
  • isEven(int number) takes an integer as argument and returns a boolean

Quiz 05

You have 10 minutes to complete the quiz

Enter one line number per response box.

Java methods

public class OddEven {

    public static boolean isOdd(int number) {
        boolean result = number % 2 == 1;
        return result;
    }
    
    public static boolean isEven(int number) {
        return number % 2 == 0;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int number = 3;
        if (isOdd(number)) {
            System.out.println("Number is odd");
        }
        
        if (isEven(number)) {
            System.out.println("Number is even");
        } else {
            System.out.println("Number is not even");
        }

    }

}

Java arrays

Syntax:

int[] numbers = new int[10];
int[] moreNumbers = new int[]{0, 5, 0, 2};
numbers[1] // get second item in array
numbers.length // attribute -- note the lack of parenthesis

Java loops

public static void main(String[] args) {
        int[] numbers = new int[10];

        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = i * 2;
        }

        for (int n : numbers) {
            System.out.print(n + " ");
        }
        
        int counter = 0;
        while (counter < numbers.length) {
            System.out.print(numbers[counter] + " ");
            counter++;
        }
    }

In-class exercise

Submit a java class called Average to Gradescope that contains one public method:

  • average(int[] numbers) takes an array of integers as argument and returns a double representing the average of all values in the array (sum values, divide by total number of values)

Solution

public class Average {

    public static double average(int[] numbers) {
        double result = 0;
        for (int n : numbers) {
            result += n;
        }
        return result/numbers.length;
    }
    
}