Developer - Level 1
Table of Contents
Introduction
0.1
0.2
Java Basics
What is Java?
1.1
1.2
Hello World
1.3
1.4
Java REPL
1.5
1.6
Variable exercises
1.7
Strings
1.8
String exercises
1.9
Numbers
1.10
Number exercises
1.11
Methods in Java
1.12
Method exercises
1.13
Booleans
1.14
Practice: Booleans
1.15
Arrays
1.16
Practice: Arrays
1.17
Introduction to Git
README Template
2.1
Git clone
2.2
2.3
2.4
Looping
3.1
3.2
For loops
3.3
3.4
While loops
3.5
Android Developer
So you want to learn how to become a mobile developer? Great decision! What mobile
development platform should you start learning first?
We at Opteamize, an IBM Coding School teach programming and while our platform is
Javascript-centric, we feel that most of our students will have great success with Android
Development. Let us explain courtesy of this excellent list from androidauthority.com why
you should start with Android development platform compared to iOS.
Portability
Native Android apps are developed using the Java programming language, and can easily
be ported to other mobile operating systems like Blackberry, Symbian and Ubuntu. In
addition, Android apps can also be ported easily to Chrome OS.
Google Play Store
Apps deployed to the Google Play store are available for download by users within a few
hours, compared to a few weeks for Apples App Store. An app can literally be updated
multiple times a day on the Google play store, in response to user complaints and/or issues,
while on the App store, your app would have to pass through the same lengthy process
whenever you submit an update and/or bug fix.
Android Studio
Android Studio is an excellent IDE, based on the equally excellent IntelliJ IDE. As the name
suggests, Android Studio is an IDE designed and developed specifically for Android app
Introduction
development. It is blazing fast and efficient, and you can setup a new Android project for
different types of Android apps within seconds.
Java
Java is a proven and powerful programming language, used on a wide range of devices and
operating systems. Learning Java can open doors for other opportunities, including the
ability to develop applications for other operating systems (Windows, Linux) and devices.
Developing for iOS, on the other hand, requires that you learn one of Apples development
languages (Objective C or Swift).
Low barrier of entry
To develop for iOS devices, a developer must use a Mac. However, Android app
development can be done on Windows, Mac and Linux. Also, to register as a developer on
the Apple App Store requires a yearly fee of $99, whereas to register as a developer on the
Google Play Store requires a one time payment of $25.
Market Share
This has to be the number one reason why developers should develop for Android first.
According to IDC, Android absolutely dominated the number of smartphones shipped
worldwide in the first three months of 2015, with 78% market share.
Welcome to Opteamize, an IBM Coding School!
Introduction
You shall not share your login, course content or other course related material with any
3rd party.
Job Guarantee Conditions
Attendance will be taken at the beginning of each class. Failure to get 80% attendance
may result in not being allowed entry into Job Guarantee program.
You shall clear Level 1 and Level 2 Examinations in a maximum of 2 attempts to gain
eligibility into Job Guarantee program. Pass marks for both these Examinations will be
60%.
You shall complete Live Project successfully scoring atleast 70% marks.
You shall submit original copies of your Marks Sheet and/or Degree Certificate with us
for safekeeping during the duration of Job Guarantee program. The original copies shall
be returned upon full payment of any pending fees.
You shall be allowed a maximum of 4 personal interviews within a period of 3 months
after graduation. You shall attempt to clear and join one of those companies.
You will agree to pay all fees promptly and as per agreed terms and conditions Option
(a) Full Payment (b) Partial Payment + 15% of Annual CTC.
You shall agree to pay 7.5% of the annual CTC within 7 days of receipt of offer letter.
Balance 7.5% shall be paid within 30 days after payment of first instalment.
No refund in partial or full is payable to you if you fail to clear and/or attend any of the 4
interviews arranged for you.
Failure to comply with any of above General Conditions & Job Guarantee Conditions
shall result in not being eligible for Job Guarantee program.
Our Commitment to you
Our support team shall support you through email, Chat, phone call, forum etc. within a
reasonable time frame.
During class time, your instructors will be available as much as possible to answer your
questions, review your code, help you with problems, and guide you through the
process of learning software programming.
Once a week, one of your instructors will have a one-on-one session with you.
We shall strive to provide you atleast 99.5% uptime of the Opteamize Coding Platorm.
However we cannot guarantee the same as it is dependent on 3rd party hosting
services.
If classes get canceled due to unfavourable conditions (like weather, power cuts etc.)
then we will try to compensate with alternate class.
We will do our best to help you find a job but we cannot guarantee how long it will take
you to find a job, or what salary you will receive.
Interviews shall be relevant to the Android or Front End Developer job roles envisaged
for you based on the course chosen and graduated from.
We feel a personal obligation to help you find a job you love, and as the reputation of
Opteamize depends on your success in the job market, it is in our best interest to do
whatever we can to help you succeed.
All the best!
Signature of Student Signature of Parent
Welcome
Hi! Welcome to Opteamize, an IBM Coding School. This is a step-by-step guide to take you
from zero experience to Front End Developer in 3 months, and contains everything you
need, including lessons and practice exercises. The content you see here is the same
curriculum at Epicodus, a Coding School in Portland, OR (USA). Thank you Michael for
agreeing to share the curriculum with Opteamize thus benefiting hundreds of Indian
students.
Curriculum
The curriculum has a strong focus on all of the skills required of Android Developers today
and is crafted to simulate a real job environment, exposing students to broken tests,
incomplete documentation and other surprises that give them experience with the sorts of
real-world challenges that many Engineers only encounter late in their careers.
If learning how to program sounds a bit overwhelming, don't worry! The curriculum is broken
down so that each step along the way is small and manageable. All you need to do is follow
along and do the exercises. Note: if you don't do the exercises, all of this is pointless. You
can't learn to program by watching somebody else. You have to actually do it
yourself.
The program culminates with student live projects and soft skills training, so that students
have the ability to articulate their skills to employers and get placed at first attempt.
Check out the table of contents to see an overview of all the sections.
Level 1 - Technical
Level 1 is designed to take you from zero experience to being able to create a basic web
page that displays information with the presentation language HTML and style it with CSS.
Understand the basics of Javascript and get a good understanding of jQuery.
Level 2 - Technical
By the second level of the course, students would have honed the ability to thrive within the
constantly shifting software engineering landscape, frequently working on projects based on
technologies not explicitly covered in our curriculum. Get a better understanding of
Javascript and discover the wonderful framework created by Google Engineers, Angularjs.
10
Java Basics
In this course, we will learn the foundations for one of the most popular programming
languages in the world: Java. Java is especially popular with big enterprise companies
including:
Google
Ebay
Amazon
Nike
LinkedIn
It will require some work before you are able to create sophisticated web applications, but if
you work hard and stick with it, you will get there.
To get started you will need to learn the foundation tools of the Java language:
First, we are going to learn about some basic types of information, Strings and
Integers. You will learn how to manipulate these with what are called operators.
Then, you will also learn how to save Strings and Integers into variables, so that you
can reuse them throughout your application, and how to apply methods to your
variables to have them do interesting things.
After learning methods that Java provides us, we will learn how to write our own
methods.
Next, we will learn about Arrays, a way to store lists of information.
The next topic is called branching. This will allow our code to make decisions, such as
only allowing users of a certain age to enter our website.
Lastly, we are going to learn how to automate repetitive parts of our code by using
looping, such as if we have a long list of people and phone numbers that we want to
display on a page. Let's get started!
Java Basics
11
Welcome to Java
Java is a general-purpose, concurrent, class-based, object-oriented computer programming
language that is specifically designed to have as few implementation dependencies as
possible. It is intended to let application developers "write once, run anywhere", meaning
that code that runs on one platform does not need to be recompiled to run on another.
Java applications are typically compiled to bytecode (class file) that can run on any Java
virtual machine (JVM) regardless of computer architecture. Java is one of the most popular
programming languages in use, particularly for client-server web applications. The language
derives much of its syntax from C and C++, but it has fewer low-level facilities than either of
them.
How it all started
Before starting to learn Java, let us plunge into its history and see how the language
originated. In 1990, Sun Microsystems Inc. (US) conceived a project to develop software for
consumer electronic devices that could be controlled by a remote. This project was called
Stealth Project but later its name was changed to Green Project.
In Jan of 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton and several others
met in Aspen, Colorado to discuss this project. Mike Sheradin was focused on Business
Development, Patrick Naughton worked on the Graphics systems and James Gosling was to
identify the proper programming language for the project. Gosling thought C and C++ could
be used to develop the project. But the problem he faced with them is that they were system
dependent languages and hence could not be used various processors which the electronics
devices might use. He started to develop a new language which was completely system
independent. This language was initially called as OAK. Since this name was registered by
other company, later it was changed to JAVA.
Why the name Java?
James Gosling and his team members were consuming a lot of coffee while developing this
language. They felt that they were able to develop a better language because of the good
quality of coffee they consumed. So the coffee had its own role in developing this language
and good quality of coffee was exported to the entire world from a place called Java near
Indonesia. Hence they fixed the name of the place for the language as JAVA. And the
symbol for JAVA Language is coffee cup and saucer.
What is Java?
12
By September of 1994, Naughton and Jonathan Payne started writing WebRunner-a Java
based Web browser, which was later renamed as HotJava. By October 1994, HotJava was
stable and was demonstrated to Sun executives. HotJava was the first browser, having the
capabilities of executing applets, which are programs designed to run dynamically on
Internet. This time, Java's potential in the context of the World Wide Web was recognized.
Sun formally announced Java and HotJava at SunWorld conference in 1995. Soon after,
Netscape Inc. announced that it would incorporate Java support in its browser Netscape
Navigater. Later, Microsoft also announced that they would support Java in their Internet
Explorer Web browser. The first Java version was released on 23rd January 1996, JDK 1.0
version.
Java 2 Platform
Java has advanced through the years in both functionality and reach. Current editions are on
the Java 2 Platform. The Java 2 Platform has various incarnations as well, including Java 2
Platform.
The Java 2 Platform has three basic Editions1. Java 2 Standard Edition (J2SE): J2SE is used primarily for writing applets and other
Java-based applications.
2. Java 2 Enterprise Edition (J2EE): J2EE is the Java architecture for developing multitier
enterprise applications. As part of J2EE, JSP pages have access to all J2EE
components, including JavaBeans and Enterprise JavaBeans components and Java
servlets. JSP pages are actually compiled into servlets, so they have all of the benefits
of these flexible, server-side Java applications.
3. Java 2 Micro Edition (J2ME): J2ME is a technology that allows programmers to use the
java programming language and related tools to develop programs for mobile wireless
information devices such as cellular phones and personal digital assistants (PDAs).
Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently
used. Some of them are as follows:
Desktop Applications
Web Applications
Enterprise Applications
Mobile
Embedded Systems
Smart Card
Robotics
What is Java?
13
Games etc.
Java Application Types
There are different types of Java applications before moving on to Servlets. Java can be
used to develop different types of applications:
1. Standalone Applications
A standalone application is a program that runs on your computer. It is more or less like a C
or C++ program.
2. Applets
An applet is an application designed to travel over the Internet and to be executed on the
client machine by a Java-Compatible web browser like Internet Explorer. Applets are also
Java programs but they reside on the servers. An applet can not be executed like
standalone application. Applet can be executed only by embedding it into an HTML page like
an image or sound file. To run an applet you need to access an HTML page which has
applet embedded into it. When the web browser downloads such an HTML page, it
subsequently loads the executable file, which contains Applet and then executes it on the
local machine.
3. Web Applications Web applications run on the Web Server. Web applications are
accessed through web clients i.e. web browsers like Internet Explorer. Whenever you access
some web site by specifying the URL (Universal Resource Locator), you are accessing
some web application.
The main components of a web application written in Java are:
Java Servlets
Java Server Pages (JSP), and
HTML
Java Servlets are also Java programs, which run on the Server and then send the
result/response to the client.
JSP pages can be thought of as a combination of HTML and Java Code. The Web Server
converts JSP pages into Java Servlets before execution.
You access the web application by specifying the URL. If the URL corresponds to an HTML
page the web server simply returns the HTML page to the client, which then displays it. If the
URL corresponds to the Servlet or JSP then it is executed on the Server and the
result/response is returned to the client, which is then displayed by the client.
What is Java?
14
Distributed Applications
Java application can be divided into a number of modules/components (Java programs),
which can run on different machines. The Java programs/applications running on different
machines can communicate with each other. To be more precise the Java Objects on one
machine can invoke methods on the Java Objects running on another machine. Thus Java
has the support for the distributed processing in the language itself.
What is Java?
15
Java setup
To start, download and install the Java SDK (Standard Edition Development Kit).
Next, download and install the Java JRE (Runtime Environment).
To make sure everything is installed correctly, run $ java -version . You should get
something like (version numbers do not need to be the same):
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
16
Hello World
Embedded Video: https://www.youtube.com/watch?v=UXL1W3ffzmE?rel=0
Now that we have some Java basics in place, lets use Java to write a program that simply
prints "Hello World" to the screen.
In the terminal, navigate to the directory where you want your new Java program to exist.
Create a folder called hello-world. Then create a file called Hello.java (the capitalization
of Hello is necessary).
Open that file in your text editor and type this code:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Now, navigate to your hello-world folder in your command line. To run this program will
require two steps.
First we need to run:
$ javac Hello.java
This tells the Java compiler to compile your code into code that the Java Runtime
Environment (JRE) can read. It will create a file called Hello.class with the compiled code in
the same directory as your Hello.java file.
Next run this command:
$ java Hello
This tells Java to look for a .class file named Hello.class and to run the compiled code in it.
You should now see Hello World on your terminal. Congratulations - you just wrote your
first Java program!
Hello World
17
Questions
Why do you think application code needs to be compiled before it is run successfully?
What is the difference between the "Hello.java" file and the "Hello.class" file?
What does System.out.println() do?
18
Java REPL
Embedded Video: https://www.youtube.com/watch?v=lOWlje6DnP0?rel=0
For the first exercises, we will be using a REPL, which stands for READ - EVALUATE PRINT - LOOP:
1. You type in a line of code and hit enter, and the REPL reads it in.
2. The REPL evaluates the code to figure out what it does.
3. The REPL prints the result.
4. The REPL loops back to step 1 and waits for you to type some more code.
Luckily, setting up your REPL for Java is as easy as opening www.javarepl.com. We will be
using this REPL for all of the Java basics.
For those of you with Macs, you can easily install javarepl onto your machine using
Homebrew. To install Homebrew, follow the instructions on Homebrew's website; make sure
to pay attention to the messages it gives you to configure your computer after it installs.
Then, just type $ brew install javarepl . After it finishes, you can launch the REPL with $
javarepl .
You can enter the Java REPL by typing $ javarepl . You can exit at any point by hitting Ctrl
+ C.
Java REPL
19
After each variable declaration, we were able to reference the variable by typing its name,
phrase , and the REPL printed out its value.
When we referenced the variable in the statement phrase + "!"; , Java replaced phrase
with the value at that time. At first, the value was "Hello World" ; then, it was "Goodbye
World" . Variables behave exactly like the value they store.
You may have noticed that java.lang.String xyz = looks familiar. That is because the
REPL saves your data into a default variable if you don't assign one.
"Hello World";
java.lang.String res0 = "Hello World"
20
res0 is your default variable that has been assigned. Just like with a variable you declare,
Now, lets make an integer variable. Much like the string variable, you must declare your data
type as Integer . For example:
> Integer number = 1;
java.lang.Integer number = 1
> number + number;
java.lang.Integer res2 = 2
> Integer bigNumber = 100;
java.lang.Integer bigNumber = 100
> number + bigNumber;
java.lang.Integer res3 = 101
A quick note on naming conventions. Variable names use what is called lower camel case.
The first letter of the first word is lowercase, there are no spaces between words, and
subsequent words are capitalized. Also, try to be explicit about what the data saved in the
variable is, so that it's easy to understand what your code is doing. number and phrase are
meaningful variable names; if you use variable names like num or n or thing or xyz , it
will be hard for other people to understand your code.
21
Variable exercises
Create a variable called myName and set it to your name. Finish the sentence "My name
is " with that variable.
Create a variable called myFavoriteNumber and set it to your favorite number. Use your
favorite number in the REPL to do some math.
Create a few more string and integer variables. Use your imagination and have fun with
them!
Variable exercises
22
(Don't type the > ; that's just to show you the beginning of the prompt in the REPL.)
A string is a sequence of characters between two quotation marks.
Every line in Java must end with a semicolon. (There are a few exceptions to this that you'll
learn later, but don't worry about that for now.)
Notice the java.lang.String res0 = "Hello World" bit below what we typed. This is called
the return value. For now, it's just the same as what we typed. In a moment, we'll see how it
can be different.
Let's write a couple more strings.
> "Programming is awesome!";
> "Winter is coming";
Notice how the return value is different from what we originally typed. This is the evaluation
part of the REPL acronym: Java has evaluated the code and given us back a new result.
Using the + symbol with strings is called concatenation: making a new string out of
multiple strings. The middle string is just a space.
Here's another example:
Strings
23
Oops, I got an error. That is something that is going to happen to you a lot. The error
messages can be a bit tricky to read, but if you look closely, they will tell you the problem.
The first error isn't very helpful, the but second error points us to a missing + .
Let's fix this:
> "Programming" + " " + "is" + " " + "awesome!";
java.lang.String res0 = "Programming is awesome!"
Play around with strings a bit more in your REPL and then move on to the next lesson.
Strings
24
String exercises
Exercises:
Try creating some different Strings. Be sure to end each line with a ; .
Create a String with your first name and concatenate it with + to another String with
your last name.
Try concatenating a few other strings together. Remember to add a " " if you want
space between words.
String exercises
25
While this second example may look like an integer, you will notice that Java read it as a
string, whereas the first example Java read as an integer. Strings are the only type of data
wrapped in quotation marks.
With strings, we used the + operator to concatenate them. Integers use the + operator for
addition. Let's try it out.
> 1 + 1;
java.lang.Integer res2 = 2
Just like with concatenating, Java evaluates 1 + 1 and then returns a new integer object
that is the sum of the two integers.
The four operators used with integers for arithmetic are:
+ for addition
- for subtraction
* for multiplication
/ for division. Why don't we try them out?
Numbers
26
> 1 - 1;
java.lang.Integer res3 = 0
> 2 * 2;
java.lang.Integer res4 = 4
> 4 / 2;
java.lang.Integer res5 = 2
Numbers
27
Integer exercises
Exercises:
Practice using the operators + , - , / , and * to perform simple math using various
numbers. See what happens when you use + with "1" and 1 .
Number exercises
28
Methods in Java
Embedded Video: https://www.youtube.com/watch?v=N7MfPFfbAmE?rel=0
We've seen how to use operators to change strings and integers, but a more common way
to interact with information in Java is by calling methods:
> String phrase = "Programming is Awesome";
java.lang.String phrase = "Programming is Awesome!"
> phrase.toUpperCase();
java.lang.String res0 = "PROGRAMMING IS AWESOME!"
> phrase.toLowerCase();
java.lang.String res1 = "programming is awesome!"
> phrase.length();
java.lang.Integer res2 = 23
We just used some very straightforward methods to manipulate our data. The pattern for
calling a method is very simple:
1. First we append a . , or dot, to our variable.
2. Next we add the method name. In the first example that was toUpperCase , the second
was toLowerCase , and the third was length .
3. Following all methods in Java we append an open and closed parentheses, () . These
are often called parens, short for parentheses.
The method runs some code that will do something with the string or integer that it is called
on. In our examples above, the methods make a string all uppercase, lowercase, or find its
length.
Let's look at a couple more methods:
> String phraseOne = "Hello ";
java.lang.String phraseOne = "Hello "
> String phraseTwo = "World!";
java.lang.String phraseTwo = "World!"
> phraseOne.concat(phraseTwo);
java.lang.String res4 = "Hello World!";
> res4.replaceAll("Hello", "Goodbye");
java.lang.String res5 = "Goodbye World!";
Methods in Java
29
Here, the parentheses on methods are used to pass in arguments to a method. Arguments
are pieces of data that a method can use in addition to the thing it's called on.
The first method we used, .concat() , was a string method that we passed a string as an
argument. It concatenated the first string with the second string, just like the + operator.
The second method, .replaceAll() , takes two arguments, both of which are strings. It will
find all segments of the string, or substrings, that match the first argument, and then
replace those substrings with the second argument. We turned the string "Hello World!" into
the string "Goodbye World!".
When you pass an argument to a method, it must be the correct type. For example, the
.concat() method can only be passed a string as its argument. If you try to pass an integer
If you ever need to find out what kind of arguments you can pass into String methods, you
can look at the Java String Documentation.
Integers also have methods, but not very many, and none of them are very interesting.
Here's one that converts an integer to a string:
> Integer number = 56;
java.lang.Integer number = 56
> number.toString();
java.lang.String res4 = "56"
Methods in Java
30
Method exercises
Practice using a few new methods:
"A".compareTo("B"); This method will return -1 since the first letter is located 1 place
before the second in the alphabet. It would return 0 if it is equal, or the number of
places after if it comes after the second in the alphabet.
" Hi ".trim(); This will remove any extra spaces at the beginning and the end of a
string.
Method exercises
31
Booleans
Embedded Video: https://www.youtube.com/watch?v=IH7hFdU6N1Y?rel=0
Let's explore a new type of data, booleans. Booleans can hold one of two values: true or
false . Let's open up the Java REPL and look at some operators that return booleans.
This is a pretty straight forward concept. The equality operator == is asking if something is
equal to something else. If it is then the Boolean will be true .
In the statement "1" == "1" we are checking to make sure that "1" is equal to "1" .
They are, so the Java REPL creates a Boolean variable java.lang.Boolean res0 = true .
Likewise, in the second statement "1" is not equal to "2" , so we create a Boolean
variable that is false : java.lang.Boolean res1 = false
We can also save Boolean variables to use again later like in Boolean isMathWrong = 1 > 2;
and Boolean isMathRight = 1 < 2; . Here we are creating our Booleans using the relational
operators > and < to check if an Integer is greater than or less than another operator. Once
the result is processed into a Boolean statement, we save it into a Boolean variable.
Using Booleans, we can add branching logic in the applications we write. Let's write
an if/else statement to see if somebody can see a rated R movie.
if-else-then/RatedR.java
Booleans
32
import java.io.Console;
public class RatedR {
public static void main(String[] args) {
Console console = System.console();
System.out.println("How old are you?");
String stringUserAge = console.readLine();
Integer integerUserAge = Integer.parseInt(stringUserAge);
if ( integerUserAge >= 17 ) {
System.out.println("You can see the movie!");
} else {
System.out.println("I'm sorry, you are too young to see that movie.");
}
}
}
We took the user's age, converted it to an integer and then used the relational operator >=
to check and see if their age was greater than or equal to 17 . When the code after if , (
integerUserAge >= 17 ) , evaluates to true , Java will run all the code between the first set
of curly braces. When it evaluates to false , Java will run all the code between the set of
curly braces that follows else .
There are also a lot of methods that will return a Boolean. Let's create a statement using one
of these methods.
if-else-then/StartsWithZ.java
import java.io.Console;
public class StartsWithZ {
public static void main(String[] args) {
Console console = System.console();
System.out.println("What's your name?");
String userName = console.readLine();
if ( userName.startsWith("Z") ) {
System.out.println("Your name starts with a Z!");
} else {
System.out.println("Your name doesn't start with a Z :(");
}
}
}
Booleans
33
The parentheses after the if statement is where we store our statement that returns a
boolean. We used userName.startsWith("Z") as the statement here. The method
startsWith("Z") is called on the userName variable. It will take the string argument passed
to it, "Z" and compare it to the first letter of userName . It will return true if it is equal to
the argument, and false if not.
Here is a list of operators that you can reference for your exercises:
Equality
==: equal to. 1 == 1 is true. 1 == 2 is false.
!=: not equal to. 1 != 2 is true. `1 != 1 is false.
Relational
: greater than. 2 > 1 is true. 1 > 2 is false.
=: greater than or equal to. 2 >= 2 and 2 >= 1 are both true. 2 >= 3 is false.
<: less than. 1 < 2 is true. 2 < 1 is false.
<=: less than or equal to. 1 <= 1 and 1 <= 2 are both true. 2 <= 1 is false.
Booleans
34
Practice: Booleans
There are a lot of methods that return booleans, so let's use a couple more:
"foo".matches("foo"); Returns true if the String matches the String argument.
"Hi".contains('H'); Note the single quotes on 'H' . Sometimes a method will ask for a
single character, called a char . chars are always wrapped in single-quotes. 'H', '1' , '
' and '&' are all char s. This method will returntrueif a string contains the char`
argument.
Make a program that will ask for a number and add 1 to it if it is positive or 0, and
subtract 1 if it is negative.
Make program that asks the user's age and then tells them whether they can drink
alcohol legally.
Make program that asks for a number and then tells whether it has two digits. Hint: a
number has two digits if it is between 10 and 99.
Practice: Booleans
35
Arrays
Embedded Video: https://www.youtube.com/watch?v=4jaVh8PCUNc?rel=0
When we are programming, it is often useful to store our data in collections of data. Let's
open up our REPL and see how we can use arrays to store data.
> String[] fruits = { "apples", "bananas", "oranges", "grapes" };
java.lang.String[] fruits = ["apples", "bananas", "oranges", "grapes"]
> Integer[] primeNumbers = { 2, 3, 5, 7, 11 };
java.lang.Integer[] primeNumbers = [2, 3, 5, 7, 11]
We access the array by calling the array's variable name. To access one entry in the array
we append square brackets, [], to the variable name, and inside the square brackets we
insert the index of the item that we want to reference. The array will then return the
information that we asked it for.
Arrays
36
In programming, we count list items starting at 0. What normal humans would call the first
item in an array is at index 0, the second is at index 1, and the one hundredth is at index 99.
We can also change the value at each index of an array.
> fruits[2] = "blood oranges";
java.lang.String res2 = "blood oranges"
> fruits
java.lang.String[] fruits = ["apples", "bananas", "blood oranges", "grapes"]
> fruits[3] = "concord grapes";
java.lang.String res2 = "concord grapes"
> fruits
java.lang.String[] fruits = ["apples", "bananas", "blood oranges", "concord grapes"]
Again, we are appending the index in square brackets to the array variable. In the line
fruits[2] = "blood oranges"; we are using = to reassign the value at index 2, "oranges" ,
Summary
Terminology
array: a sequenced collection of data designated with square brackets [ ]
Example:
> String[] fruits = { "apples", "bananas", "oranges", "grapes" };
java.lang.String[] fruits = ["apples", "bananas", "oranges", "grapes"]
> Integer[] primeNumbers = { 2, 3, 5, 7, 11 };
java.lang.Integer[] primeNumbers = [2, 3, 5, 7, 11]
index: the sequence location of an element in an array; first element of an array has an
index of 0.
Example:
Arrays
37
> fruits
java.lang.String[] fruits = ["apples", "bananas", "oranges", "grapes"]
> fruits[1];
java.lang.String res0 = "bananas"
> fruits[3];
java.lang.String res1 = "grapes"
> String favoriteFruit = fruits[0];
java.lang.String favoriteFruit = "apples";
Arrays
38
Practice: Arrays
Code
Create a String Array of things you don't like. Then replace all of the Strings in that array
with things that you like.
Create an Integer Array. Save the results of multiplying an element by itself back into
that element's index.
Questions
What is the difference between a String Arrray and an Integer Array?
What is the index of "lemur" in this array of animals, ["gorilla", "chimpanzee", "lemur",
"orangutan"]? What is the index of "gorilla"?
Practice: Arrays
39
Introduction to Git
Embedded Video: https://www.youtube.com/watch?v=r63f51ce84A?rel=0
GitLab
GitLab is an online Git repository manager with a wiki, issue tracking, Continuous Integration
(CI) and Continuous Deployment (CD). It is a great way to manage git repositories on a
centralized server. GitLab gives you complete control over your repositories or projects and
allows you to decide whether they are public or private for free.
What is Git? Git is a system where you can create projects of different sizes with speed and
efficiency. It helps you manage code, communicate and collaborate on different software
projects. Git will allow you to go back to a previous status on a project or to see its entire
evolution since the project was created. You could think of it as a time machine which will
allow you to go back in time to whenever youd like in your project.
With Git, 3 basic issues were solved when working on projects:
It became easier to manage large projects.
It helps you avoid overwriting the teams advances and work. With git, you just pull the
entire code and history to your machine, so you can calmly work in your own little space
without interference or boundaries.
Its much simpler and much more light-weight.
What is Repository? The place where the history of your work is stored.
What is Remote repository? Its a repository that is not-on-your-machine, so its anything
that is not your computer. Usually, it is online, GitLab.com for instance. The main remote
repository is usually called Origin.
What is Source control or revision control software? Its a system that records and
manages changes to projects, files and documents. It helps you recall specific versions later.
It also makes it easier to collaborate, because it shows who has changed what and helps
you combine contributions.
What is Continuous Integration (CI)? Its the system of continuously incorporating the
work advances with a shared mainline in a project. Git and GitLab together make continuous
integration happen.
Introduction to Git
40
What is Continuous deployment (CD)? It means that whenever there is a change to the
code, it is deployed or made live immediately. This is in contrast to continous integration,
where code is continuously being merged in the mainline and is always ready to be
deployed, rather than actually deployed. When people talk about CI and CD what they
usually mean to say is that they are constantly and automatically testing their code against
their tests using a tool such as GitLab CI and upon passing to a certain action. That action
could be merging the code into a branch (master, production, etc), deploying it to a server or
building a package / piece of software out of it. Non-continuous integration would be
everyone working on something and only integrating all the work as the very last step.
Obviously, that results in many conflicts and issues, which is why CI is adopted widely
nowadays.
What is a Commit? Its the way you call the latest changes of source code that you made
on a repository. When changes are tracked, commits mark the changes on a document.
What is a Master? Its how you call the main and definitive branch (the independent line of
development of a project).
What is a Branch? Its an independent line of development. They are a brand new working
directory, staging area, and project history. New commits are recorded in the history for the
current branch, which results in taking the source from someones repository (the place
where the history of your work is stored) at certain point in time, and apply your own
changes to it in the history of the project.
What is a Fork? Its a copy of an original repository (the place where the history of your
work is stored) that you can put somewhere else or where you can experiment and apply
changes that you can later decide if publishing or not, without affecting your original project.
What is a Clone? Its to get a copy of a git project to look at or to use the code.
What is to Merge? Its integrating separate changes that you made to a project, on different
branches.
What is markdown? Its a plain text format that will make any document easy-to-write and
easy-to-read.
What is to Push a repository? Its to incorporate a local branch (the independent line of
development of a project) to a remote repository (online version of your project).
What is a README.md? It's a file in a simple format which summarizes a repository. If
theres also a README (without the .md), the README.md will have priority.
What is SSH (secure shell protocol)? Its how you call the commands that help
communicate through a network and that are encrypted and secure. Its used for remote
logins and it helps users connect to a server in a secure way.
Introduction to Git
41
What is to stage a file? Its how you call the act of preparing a file for a commit (the latest
changes of source code in a repository).
Introduction to Git
42
README Template
Every GitHub repository should include a README.md file that provides the visitor to the
repo with the general information about the repository and the code it stores. The
README.md file should be stored at the top level of the project folder. GitHub will look for
this file and present it on the main viewing page of the repository.
README Information
Every README should have these five parts:
A description of the project's purpose
Complete setup instructions
Names of contributors
A copyright with the date
License information
And could additionally include sections for:
Technologies used
Known bugs
Contact information
Support or Contribution instructions
README Template
Here is some README text for you to use in your apps. It's already written in Markdown, so
it will be nicely formatted on Github. If you aren't familiar with Markdown check out
Markdown Live Preview to get familiar.
It's worth taking the time to make your README look nice because it will be the first thing
anyone will see in any of your projects. If people see that you have a messy or incomplete
README, they will assume that your code is also messy or incomplete. But if you have a
README Template
43
README with clean formatting and clear setup instructions, your users will have more
confidence in trying out your software.
If you copy and paste the text below into a new file and replace the relevant parts with
information about your project, then it will look something like this at the end.
README Template
44
# _{Application Name}_
##### _{Brief description of application}, {Date of current version}_
#### By _**{List of contributors}**_
## Description
_{This is a detailed description of your application. Give as much detail as needed to explain what t
## Setup
* _This is a great place_
* _to list setup instructions_
* _in a simple_
* _easy-to-understand_
* _format_
_{Leave nothing to chance! You want it to be easy for potential employers and collaborators to run yo
## Technologies Used
_{Tell me about the languages you used to create this app. Assume that I know you probably used HTML
### Legal
*{This is boilerplate legal language. Read through it, and if you like it, use it. There are other li
Copyright (c) 2015 **_{List of contribtors}_**
This software is licensed under the MIT license.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
README Template
45
README Template
46
Git clone
Often, we'll want a local copy of a public repository on our local devices. This is called a
clone in Git terminology.
To create a local clone, find the GitHub repository URL and copy it - either from the address
bar or with the copy to clipboard button (see red boxes below).
In the terminal, navigate to the directory to store the cloned repository and run git clone with
the chosen repo's URL:
$ git clone https://github.com/epicodus_examples/title_case_sinatra
Cloning into 'title_case'...
remote: Counting objects: 14, done.
remote: Total 14 (delta 0), reused 0 (delta 0), pack-reused 14
Unpacking objects: 100% (14/14), done.
Checking connectivity... done.
The clone command creates a clone of the remote repository in the current directory,
including the initialized .git repository so you can immediately begin working and making
commits.
Git clone
47
48
Summary
git checkout -b _branch-name_ : creates and checks out a new branch named branch-name
git branch: lists current branches with an asterisk to indicate the one you're currently on git
branch -D _branch-name_ : delete the branch named branch-name git merge _branch-name_ :
merge branch-name into the current branch git clone _remote-name_ : creates a local
repository from a remote repository git remote: lists currently associated remote repositories
git remote add _remote-name_ _url_ : adds a new remote repository with the name remotename using the URL of the remote repo on github git push remote-name _branch-name_ :
pushes your branch (branch-name) to a remote repository (remote-name) git pull remotename _branch-name_ : pull the latest changes from a remote repository to your repository
(e.g. git pull origin master)
49
50
51
52
This prints our list out to the console, but what if we wanted to add a few more items to our
list? Or what if it was the holidays and we had a huge list? We would have to add a new
System.out.println for each new item.
There is a new keyword for that we can use to create a for each loop. This for each
loop will help us print each item in an array, no matter how big it is. Let's add it into our
GroceryList application. We'll also add a few more items to myGroceryList while we are
there.
grocery-list/GroceryList.java
public class GroceryList {
public static void main(String[] args) {
String[] myGroceryList = { "eggs", "milk", "bread", "bananas", "cereal", "rice", "yogurt" };
System.out.println("My grocery list:");
for ( String groceryItem : myGroceryList ) {
System.out.println( groceryItem );
}
}
}
53
The line for ( String groceryItem : myGroceryList ) can be read as "for each item in
myGroceryList , name it groceryItem . Then run the line of code between the curly braces."
In this case we are simply printing System.out.println( groceryItem ); to the console for
each item in the myGroceryList .
We can loop through any type of an array. Let's add the ability to keep track of how much
our grocery trip will cost us.
grocery-list/GroceryList.java
public class GroceryList {
public static void main(String[] args) {
String[] myGroceryList = { "eggs", "milk", "bread", "bananas", "cereal", "rice" };
Integer[] groceryItemPrices = { 3, 6, 4, 2, 4, 4 };
System.out.println("My grocery list:");
for ( String groceryItem : myGroceryList ) {
System.out.println( groceryItem );
}
Integer total = 0;
for ( Integer price : groceryItemPrices) {
total = total + price;
}
System.out.println("Your total for this shopping trip will be: $" + total);
}
}
We create a new Integer total , and set it to 0 . It is important that we do this outside of
our loop, or it will be reset to 0 each time we go through it.
Inside, we are updating total to equal total + price . price represents one item in
the groceryItemPrices as the for loop goes through each item in the array.
This pattern where we add to a variable and then resave the variable is so common, there is
an operator just for that, += : total = total + price; is the same as total += price .
54
Questions
When would you implement a for each loop?
55
For loops
Embedded Video: https://www.youtube.com/watch?v=v4TxINQBlFg?rel=0
for-each loops are great when you want to do something to each item in an array. But
other times you want to do something until a condition is met. For that we can use a for
loop.
First, let's adapt our GroceryList application to use a for loop instead of a for-each so we
can see the difference.
for-loop/GroceryList.java
public class GroceryList {
public static void main(String[] args) {
String[] myGroceryList = { "eggs", "milk", "bread", "bananas", "cereal", "rice" };
System.out.println("My grocery list:");
for ( Integer index = 0 ; index < myGroceryList.length ; index++ ) {
System.out.println( myGroceryList[index] );
}
}
}
For loops
56
5. On each loop through we find the item in myGroceryList at the current index . Let's
write an application that will tell a user what leap years occurred while they were alive.
for-loop/LeapYear.java
import java.io.Console;
public class LeapYear {
public static void main(String[] args) {
Console console = System.console();
System.out.println("What year were you born in?");
String stringBirthYear = console.readLine();
Integer birthYear = Integer.parseInt(stringBirthYear);
System.out.println("You were alive during these leap years:");
for ( Integer year = birthYear ; year < 2015 ; year++) {
if ( year % 4 == 0) {
System.out.println(year);
}
}
}
}
Here, we got the user's birth year and saved it into the birthYear variable. In our for loop
we:
1. Initialized the year variable and set it to the user's `birthYear.
2. We told the loop to stop running when year < 2015 is no longer true .
3. We told the loop to add 1 to our year variable every time we run through the loop.
In the loop, we ran the code: java if ( year % 4 == 0) { System.out.println(year); }
year % 4 is using an operator we haven't seen before, % , called modulo . It will divide the
first number by the second number and return the remainder. For every year that is
divisible by 4 , it will return 0 , making the entire statement year % 4 == 0 evaluate to
true .
Every year divisible by 4 is also a leap year, so we print it out for the user
System.out.println(year); . (There are some exceptions to this rule you'll get an exercise
For loops
57
Questions
What is the difference between a for and a for each loop?
When will a for loop stop looping?
58
While loops
So far we have learned about the different kinds of for loops. Those are useful when you
want to control how many times you want a loop to run. Sometimes, you want to run a loop
until a condition is met. For those loops, we can use the while and do-while loops. Take a
look at a couple examples:
> Integer seconds = 875;
> Integer minutes = 0;
> while (seconds > 60) {
seconds -= 60;
minutes++;
}
String.format("%d minutes and %d seconds", minutes, seconds);
java.lang.String res2 = "14 minutes and 35 seconds"
do {
minutes--;
seconds += 60;
} while (minutes > 0);
String.format("%d minutes and %d seconds", minutes, seconds);
java.lang.String res5 = "0 minutes and 875 seconds"
The while and do-while loops are essentially the same, the major difference being when
the while statement is evaluated. With the while loop, the code only runs if seconds >
60 evaluates to true .
In the do-while loop, we run the code once, and then if minutes > 0 evaluates to true ,
we end the loop. If it evaluates to false we run the code again.
We have to always be careful to give the loop the opportunity to break. If we were to run
something like this:
while (true) {
system.out.println("I'm in an infinite loop");
}
We would create an infinite loop that would run forever or crash your computer.
While loops
59