Welcome to Java

Major Java components

The Java development kit (JDK) contains the minimum software you need to do Java development. It includes

  • the virtual machine JVM to execute your programs.
  • the compiler javac compiles .java files into .class. It converts instructions into bytecode.
  • the launcher java creates the VM and executes the program. Runs this bytecode on the actual machine.
  • the archiver jar command can package files together
  • the api documentation javadoc for generating documentation
  • jlink creates a executable that contains the required pieces that would have been in the JRE

Where did the JRE go?

From Java11 on, the JRE is no longer available. People use the full JDK when running a program.

The JRE was used for running a program but could not compile one. It was a subset of the JDK.

Java Benefits

Object Oriented Java is object-oriented. All code is defined in classes and most of those classes can be instantiated into objects. Java allows for functional programming within a class, but the main organization of code is still object-oriented.

Encapsulation Java supports access modifiers to protect data from unintended access and modification. Encapsulation is an aspect of object-oriented programming languages.

Platform independent Java is an interpreted language that gets compiled into bytecode. A key benefit is that Java only needs to be compiled once rather than needing to be recompiled for different OS. The same class files runs everywhere (except for some exceptions or os-specific directories).

Robust Java manages memory leaks on its own and does garbage collection automatically .

Simple It’s simpler than C++ by eliminating pointers.

Secure Java code runs inside the JVM. This creates a sandbox that makes it hard Java code to do evil things inside a computer.

Multithreaded Java is designed to allow multiple pieces of code to run at the same time.

Backward Compatibility Old programs will work with later versions of Java.

Unterstanding the Java Class Structure

  • Classes are the basic building blocks. When defining a class, you describe all the parts and charasteristics of one of those building blocks.
  • To use most classes you have to create objects. An object is a runtime instance of a class in memory.
  • An instance is a single representation of a class.
  • A reference is a variable that points to an object.

Fields and Methods

The members of a class are fields (variables) and methods (functions).

This is the simplest Java class

public class MyClass {
}

Method signature it’s formed by the method name and parameters. Method declaration it’s the return type.

Classes vs Files

Usually, classes are public but they don’t have to. Each class it’s defined in its own .class usually.

You may have more than one class in a single file but you can only have 1 public class per file.
Also, if you’ve a public class, it’s name needs to match the filename.

Compiles

File ClassOne.java

public class ClassOne {
}

class ClassTwo {
}

File ClassOne.java

class ClassOne {
}

class ClassTwo {
}

Doesn’t compile

File ClassOne.java

// class name != file name
public class AnotherClassName {
}

File ClassOne.java

// two public classes
public class ClassOne {
}

public class ClassTwo {
}

Writting a main() method

A main() method is the gateway between the start of a java process, managed by the JVM, and our code.

To compile code, the file must have the .java extension. We must omit the .class to run as file.

Any of the following is a valid array declaration:

String[] args
String args[]
String args    []
String... args
String...args

Passing Parameters to a Java Program

Arguments are separated by spaces.

We have a program to print the first 2 arguments, with the following arguments it will print:

Input: San Diego Zoo
Output:
San
Diego

Input: "San Diego" Zoo
Output
"San Diego"
Zoo

Running a Program in One Line

Starting in Java11 you can run a program “without compiling” it (the code is compiled in-memory) but even if it compiles, it doesn’t create a .class file.

When compiling a file, you compile it and give the java command and the class name to run it.
When interpreting it, you just give the filename with extension included.

For the following class

public class Zoo {
}
// compile & run
javac Zoo.java
java Zoo

// interpret
java Zoo.java

Limits:

  • this is only for programs that have a single file and 1 class.
  • you can only refer to any .class that comes with the JDK (java or javax packages).
  • it has to compile. If there’s a compilation error it won’t work.
  • programs will run slower, as compiling is faster

imports & wildcards

import java.util.*;

The char * is a wildcard that matches all classes in a package. It doesn’t import child packages, fields or methods; it imports only classes.

Importing so many classes doesn’t slow the program down. The compiler figures out what’s really needed.

We need to know Files and Paths classes are at the package java.nio.*

Redundant import

There’s a special package that’s always imported. This is

import java.lang.*;

This is the reason we’re able to use System without any import.

Another example of redundant imports would be to import a class that’s in the same package level. Java already looks in the same package for classes.

Naming Conflicts

One of the reason to use packages is classes don’t need to be uniquely named.

import java.util.Date;
import java.sql.Date;

Java throws an error for ambiguous reference for the previous imports, but an explicit import will have preference over a wildcard.

import java.util.Date; // this will take preference
import java.sql.*;

if you need to reference 2 classes with the same name, just specify the package when using it.

 import java.util.Date;
 public class Conflict {
 	Date date;
	java.sql.Date sqlDate;
 }

Compiling with wildcards

You can use an asterisk to compile all Java files in a folder.

 javac packagea/*.java packageb/*.java

This won’t include subdirectories.

Using an alternative Directory

By default javac compiles the files at the same directory as the source code. To place them at other folder is done with -d option

 javac -d classes packagea/ClassA.java
 // this will place the files at classes/packagea/ClassA.class

To run this program, we’d need to specify the classpath so that Java knows where to find the classes.

 java -cp classes packageb.ClassB
 // or -classpath
 // or --class-path

java & javac modifiers

javac    
  -cp classpath location of classes needed to compile
  -classpath classpath  
  –class-path classpath  
  -d dir directory to place generated class files
java    
  -cp classpath location of classes needed to run the program
  -classpath classpath  
  –class-path classpath  

Compiling with JAR Files

You can specify the location of other files explicitly using a classpath. This is useful when the classes are located in another JAR. A Java Archive (JAR) is like a zip file.

java -cp ".;C:\temp\myJar.jar" myPackage.class

// like compiling, you can use a wildcard * to include all JARs.
// (!) this WONT include subdirectories!!!
java -cp ".;C:\temp\*.jar" myPackage.class

the . indicates that we want to include the current directory. The rest of the command specifies where to look for the other classes. Windows uses ; to separate parts of the classpath.

Creating JAR Files

You can use the jar command to do so yourself.

// short version
java -cvf myNewJar.jar .

// long version
java --create --verbose --file myNewJar.jar .

// specify another directory
jar -cvf myNewJar.jar -C dir .

jar command modifiers

command modifier description
jar    
  -c creates a new JAR
  –create  
  -v prints details when working with JARs
  –verbose  
  -f {filename} JAR filename
  –file {filename}  
  -C {directory} directory containing the files to be used to create the JAR

Running a program in one line w. packages

You can run standalone files from within a package as long as they rely on classes supplied by the JDK.

This program does an import but still works as an interpreted program.

package singleFile;
import java.util.*;

public class Learning {
	private ArrayList list;
	public static void main(String[] args) {
		System.out.println("This works!");
	}
}

To interpret it we just use

java Learning.java

Ordering elements in a class

  1. Package declaration
  2. Imports
  3. Class
  4. Fields
  5. Methods

Think PIC (package, imports, class)

This is a correct class

package structure;
import java.util.*;

public class Meerkat { }

This won’t compile

import java.util.*;
package structure; // THIS WON'T COMPILE

public class Meerkat { }

Remember

Multiple classes can be defined in the same file, but only one is allowed to be public. The public class matches the name of the file.

Class Meerkat.java

// this compiles
public class Meerkat { }
class Paw { }

A file is also allowed to have 0 public classes.

Code formatting

Don’t worry about missing packages or imports unless you’re asked about them, or the code has line numbers which start by 1. Example:

Does this compile?

6: public void getLetter(ArrayList list) {
7: 		if (list.isEmpty()) { System.out.println("e");
8: 		} else { System.out.println("n");
9: } }

Yes. It does.

Does this compile?

1: public class LineNumbers {
2: 	public void getLetter(ArrayList list) {
3: 		if (list.isEmpty()) {
4:                  System.out.println("e");
5: 		} else { System.out.println("n");
6: } } }

No. It doesn’t since the code starts with the line #1. You don’t get to assume that valid imports were provided earlier.

Summary

The JDK contains the compiler javac which turns code into bytecode. It also contains the launcher java, which launches the JVM and the calls the code.

APIs are available to call reusable pieces of code.

Java is object-oriented, meaning all code is defined in classes. Access modifiers allow classes to encapsulate data.

Java is platform-independent, compiling into bytecode and is secure because it runs inside a virtual machine. It also facilitates multithreaded programming and strives for backward compatibility.

Java classes consist of members called fields and methods. An object is an instance of a java class.

A wildcard ending an import statement means you want to import all classes in that package. It does not include packages that are inside that one.
The package java.lang is special in that it doesn’t need to be imported. It’s always imported by default.

The package statement, if present, always comes before the imports (PIC).

Exam essentials

Identify benefits of Java. Benefits of Java include object-oriented design, encapsulation, platform independence, robustness, simplicity, security, multithreading, and backwards compatibility.

Define common acronyms. The JDK stands for Java Development Kit and contains the compiler and JVM launcher. The JVM stands for Java Virtual Machine, and it runs byte-code. API is an application programming interface, which is code that you can call.

Be able to write code using a main() method. A main() method is usually written as public static void main(String[] args). Arguments are referenced starting with args[0]. Accessing an argument that wasn’t passed in will cause the code to throw an exception.

Understand the effect of using packages and imports. Packages contain Java classes. Classes can be imported by class name or wildcard. Wildcards do not look at subdirectories. In the event of a conflict, class name imports take precedence.

Be able to recognize misplaced statements in a class. Package and import statements are optional. If present, both go before the class declaration in that order. Fields and methods are also optional and are allowed in any order within the class declaration.