Title Text
Title Text
Title Text
Introduction to programming
Intro to Java
Programming Languages
From machine code to almost human language, programming languages have come a long way.
According to their degree of abstraction, programming languages can be defined as:
- High-Level (closer to human language)
- Low-Level (closer to machine language)
High vs. Low-Level Programming languages
This language abstraction is useful to us, programmers, but the machine does not understand it. Before it can be executed, our code must undergo a translation process.
// ASSEMBLY
mov ax, num1
mov bx, num2
cmp ax, bx
jne L1
mov x, 1
jmp L2
L1: mov x, 2
L2:
// JavaScript
if(num1 === num2) {
x = 1;
} else {
x = 2
}
Languages like Pascal, C, Go, Rust, Swift, among others, are what we call compiled languages.
Code written in these languages must first be parsed by a piece of software called the compiler, and then converted into machine code.
Compiled languages
interpreted languages
Languages like Ruby, JavaScript, PHP, Perl, among others, are what we call interpreted languages.
Code written in these languages must be parsed and translated into machine code by a piece of software called the interpreter.
COMPILED vs. interpreted
↳ faster to run | ↳ more flexibility |
↳ errors caught earlier | ↳ platform independent |
COMPILED | INTERPRETED |
---|
Java
Java is a cross-platform, portable language.
This means that a Java program can be developed on any machine, compiled into standard bytecode, and then executed in any device that is equipped with a Java Virtual Machine (JVM).
Write Once, Run ANYwhere
The Java Platform
The Java programming language is the standard language used by the Java Platform. However, it is not its only language.
Other JVM compatible languages include:
- Clojure
- Scala
- Kotlin
- Groovy
JVM
LIVE CODING
HelloWorld.java
Java's syntax is largely influenced by C++ and C.
It's a statically typed language, and almost exclusively object oriented.
The Java Language
The java memory model
There are eight primitive types in Java.
Primitive Types
Primitive Types IN MEMORY
Every non-primitive type is known as a reference type.
There are reference types built in the language, like Strings, but programmers can create their own.
The default value of a reference type is null.
Values of a reference type are called objects.
Reference Types
OPERATORS
Assignment and arithmetic operators
// ASSIGNMENT
int firstNumber = 20;
int secondNumber = 5;
// ADDITION
int additionResult = firstNumber + secondNumber; // 25
// SUBTRACTION
int subtractionResult = firstNumber - secondNumber; // 15
// MULTIPLICATION
int multiplicationResult = firstNumber * secondNumber; // 100
// DIVISION
int divisionResult = firstNumber / secondNumber; // 4
// REMAINDER
int remainder = 20 % 5; // 0
Compound assignments
int result = 0;
// ADDITION
result += 5; // 5 || same as result = result + 5;
// SUBTRACTION
result -= 2; // 3
// MULTIPLICATION
result *= 10; // 30
// DIVISION
result /= 5; // 6
equality and relational operators
int johnsAge = 24;
int marysAge = 31;
int petersAge = 31;
// EQUAL TO
johnsAge == marysAge; // false
marysAge == petersAge; // true
// NOT EQUAL TO
johnsAge != marysAge; // true
marysAge != petersAge; // false
// GREATER THAN
johnsAge > marysAge; // false
marysAge > petersAge; // false
johnsAge >= marysAge; // false
marysAge >= petersAge; // true
// LESS THAN
johnsAge < marysAge; // true
marysAge < petersAge; // false
johnsAge <= marysAge; // true
marysAge <= petersAge; // true
UNARy operators
int result = 0;
// ADDITION
result++; // 1 || same as result = result + 1;
// SUBTRACTION
result--; // 0
// INVERSION
boolean isMorning = true;
System.out.println(!isMorning); // prints false
conditional operators
int mikesAge = 16;
boolean fakeId = false;
// CONDITIONAL-AND
if(mikesAge > 21 && !fakeId){
System.out.println("Mike can get into the club.");
}
// CONDITIONAL-OR
if(mikesAge > 21 || fakeId){
System.out.println("Mike can get into the club.");
}
TERNARY operator
int mikesAge = 16;
int basePrice = 20;
// TERNARY OPERATOR TO ASSIGN VALUE
int bribingPrice = mikesAge >= 21 ? basePrice : basePrice * 2;
// TERNARY OPERATOR TO PRINT SOMETHING
System.out.println(mikesAge >= 21 ? "Please, come in!" : "Go away!");
// A TINY EXERCISE:
System.out.println(mikesAge++ >= 17 ? "Please, come in!" : "Go away!"); // What will be printed?
TERNARY operator
int mikesAge = 16;
int basePrice = 20;
// TERNARY OPERATOR TO ASSIGN VALUE
int bribingPrice = mikesAge >= 21 ? basePrice : basePrice * 2;
// TERNARY OPERATOR TO PRINT SOMETHING
System.out.println(mikesAge >= 21 ? "Please, come in!" : "Go away!");
Strings
A String is a sequence of characters.
In Java, specifically, strings aren't primitives; they are treated as objects.
What is a string?
// The following are all strings in Java:
"To be, or not to be a String, that is the question."
"98423"
"false"
"a"
" "
""
There are two ways of creating a String in Java:
String Creation
// STRING LITERALS:
String message = "I came here to make one thing clear: I'm a literal legend.";
// USING THE CONSTRUCTOR METHOD:
String message = new String("I'm no Bob, though.");
But are these two ways of creating Strings interchangeable? Is the result the same? Let's see.
In Java, created objects are stored in a specific area of memory called the heap. The same goes for strings.
StringS In memory
When a String literal is created, its storing process is slightly different.
Inside the heap region, there's an even more specific zone called the String pool.
String LIterals In memory
What happens if we change the value of the songTitle variable?
Altering strings
Java Strings are immutable!
Altering strings
"Cry Baby" will either be reassigned or garbage collected.
Comparing StringS
String name = "Jim Morrison";
String artist = "Jim Morrison";
System.out.println(name == artist); // what's the result?
String name = "Jim Morrison";
String artist = new String("Jim Morrison");
System.out.println(name == artist); // what's the result?
String name = "Jim Morrison";
String artist = "David Bowie";
System.out.println(name == artist); // what's the result?
String name = new String("Jim Morrison");
String artist = new String("Jim Morrison");
System.out.println(name == artist); // what's the result?
Comparing StringS
(Memory EVENTS ExplaINED)
Despite having the exact same sequence of characters, the Strings name and artist are different objects.
The == operator compares the memory addresses of two objects, not their content.
Comparing Strings Content
The equals() method, available in all String objects, compares the character sequence itself, instead of the objects' memory references.
String name = "Jim Morrison";
String artist = new String("Jim Morrison");
name == artist; // FALSE; compares references
name.equals(artist); // TRUE; compares the content of the two objects
OPERATIONS WITH Strings I
String character = "Cookie Monster";
int length = character.length();
System.out.println(length); // prints 14
char c = character.charAt(1);
System.out.println(c); // prints 'o'
String result = character.concat("!");
System.out.println(result); // prints "Cookie Monster!" || same as using the '+' operator
boolean containsLetterP = character.contains("p");
System.out.println(containsLetterP); // prints false || contains() method takes on a sequence of characters; it's case sensitive
boolean endsWithR = character.endsWith("r");
boolean startsWithR = character.startsWith("r");
System.out.println(startsWithR); // prints false || startsWith() method takes on a String; it's case sensitive
System.out.println(endsWithR); // prints true || endsWith() method takes on a String; it's case sensitive
OPERATIONS WITH Strings II
String monsterMessage = "Om nom nom nom.";
int index = monsterMessage.indexOf("a"); // -1 || indexOf() method takes on a String, and it's case sensitive; returns -1 if there aren't any matches
int secondIndex = monsterMessage.indexOf("o", 5); // 8
int lastIndexOf = monsterMessage.lastIndexOf("o"); // 12
String allCapsMessage = monsterMessage.toUpperCase(); // "OM NOM NOM NOM."
String noCapsMessage = monsterMessage.toLowerCase(); // "om nom nom nom."
String result = monsterMessage.replace("o", "a"); // "Om nam nam nam." || replace() method can take either a single character or a character sequence
String result2 = monsterMessage.replaceAll("\\s", ""); // "Omnomnomnom."
OPERATIONS WITH Strings III
String monsterGift = "I'd give you a cookie but I ate it.";
String[] words = monsterGift.split(" "); // [I'd, give, you, a, cookie, but, I, ate, it.]
String[] moreWords = monsterGift.split(" ", 2); // [I'd, give you a cookie but I ate it.]
String substring = monsterGift.substring(23); // "but I ate it."
String anotherSubstring = monsterGift.substring(15, 21); // "cookie" || second index is exclusive
String cookieType = " chocolate chip ";
cookieType.trim(); // "chocolate chip"
A bunch of musicians are having a feast, and each of them is bringing a dish. The only rule is that the first and last letters of the dish must match the first and last letters of the musician's name.
EXERCISE - The MusicianS Feast I
class DishTester {
public static void main(String[] args){
testDish("Bob Dylan", "beef wellington"); // should print true
testDish("Mick Jagger", "mushroom soup"); // should print false
}
public static void testDish(String musicianName, String dish){
// write your code here
}
}
Each musician is given a password to get into the feast's venue. Every password is generated the same way: a computer program takes the musician's last name and replaces every 'a' with an '@', and every 'i' with an exclamation point.
EXERCISE - The MusicianS Feast II
class PasswordGenerator {
public static void main(String[] args){
generatePassword("Peter Gabriel"); // should print "G@br!el"
generatePassword("Brian Adams"); // should print "@d@ms"
}
public static void generatePassword(String musicianName){
// write your code here
}
}
ARRAYS
Arrays are used to store multiple values in a single variable.
In Java, arrays are objects that must be declared with a specific type.
What is aN Array?
// CREATING AN ARRAY WITH PRE-DEFINED ELEMENTS
int[] numbers = {1, 34, 29, 18};
String[] names = {"Anthony", "John", "Dave", "Florence"};
// ELEMENTS MUST BE OF THE PRE-DEFINED TYPE
numbers[0] = "1"; // COMPILATION ERROR
Creating an empty array
int[] numbers = new int[4]; // [0,0,0,0]
String[] names = new String[2]; // [null, null]
// Java arrays have a fixed size that
// must be defined at the time of creation
names[2] = "Mark"; // RUNTIME ERROR
ARRAYS IN MEMORY
OPERATIONS WITH ARRAYS
int[] numbers = new int[4];
// INSERT DATA INTO ARRAY
numbers[0] = 23;
// CHANGE DATA IN ARRAY
numbers[0] = 34;
// ACCESS ARRAY SIZE
numbers.length
Control Flow
IF-THEn-else
int mariasAge = 16;
if(age > 21){
System.out.println("Please come in!");
} else {
System.out.println("Leave, or I'll call your mom.");
}
IF-THEn-else
int mariasAge = 16;
if(age < 80){
System.out.println("Please come in, but beware of the loud noises.");
} else if(age < 50){
System.out.println("Please, come in!");
} else if(age < 21){
System.out.println("Leave, before I call your mom.");
}
// BEWARE OF THE ORDER
SWITCH STATEMENT
String weekday = "MONDAY";
switch(weekday){
case "SUNDAY":
System.out.println("Sunday, bloody Sunday.");
break;
case "MONDAY":
System.out.println("Monday, Monday, can't trust that day.");
break;
case "TUESDAY":
System.out.println("Give me your heart and I'll love you till Tuesday.");
break;
case "WEDNESDAY":
System.out.println("On Wednesday they're feelin' fine again.");
break;
case "THURSDAY":
System.out.println("And I was Thursday's child (oh, oh, oh, oh).");
break;
case "FRIDAY":
System.out.println("It's Friday, Friday, gotta get down on Friday.");
break;
case "SATURDAY":
System.out.println("Gonna keep on dancing to the rock and roll, on Saturday night.");
break;
}
WHile statement
int bullets = 20;
// WHILE LOOP
while (bullets > 0){
System.out.println("Pew pew pew.");
bullets--;
}
// DO-WHILE LOOP
do {
System.out.println("Pew pew pew.");
bullets--;
} while (bullets > 0);
for statement
String[] names = {"Elizabeth", "Archibald", "Victoria", "Charles", "Sarah"};
// FOR LOOP
for(int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
// ENHANCED FOR LOOP
for(String name : names) {
System.out.println(name);
}
flow disruption - break
String[] names = {"Elizabeth", "Archibald", "Victoria", "Charles", "Sarah"};
for(int i = 0; i < names.length; i++) {
if(names[i].startsWith("C")){
System.out.println("Found who I'm looking for! Hi, " + names[i] + "!");
break;
}
System.out.println("You're not who I'm looking for.");
}
flow disruption - continue
String[] names = {"Elizabeth", "Archibald", "Victoria", "Charles", "Sarah"};
for(int i = 0; i < names.length; i++) {
if(names[i].endsWith("h")){
System.out.println("Hello, " + names[i] + "!");
continue;
}
System.out.println("You're not who I'm looking for.");
}
EXERCISE - THE MUSICIANS FEAST III
It's concert time!
Ten of the invited musicians will perform a concert, and each was given a number, from 1 to 10. That number will define the order in which the musicians will perform.
Madonna, however, wasn't invited to perform and isn't handling the rejection with grace. Once the musicians are all lined up, she takes a number out of the set. Figure out which number she took.
class StolenNumber {
public static void main(String args[]){
findStolenNumber(new int[]{1,2,3,5,6,7,8,9,10}); // should print 4
findStolenNumber(new int[]{1,2,3,4,5,6,7,8,10}); // should print 9
findStolenNumber(new int[]{1,2,3,4,5,6,7,8,9,10}); // should print "no number was stolen"
}
public static void findStolenNumber(int[] numbers){
// write your code here
}
}
METHODS
A method is a collection of statements that are grouped together to perform an operation.
The code inside a method only executes when the method is called.
What is a METHOD?
Non-Returning methods
public void printNumberOne(){
System.out.println(1);
}
public void printNumberTwo(){
System.out.println(2);
}
printNumberOne();
printNumberTwo();
// WHAT IF WE COULD CREATE A METHOD THAT PRINTED ANY NUMER WE WANTED?
PARAMETERS AND ARGUMENTS
public void printNumber(int number){
System.out.println(number);
}
public void addNumbers(int number1, int number2){
System.out.println(number1 + number2);
}
printNumber(34); // 34
printNumber("one"); // COMPILATION ERROR
addNumbers(2, 10); // 12
Returning methods
public int addNumbers(int number1, int number2){
return number1 + number2;
}
int result = addNumbers(2, 10);
int result2 = addNumbers(22); // COMPILATION ERROR
String result3 = addNumbers(2, 8); // COMPILATION ERROR
System.out.println(addNumbers(1, 1)); // prints 2
MATH METHODS
// ABSOLUTE
int absoluteInt = Math.abs(-10); // returns 10
double absoluteDouble = Math.abs(2.22); // returns 2.22
// ROUNDING
double number = 10.3;
double roundedUp = Math.ceil(number); // 11.0
double roundedDown = Math.floor(number); // 10.0
int rounded = Math.round(number); // 10
// RANDOM
int min = 1;
int max = 10;
double random1 = Math.random(); // value between 0 and 1 (exclusive)
double random2 = Math.random() * max; // value between 0 and max (exclusive)
double random3 = Math.random() * (max + 1); // value between 0 and max (inclusive)
double random4 = Math.random() * (max - min + 1) + min; // value between min and max (inclusive)
int randomInt = (int) (Math.random() * (max - min + 1) + min);
MAth methods I
// MAX
double maxDouble = Math.max(10.2, 11.3); // 10.2
int maxInt = Math.max(23, 12); // 12
// MIN
double minDouble = Math.min(1.23, 2); // 1.23
int minInt = Math.min(12, 50); // 12
int minInt = Math.min(12.2, 5); // COMPILATION ERROR
MAth methods II
The party is coming to an end, and the last musicians are leaving the venue when the staff calls them to help clean up the place.
No one wants to do it, so a plan takes form: they will all line up, and a staff member will think of a random number between 10 and 15 to give each artist. If the musician's name has more letters than the picked number, that musician gets chosen to help. The others are free to go.
EXERCISE - The MusicianS Feast IV
class MusiciansHell {
public static void main(String[] args){
String[] musicians = {"Steven Tyler", "Erykah Badu", "Mick Jagger", "Paul McCartney", "Brandon Flowers", "Alex Turner"};
String musician = pickMusician(musicians); // should return the musician's name, or "No one will stay to help."
}
public static String pickMusician(String[] musicians){
// write your code here
}
}
Intro to Java
By Soraia Veríssimo
Intro to Java
- 1,692