24
Introduction to Java Programming Language features Running sample code Tools support 1

Introduction to Java Programmingcs349/w20/slides/05.java.pdf · Swing. java.io File,FileReader, FileWriter, InputStream Provides for system input and output through data streams,

  • Upload
    others

  • View
    23

  • Download
    0

Embed Size (px)

Citation preview

Introduction to Java Programming

Language features

Running sample code

Tools support

1

Origin

2

§ Java was developed by Sun in the 1990s, as an alternative to C++.

§ Designed to be multi-platform- Compiles to bytecode (IR) that runs on a Java Virtual Machine.- Binary compatibility across platforms (i.e. you can deploy the compiled code

to multiple targets and it will run).

§ Object-oriented language.

§ Strongly-typed, static compilation (to bytecode).

§ Strong library support for different application styles and paradigms.

§ Open source under GNU GPL in 2007

§ Sun and Java acquired by Oracle in 2010

§ Why? - Supports Win/Mac/Linux desktop + Android

Java Tools Installation

3

Java JDK https://adoptopenjdk.net

IntelliJ Community https://www.jetbrains.com/idea/download

You will need to install the Java SDK 11 and IntelliJ 2019.3 Community.

Java Documentation

4

https://docs.oracle.com/en/java/javase

Virtualization

5

§ Java source files (.java extension)- compile to bytecode (.class files)- Java Virtual Machine (JVM) runs it - Supports Just-in-Time (JIT) compilation

for near-native performance.

§ JVM can execute code from any language that compiles to JVM bytecode (e.g. Java, Scala, Kotlin)

§ Java runs everywhere by having a JVM for each target platform (Mac, Linux, Windows, Raspberry Pi, Arduino, car OS, toasters…)

http://viralpatel.net/blogs/java-virtual-machine-an-inside-story/

Compiling Java Applications

6

Compile java source files using `javac’

§ You will often have multiple class files (typically one per .java file)

§ You can compile all at once e.g. `javac *.java’

To run an application

§ Use the `java' command with the name of the class file containing the `main()’ method:

// compile// execute

Java files contain classes. • Each file must contain a class with the same name as the file.• One class should typically have a main() method

Using Libraries

7

Classes are grouped into ”packages” (collection of classes)

§ package keyword to assign source to a package- a package is a subdirectory- It’s also the name of the namespace for a class file

The package for these Java source files will be codebot.nete.g. codebot.net.Main

Use import at the top of a source file to import a class from a different package.

There are 3 classes here: Main, SomeClass1,

SomeClass2

Java vs. C++?

8

§ Java “feels” like C++ in some ways…- C++ syntax w/ semi-colons- Classes and “standard” OO features- Static typing: compiler checks your program when its compiled

§ But Java isn’t C++- No headers! Single file declaration and definition.- No pointers! Reference or value types, but no raw addresses. - No operator overloading. Use methods like equals() or plus()- No support for multiple inheritance. Use interfaces instead.- Garbage collection! No need (or support) for destructors.

Hello World!

9

class definition

static main

constructor

Things that stand out• Top-level class definition (remember that Filename matches Class name)• Static main method is scoped within the class• No-argument constructor

Compiling and running it> javac Hello.java> java Hello

compiles to Hello.class

executes Hello.class

Hello.java

Command-Line Parameters

10

§ Command-line arguments are passed to the main() method as an array of Strings.- The shell will automatically expand wildcards, so that each filename

comes in as a string.- See public/code/04.java/CommandLine

11

constructor

methods

main

fields

classBicycle.java

Useful Packages and Packages

12

Package Classes (Examples) Description

java.awt Color, Graphics, Font,Graphics2D, event.

Base classes for creating user interfaces and for painting graphics and images.

javax.swing JFrame, JButton, JList, JToolbar

”Lightweight" components that works the same on all platforms.

javafx.* Scene, Stage, Button, ”Lightweight” components that work across all platforms. More “modern” than Swing.

java.io File, FileReader, FileWriter, InputStream

Provides for system input and output through data streams, serialization and the file system.

java.lang Boolean, Integer, String, System, Thread, Math

Provides classes that are fundamental to the design of the Java programming language.

java.util ArrayList, HashMap, Observable

Contains the collections framework, legacy collection classes, event model,…

No Pointers!

13

Parameters are passed by value. However, this isn’t always obvious.

§ Primitive types (int, float, etc.) are allocated on the stack and always passed by value.

§ Objects are allocated on the heap, and the address is passed-by-value- Java uses pass-by-reference semantics, so it appears as-if you’re passing

by reference.- Practically, you can treat Java as passing objects by reference.

§ There are no pointer semantics in Java- i.e. no *, no &, no out, no ref

both refer to same memory on the

heap

Inheritance

14

§ Inherit some methods or fields from a base class (“is a”)

§ Very common in Java to extend and override other classes

§ Example:- “Mountain Bike” is-a “Bike”- Mountain bike inherits speed and gear fields- Mountain bike defines addition field for suspension type

Bike

Mountain Bike

15

inner derived class

” Meow! ““ Woof! “

abstract inner base class

top-level class Animals1.java

No Multiple-Inheritance

16

§ Java only supports single (class) inheritance

§ However, to specify complex class behavior, you can use interfaces

§ An interface represents an API (i.e. it defines functionality)- It represents a set of methods a class must have - You can’t instantiate an interface- Essentially, it’s a pure abstract class

§ Classes can choose to implement an interface- A class that implements an interface must implement *all* of the

methods in the interface- A class can implement multiple interfaces, representing different

behaviours that the class wants to support (e.g. you might have interfaces indicating that something printable and loggable).

17

The interface Pet is like a type

interface

implementations

Animals2.java

Managing Errors

18

§ You can use things like error codes and check return values in your own code, but system libraries and classes use exception handling.

§ You need to “wrap” library calls in try… catch() blocks like this:

A1 Classes

19

§ Java has extensive libraries that cover any functionality you will need.

§ Useful classes for A1:

- java.lang.String. concat (String str). startsWith (String prefix) . replaceAll (String regex, String replacement). equals (String) // do NOT use == since that compares objects

- java.io.File. renameTo(File dest). isDirectory(). exists()

Packaging Java Applications

21

How do you deploy a more complex Java application?

§ 1. Give out all of the .class files (could be hundreds of them!)- i.e. email, flash drive etc.

§ 2. Use `jar’ utility to package the .class files into a single file- Basically a ZIP file with some metadata. e.g. Main.jar- User can execute from the JAR file directly.

e.g. java –jar Main.jar

§ 3. Use a third-party utility to build a standalone EXE file (e.g. Launch4j)

For this course, we’re not going to package our apps.

Coding w. an IDE

23

§ We’re using IntelliJ 2019.3 in this course. This is an Integrated Development Environment (IDE) that provides:- Better code navigation- Code completion - Debugging- Profiling- Integration with API docs- Integration with testing framework- Simplified build framework

§ For your assignments, you are required to submit source code AND an IntelliJ project that compiles and builds your code.- This is critical when we start building more complex applications (esp. in

Android).

Yes, you can do some of this in vim... but there

are IDE exclusive features we be

using!

How to Start A1?

24

Getting Started

§ Copy A0 into A1 (or create a new project in a1/ directory)

§ Open your project in IntelliJ, and make sure it builds!

§ Make sure that you have a single Java file: rename.java (yes lowercase).- i.e. class is named rename

Structure

1. Read command-line arguments- Check that options are valid, sufficient parameters

2. Create replacement filenames that using rules- Check that rules result in legal replacement strings

3. Rename the files in order, using the new filenames- Catch errors related to the filesystem!

Jeff’s Development Environment

25

§ AdoptJava: Open Source version, using binary distribution.

§ JavaFX: We will use this for A2+. It needs to be installed separately.

§ Visual Studio Code: for quick samples (e.g. single-file programs).

§ IntelliJ Community: commercial IDE, supports multiple languages and plugins.

§ Dash: docs browser (with an Alfred plugin) for Mac.- Zeal: comparable docs browser for Windows, Linux. - devdocs.io is an online alternative.

§ Fork: Git client for Mac, Windows (although I mostly use command-line).

26

education.github.com/pack

www.jetbrains.com/student/

Free stuff!