11/30/2020
Introduction to Java
Brandon Krakowsky
Introduction to Java
Property of Penn Engineering | 2
First … Can We Forget About Python?
• In terms of syntax, mostly …
• But you SHOULD NOT forget about:
‐ Code reuse
‐ Modular programming
‐ Test‐Driven Development
‐ Good Style (Java is stricter in many ways)
‐ Commenting your code
‐ Etc.
Property of Penn Engineering |
3
11/30/2020
Java vs. Python
• Java and Python are similar in that they’re both object‐oriented languages
‐ Conceptually, the languages are very similar
‐ The syntax is quite different, while Java syntax is much more verbose
• It is both explicit (and strict), which can be a good thing
‐ Transitioning from Python to Java has a lot to do with learning the new syntax
• Java and Python are different in that Java is compiled and Python is interpreted
‐ This allows Java to run much faster and more efficiently
‐ It also allows your Java code to be inspected for all kinds of errors, including syntax errors,
type errors, and non‐existing functions
Property of Penn Engineering |
Java is Compiled
• When Java is compiled, it’s converted to binary machine code (or Java bytecode)
‐ This allows Java programs to be “portable” and run on different machines and operating
systems
• Compiled languages have many advantages over interpreted languages
‐ When code is compiled, it’s optimized under the hood
‐ Since your program will be inspected for errors, many kinds of potential bugs will be caught
early (e.g. using the same variable name twice)
• Your program will not run if it is not compiled!
• The IDE we’ll be using for Java development, Eclipse, will compile your code for you (on the fly)
as you save your work
‐ It will also help you fix MANY problems in your code
Property of Penn Engineering |
Popularity of Java vs. Python Using TIOBE
• The TIOBE Programming Community index is an indicator of the popularity of programming
languages
• It can be used to:
‐ Check whether your programming skills are up to date
‐ Make a decision about what programming language(s) to use when starting new projects
• The ratings are:
‐ Based on the number of skilled engineers world‐wide, courses and third party vendors
‐ Calculated based on popular search engines
• The index is updated once a month
Ref: https://www.tiobe.com/tiobe‐index/
Property of Penn Engineering |
6
11/30/2020
Popularity of Java vs. Python Using TIOBE
• Top 10 of the TIOBE index for October 2020
• General highlights:
‐ Java and Python are in the top 3 most popular programming languages
‐ Currently, both languages have almost the same rating
Ref: https://www.tiobe.com/tiobe‐index/
Property of Penn Engineering |
Configuring Java & Tools
Property of Penn Engineering | 8
Installing & Running Java
• In order to use Java, you need to first install the Java Development Kit (JDK)
‐ This is the package of tools for developing Java‐based software
• You’ll also need the Java Runtime Environment (JRE) which includes the Java Virtual Machine
(JVM)
‐ This is the environment for running Java applications
• The JVM is what actually runs compiled Java bytecode
• Download and install the JDK, which includes the JRE (and JVM):
https://www.oracle.com/java/technologies/javase‐downloads.html
Property of Penn Engineering |
9
11/30/2020
Downloading and Installing the JDK
• Download and install the JDK, which includes the JRE (and JVM):
https://www.oracle.com/java/technologies/javase‐downloads.html
‐ Locate the main link for the JDK
Property of Penn Engineering |
10
Downloading and Installing the JDK
• Download and install the JDK, which includes the JRE (and JVM):
https://www.oracle.com/java/technologies/javase‐downloads.html
‐ Download the latest version of the JDK for your OS
Property of Penn Engineering |
11
Eclipse
• Eclipse is one of two main IDEs for Java development
‐ The other IDE is IntelliJ
‐ I’ll work with Eclipse
• Eclipse makes it very easy to write well‐formatted Java, with good style
‐ Like Python’s PyCharm, it has a TON of features
‐ It compiles code on the fly, provides autocomplete suggestions, and fixes simple bugs
‐ Overall, Eclipse greatly speeds up Java programming
• Getting Eclipse:
‐ Go to https://www.eclipse.org/downloads/ and download the latest version
Property of Penn Engineering |
12
11/30/2020
Installing & Configuring Eclipse
• Install Eclipse via https://www.eclipse.org/downloads/
‐ Scroll down to get the latest version of Eclipse
Property of Penn Engineering |
13
Installing & Configuring Eclipse
• Install Eclipse via https://www.eclipse.org/downloads/
‐ Click to download the latest version of the IDE for your OS
Property of Penn Engineering |
14
Installing & Configuring Eclipse
• When you extract and run the Eclipse Installer
‐ Choose Eclipse IDE for Java Developers
Property of Penn Engineering |
15
11/30/2020
Installing & Configuring Eclipse
• When you launch Eclipse, you need to specify a workspace location
‐ You can use the default option (unless you have a really strong need to change it)
‐ Click “Launch”
Property of Penn Engineering |
16
Java & Eclipse
• Eclipse stores projects in a workspace
• When you use Eclipse to create a project (a single “program”), it creates a directory with that
name in your workspace
• Within the project, you create an optional package (a sub‐directory)
• Finally, within the package, you create a class (a file)
• For the simplest program, you’ll only need a single package (or the default “no” package), and
only one (or a very few) classes
‐ Java is object‐oriented and class‐based, which means you have to create at least one class to
write a Java program
Property of Penn Engineering |
17
Java Language
Property of Penn Engineering | 18
18
11/30/2020
Simple Introductory Java Program
//Optional package declaration
package myPackage; //Should begin with a lowercase letter
//Class declaration
public class MyClass { //Should begin with a capital letter
//The Java file will be named (and saved in) ‘myPackage/MyClass.java’
//Main method ‐‐ the starting point of any Java program
//In Java, the name “main” is special and reserved for the main
method
public static void main(String[ ] args) {
System.out.println(“Hello World”); //Prints ‘Hello World’
}
}
Property of Penn Engineering |
19
Some General Rules for Java
• Individual statements end in a semicolon
‐ New lines do not mean anything in Java
‐ This means you COULD have an entire program on one line
• Obviously, this is bad style!
• For example, here’s a statement
System.out.println(“Hello World!”);
• Here’s another statement
String myString = “My String”;
Property of Penn Engineering |
20
Some General Rules for Java
• Indentation doesn’t matter
‐ Unlike Python, where it’s required, indentation in Java is a matter of style
‐ While it won’t make your program fail the way it does in Python, you should not stop
indenting your programs!
• You can use these shortcuts in Eclipse
‐ Fixes format of your code
CTRL/Cmd + SHIFT + F
‐ Selects all code in Java file and fixes indentation
CTRL/Cmd + A, CTRL/Cmd + I
Property of Penn Engineering |
21
11/30/2020
Some General Rules for Java
• Java uses curly braces { } to surround code blocks
‐ Unlike Python, which uses a colon (:) and indentation to indicate code blocks
• For example, here’s a conditional
if (myVar == true) {
//code block
}
• And here’s a function
public void myFunction() {
//code block
}
• For purposes of style, an opening brace { should go at the end of a line, not on a line by itself
Property of Penn Engineering |
22
Variables & Types
• You typically name variables using “camelCase”, starting with a lowercase letter
• Every variable in Java has a pre‐defined type
‐ You declare the type in front of the variable
int myInt = 0; //myInt can only store an int
• You MUST store that kind of data in the variable
‐ For example, you can’t do this:
int myInt = “hello”;
‐ Eclipse won’t even let you compile your code!
• The type of a variable CANNOT be changed
‐ Java is statically typed
‐ In Python, you can change variable types on the fly, because it’s dynamically typed
Property of Penn Engineering |
23
Variables & Types
• Some primitive (simple) data types
‐ int: Integer
‐ float: Floating point (decimal)
‐ boolean: true/false
• Some other primitive types
‐ char: Single character
‐ double: Large and precise floating point
‐ byte, short, or long: Various integer sizes (8, 16, 64 bits)
• Another type is String, which is an Object (not a primitive)
‐ It’s used to store a character string
• You might also come across Integer, Boolean, Double, etc.
‐ Don’t worry about these for now!
Property of Penn Engineering |
24
11/30/2020
Variables & Types
• You can declare variables WITH initial values
int count = 0;
String firstName = “Brandon”;
• Or declare variables WITHOUT initial values
double distance; //Declares a double without actually creating a double
String color; //Declares a String without actually creating a String
• And obviously set the variables later
distance = 2.3;
color = “red”;
Property of Penn Engineering |
25
Variables & Types ‐ Strings vs. Chars
• There is a difference between a single character and a character string
‐ Unlike Python, be careful about when you are using double quotes vs. single quotes
• To define a String, use double quotes
String firstName = “Brandon”; //”Brandon” is a String
• To define a char, use single quotes
char letter = ‘a’; //‘a’ is a char
• Like in Python, you can concatenate Strings using +
String fullName = “Brandon” + “ ” + “Krakowsky”;
• Tip: Anything concatenated with a String is automatically converted to a String
• For example:
String myResult = "There are " + appleCount + " apples and " +
orangeCount + " oranges.”;
‐ Note the difference with Python, where you have to call the str method to cast to a String
Property of Penn Engineering |
26
Printing
• There are two methods you can use for printing:
//This prints something and ends the line
System.out.println(something);
//This prints something and doesn’t end the line (so the next thing you
print will go on the same line)
System.out.print(something);
• These methods will print any one thing, but only one at a time
• Of course, you can always concatenate Strings with the + operator
• Example:
System.out.println("Four " + 4 + ", three " + 3 + ", two " + 2 + ", one
" + 1);
Property of Penn Engineering |
27
11/30/2020
while Loops
• while loops in Java have a similar syntax to while loops in Python
• Simple while loop that iterates 10 times:
int i = 0;
while (i < 10) {
//do stuff here every time loop happens
i++; //manually increment i
}
//i is initially set to 0
//i must be less than 10 in order to enter the loop each time
//code in the loop manually increments i by 1 at the end of each loop
Property of Penn Engineering |
28
for Loops
• for loops in Java have a very different syntax than for loops in Python
‐ But they are equivalent to: for i in range(10)
• A for loop has 3 parts:
‐ Setting the initial value
‐ The condition for entering the loop
‐ The change in the loop variable that happens at the end of each loop
• Simple for loop that iterates 10 times:
for (int i = 0; i < 10; i++) {
//do stuff here every time loop happens
}
//i is initially set to 0
//i must be less than 10 in order to enter the loop each time
//i is incremented by 1 at the end of each loop (you can’t see it)
Property of Penn Engineering |
29
Getting Input
• First, import the Scanner class:
import java.util.Scanner;
• Create a scanner and assign it to a variable:
Scanner scan = new Scanner(System.in);
‐ The name of the scanner is scan
‐ new Scanner(...) tells Java to make a new one
‐ System.in tells Java that the scanner is to take input from the keyboard
• To read in the next int:
int myNumber = scan.nextInt();
• To read in the next String:
String myString = scan.next();
• To read in the entire next line as a String:
String myLine = scan.nextLine();
Property of Penn Engineering |
30
11/30/2020
Java Comments
• Here is a single line comment, using double slashes //
//Here is an int, initially set to 0
int myInt = 0;
• Here is a block comment, using /* */
/*
* Here is an int
* It’s initially set to 0
*/
int myInt = 0;
• As a shortcut in Eclipse, you can type the following
/*
and then hit Enter
• It will add a block comment and you can fill in the rest
Property of Penn Engineering |
31
Javadocs
• You can add Javadocs (Java documentation) just before the definition of a variable, method, or class
‐ This is the equivalent of a docstring inside of a Python function or class
• As a shortcut, you can type the following right above a variable, method, or class name
/**
and then hit Enter
• It will add a javadoc block and you can fill in the rest
/**
* Returns the sum of two given numbers.
* @param firstNum First value to add
* @param secondNum Second value to add
* @return Sum of values
*/
public int getSum(int firstNum, int secondNum) {
return firstNum + secondNum;
}
Property of Penn Engineering |
32
My First Java Project
Property of Penn Engineering | 33
33
11/30/2020
My First Java Project
• In Eclipse, go to “File” “New” “Java Project”
Property of Penn Engineering |
34
My First Java Project
• Create a Java Project in your workspace
• Provide a Project name
‐ Project names should be capitalized
‐ Use the default location
Use the default JRE and project layout
• Click “Next”
Property of Penn Engineering |
35
My First Java Project
• Define the compilation/build settings
• Make sure Create module‐info.java file
IS NOT checked
• Use the default output folder
• Click “Finish”
Property of Penn Engineering |
36
11/30/2020
My First Java Project
• The project will appear in the Package Explorer on the left hand side in the IDE
Property of Penn Engineering |
37
My First Java Project
• In Eclipse, go to “File” “New” “Class”
Property of Penn Engineering |
38
My First Java Project
• Create a Java Class in your Java Project
• Provide a Name
‐ Class names should be capitalized
• Make sure public static void main(String[ ] args)
IS checked
• Make sure Inherited abstract methods
IS NOT checked
• Click “Finish”
Property of Penn Engineering |
39
11/30/2020
My First Java Project
• The entry point of any java program is the main method
Property of Penn Engineering |
40
My First Java Project
Property of Penn Engineering |
41
My First Java Project
• To run your Java program in Eclipse, go to Run Run
‐ Or click the “Run” button
• Keyboard shortcuts will vary based on your install of Eclipse and operating system
‐ On a Mac, you should use CMD + (Fn) F11
Property of Penn Engineering | 42
42
11/30/2020
My First Java Project
Property of Penn Engineering |
43
My First Java Project
Property of Penn Engineering |
44
My First Java Project
Property of Penn Engineering |
45
11/30/2020
My First Java Project
Property of Penn Engineering |
46
My First Java Project
Property of Penn Engineering |
47
My First Java Project
Property of Penn Engineering |
48
11/30/2020
My First Java Project
Property of Penn Engineering |
49
My First Java Project
Property of Penn Engineering |
50
My First Java Project
• The Scanner class requires an import at the top of the class
Property of Penn Engineering |
51
11/30/2020
My First Java Project
• Add javadocs to class, method, and variable definitions
• We’ll eventually learn that javadocs are useful for easily creating documentation for an entire
program
‐ This can be extremely helpful for other programmers reading/running your code
Property of Penn Engineering |
52