0% found this document useful (0 votes)
87 views

Python and Java

This document is a compilation of two books that teach Python and Java programming. The Python book covers introductory Python concepts like values, variables, control flow, and lists over four chapters in the first half of the document. The second half contains a book about learning Java programming in one week.

Uploaded by

adriansinisa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views

Python and Java

This document is a compilation of two books that teach Python and Java programming. The Python book covers introductory Python concepts like values, variables, control flow, and lists over four chapters in the first half of the document. The second half contains a book about learning Java programming in one week.

Uploaded by

adriansinisa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 165

Python

& Java: Learn Python and Java

Programming in One Week With Step by

Step Tutorials (Bundle)


Dr. Michael Lombard





Disclaimer

No part of this publication may be reproduced or transmitted in any
form or by any means, mechanical or electronic, including
photocopying or recording, or by any information storage and
retrieval system, or transmitted by email without permission in writing
from the publisher.
While all attempts have been made to verify the information
provided in this publication, neither the author nor the publisher
assumes any responsibility for errors, omissions, or contrary
interpretations of the subject matter herein.
This book is for entertainment purposes only. The views expressed
are those of the author alone, and should not be taken as expert
instruction or commands. The reader is responsible for his or her own
actions.
Adherence to all applicable laws and regulations, including
international, federal, state, and local governing professional
licensing, business practices, advertising, and all other aspects of
doing business in the US, Canada, or any other jurisdiction is the sole
responsibility of the purchaser or reader.
Neither the author nor the publisher assumes any responsibility or
liability whatsoever on the behalf of the purchaser or reader of these
materials.
Any perceived slight of any individual or organization is purely
unintentional.

Thanks for your purchase!
You might wonder how this book is different than the others I’ve
published.
What you’re about to read is a compilation of two books about
Python and Java so you can learn these 2 amazing programming
languages in one week. The important thing is to apply what you
learn so you can gain maximum benefits.

Happy Reading :)





Book 1

Python:

Learn Python Programming in One Week with Step-by-

Step Tutorials
Dr. Michael Lombard
Table of Contents

Introduction

Chapter 1: Python – Why and How?

Chapter 2: Values and Variables

Chapter 3: Control Flow: Booleans, Conditions, and Loops

Chapter 4: Lists and Files

Conclusion
 Copyright 2016 by ___Lulu Publishing___________________ -

All rights reserved.

The following eBook is reproduced below with the goal of providing


information that is as accurate and reliable as possible. Regardless,

purchasing this eBook can be seen as consent to the fact that both the

publisher and the author of this book are in no way experts on the

topics discussed within and that any recommendations or suggestions

that are made herein are for entertainment purposes only.

Professionals should be consulted as needed prior to undertaking any

of the action endorsed herein.

This declaration is deemed fair and valid by both the American Bar

Association and the Committee of Publishers Association and is

legally binding throughout the United States.

Furthermore, the transmission, duplication or reproduction of any of

the following work including specific information will be considered


an illegal act irrespective of if it is done electronically or in print. This

extends to creating a secondary or tertiary copy of the work or a

recorded copy and is only allowed with express written consent from

the Publisher. All additional right reserved.


The information in the following pages is broadly considered to be a

truthful and accurate account of facts and as such any inattention, use

or misuse of the information in question by the reader will render any

resulting actions solely under their purview. There are no scenarios in

which the publisher or the original author of this work can be in any

fashion deemed liable for any hardship or damages that may befall

them after undertaking information described herein.

Additionally, the information in the following pages is intended only

for informational purposes and should thus be thought of as universal.

As befitting its nature, it is presented without assurance regarding its

prolonged validity or interim quality. Trademarks that are mentioned

are done without written consent and can in no way be considered an

endorsement from the trademark holder.



Introduction

Congratulations on downloading this book and thank you for doing

so.

The following chapters will discuss Python programming and the

many caveats that you’ll have to deal with as a beginner. This book

may be paced a bit slow; it’s going to treat you as though you’ve

never programmed before and go through the pains of explaining

every concept that we encounter. One thing that Python does is leave

important details out, sometimes; this is why so many people are keen

to jump on Python as a first programming language. These details,

when left out, can be extremely helpful to programmers and make the

language easy to learn for hobbyists. However, for people who would

like to start programming seriously, these missing details can be

devastating. This book looks to ameliorate that by filling in the blanks

where Python (and the other quick-and-easy Python books) fall short.

What results is a fantastic and fast introduction to one of the most


versatile and beautiful programming languages out there.

There are plenty of books on this subject on the market, thanks again

for choosing this one! Every effort was made to ensure it is full of as

much useful information as possible, please enjoy!



Chapter 1: Python – Why and How?

So if you’re reading this book, it means that for one reason or another

you’ve decided that you want to learn how to program in Python.

That, or you’re wanting to start programming in general and you

heard that Python was one of the best places to start.

Maybe I’m wrong there. Maybe you have to learn Python for a

programming class and you’re looking for extra help. Or, maybe

you’re reading this book because you have no idea what the Python

programming language is, but you know there are a lot of books on it.

One way or another, you’ve come to just the right place. Throughout

the course of this book, we’re going to be covering all of the major

concepts that you need to know as a new Python programmer in order

to get from being absolutely new to programming in general to being

relatively adept and an able console programmer.


So, if you are one of those people that came to this book out of

curiosity towards Python (or programming in general), you may be

wondering – what is Python? What sets it apart from other similar

programming languages? Why should one learn to program, and most

importantly, why should one learn Python?


Well, let’s tackle these questions one at a time. Python is a

programming language, as I’m sure you’ve gathered. Development on

Python started in the late 1980s. Python is what’s known as a scripting

language; this means that it was developed for the easy creation of

scripts. In terms of the language itself, this meant that it was designed

to have a lot less overhead than other languages that were popular at

the time, such as C++, Java, and Haskell. Python would demand very

little of the user. This can be both a great thing and a bad thing – we’ll

get to that in a second.

Alright, let’s say that you are to stick it out through this book and

learn Python programming like a champ; what are you gaining? Well,

first off, learning to program makes you a better problem solver. All
of programming is based around the notion of looking at a situation

and then creating a solution based off of what you already know in the

situation. By training this sort of creative criticism, you’re going to be

making yourself smarter in the process!


So why should you learn Python specifically as your first

programming language? Well, there are two reasons. The first reason

is all of the things that Python offers, and the second reason is all of

the things that Python offers over other languages. We’ll tackle these

one at a time.

In terms of what Python offers, I mean that by learning Python you’ll

be able to do quite a few things. For example, Python is pretty much

everywhere. Designed to be cross-platform and “write-once, run-

anywhere”, Python code can be executed on any operating system that

can run the Python interpreter. This means that whether your end user

is running a Windows, Mac, Linux, or even a mobile operating

system, they’ll most likely be able to execute the code in question.


Python also is an extremely popular language. What this means, in

conjunction with the last part, is that you’ll find a wide array of

different utilities and frameworks that you can use with Python.

Whether you’re wanting to have a script that you run on the backend

of your webpage, to design a video game from scratch, or to develop a


fully-featured desktop application complete with a really good-

looking user interface, there is most definitely a Python API or

framework out there to help you accomplish your end goal. There are

even some more esoteric APIs and frameworks out there, if you’re

needing to do something more specialized.

The last thing to explain is why you should learn Python instead of a

language such as, say, C++ or Java. The simple reason is that it’s the

easiest to start with.

As I’ve already said, Python is a scripting language, which means that

it’s completely and entirely intended to reduce the amount of overhead

that the programmer experiences. This means less boilerplate code is

written, and more of the code will be the actual functionality of the
program. This can be both a blessing and a curse in ways that you’ll

see later, but for the places where it can be a bad thing, I make certain

to go over everything that you need to know in order for your

experience to be good one way or another and to make certain that

you aren’t walking away confused on things where Python does fall
short compared to other languages.

So in short, Python is a great beginner language because, well, it’s

easy. That’s the long and short of it. You can have a Python program

up and running in no time. Compare the two programs, the first

written in C++ and the second in Python:

C++:

#include <iostream>

using namespace std;

int main() {
cout << “hello world!\n”;

return 0;

Python:

print “hello world!\n”;

Do you see what I mean now by Python lacking boilerplate code?

There’s a massive difference between these two code samples! And in

that, you find the reason you should start off with Python – it lets you

create efficient and beautiful programs really early without

overloading you. You won’t be looking at the book trying to

memorize how to do this or that; you’ll just be programming. Easy!

So, by now I’ve sold you on Python. You may be wondering how to

get started programming and get on the ground running with all of

this! It’s very simple.

The first thing that you’re going to need to do is make certain that
Python is installed. If you’re running Mac or Linux, then it should

already be installed, actually. The way to check is to open either

Terminal or PowerShell (if you’re on Windows) and then try running

the command python.


This is the point at which it’s worth saying that if you’re not familiar

with navigating via command line, then you should do what you can

to become at least marginally familiar. That’s very far away from the

focus of this book so I’m not going to spend any time going over how

to navigate via command line. There are plenty of Google tutorials

that should acquaint you quite adequately (and more effectively than

I’d be able to!).

Anyhow, if a Python program launches, then perfect! You’ve got

Python installed. If not, then you’re going to need to install it. This is,

once more, relatively simple.

In order to install Python, you simply have to go to http://python.org,

then to the Downloads page. At this point, you may be wondering


whether we’re going to use Python 2 or Python 3; this book is going

to cover Python 2 specifically. Why? For the simple fact that almost

all legacy Python code – and almost all projects that you can work

with in order to practice your Python programming skill – are going to

be written in Python 2 as opposed to Python 3. Python 3 is, for all


intents and purposes, bleeding-edge; this can be a good thing and a

bad thing. For a new programmer, it is a bad thing. You should learn

Python 2 at first. Making the switch to Python 3 is easy enough when

the time comes that you’ll need to.

The current version of Python, as of the writing of this book, is

Python 2.7.12. You’ll need to download that version of Python and

follow the standard installation instructions in order to get it up and

running.

Once that’s done, you need to test running Python again by going to

the command line and running the python command. This time, the

program should most definitely run. If not, consider checking your

PATH variables (if on Windows) to ensure that everything is set up


correctly there for you to launch Python from the command line.

Hopefully, though, that’s not a problem and Python is now up and

running. You’re not quite ready to start cracking open Python code

yet; you need an environment in which to write it!


Technically, you can write Python in any number of different

programming environments. You could even open up good old’

Notepad and write your Python code from within there. However, I

highly discourage this. Rather, I’d recommend that you get a text

editor specifically aimed towards development and coding. There are

several free options that are all equally incredible: Atom (at

http://atom.io) and Notepad++ (at http://notepad-plus-plus.org) are

both very solid cross-platform text editors.

The primary reason for using one of these is that they offer syntax

highlighting. This helps you keep track of the various different things

in your program, such as variables and functions, by painting the text

different colors. Well, that’s the primary reason for a beginner,

anyhow.

As you come to write more and more programs, you’ll probably find

that there are a few things that you wish were more convenient or

more automatic; this is where these text editors really shine. They

both have a number of different features and add-ons (especially


Atom) that allow them to heavily automate your entire workflow.

Regardless of what you’re using, you’ll need to download and install

it so that you’ve got it on your system. Then, you’re going to need to

start a new file. Save it preemptively so that you can get the syntax

highlighting feature – save this file as “chapter1.py”, wherever you’d

like.

Within the file, you’re going to type the following:

print “Hi, this is my first Python program!”

then save the file. Head back to your command line and navigate to

the location where you saved the file. Then type the following
command:

python chapter1.py

This tells the Python interpreter to run the chapter1.py script. Within
your command line, you should see it print out the text:

Hi, this is my first Python program!

If you see that, then congrats! With that, you’ve written your first

program and executed it successfully. It can be rather daunting to

start, and there’s a lot to absorb. Don’t worry, though; I’m going to be

sure to ease you into all of the concepts as we make our way through

the book.

In the next chapter, we’re going to be learning how to store values and

manipulate them – no worries, it will be far more fun than it sounds.

Stick around, because you’re only just getting started on the path to

becoming a great Python programmer.


Chapter 2: Values and Variables

Okay, so we’re going to hit the ground running in this chapter. There

will come a lot of different times in your programming experience

where you’re going to need to keep a value or work with a value, a

value here being defined as any number of different things; the value

could be a number, it could be a set of words, it could even be whether

something is true or false. One way or another, you’re going to need

to store some kind of data. Variables are what allow you to do that.

Variables essentially offer you a storehouse for a piece of data, and

with that storehouse, you can change that piece of data however you
wish. You can add to it, you can subtract from it, you can even store

several different pieces of data inside the same storehouse and then

bring in or take out more data at will.

However, before we get into variables, it’s important to talk about

something else.

Remember at the beginning of the book when I said that sometimes,

Python can oversimplify things compared to other languages and

leave you a bit confused? This is one of those times where it’s more

than worth the time to explain the underlying computer science


concept so that you understand it.

Computers understand things, ultimately, in math. Everything,

ultimately, corresponds to a number somewhere, whether it’s a

different number, a letter, or a symbol. Even things that you wouldn’t

think involve much math – drawing a dialog box onto the screen, for

example – are actually requiring a huge amount of arithmetic on the

part of the computer.

This means that things must be codified in different ways. Computers,

under it all, are just rearranging things into 1s and 0s. So, even though

we may not see, for example, the numbers 234 and 233.9999999 as

very different at all, the computer does. They represent entirely

different things, and entirely different types of arithmetic!


This is where the idea of data types comes from. Data types are a way

of codifying the different types of values to keep the computer’s head

straight and allow it to perform the right types of arithmetic based

upon what something is.


There are many different kinds of data that computers can understand.

These are pretty much delineated, in Python at least, as the following:

Data type Meaning Example

Integer Whole numbers x = 3

Float Decimal numbers x = 3.45

String One or more characters x = “hello there”; x = “d”

Boolean True or false x = True

We’ll be working with Booleans specifically in the next chapter, but

for now we’re going to focus on the first three. There are, of course,

more, but these are all that you really need to know as a beginning

Python programmer.

So how does one create and work with Python variables? This is

pretty easy. The first thing that you’re going to need to do is create a

new file called chapter2.py in your text editor of choice.


Once you’re there, you’re going to want to type the following text:

melons = 3

That’s the first thing we’re going to do. That’s the basic structure for

creating a variable and assigning a value to it. Note here that you

aren’t restricted to assigning raw data. If, for example, you had a

function that returned a specific value, you could actually store the

result of that function to a variable without knowing exactly what that

variable was! Remember, a variable is simply a storehouse for data.

However, this is where the data types come in. If you store one sort of

data in a variable, that variable must then exclusively hold that type of

data (unless you do something called a type cast, which is, frankly,
beyond the scope of this chapter). So, look at the variable we just

created: melons = 3. We’re storing a whole number to it, so we can

presume that the variable melons is an integer.

Anyhow, moving on. Let’s prove to you that you just created a
variable. Below your lost line of code, type the following line:

print “I have %d melons!” % melons

Save the file and then try running it from the command line. It should

output the following text:

I have 3 melons!

If it does so, then perfect! You followed instructions and it turned out

alright. Now what we’re going to do is try to modify this variable.

Let’s say that our friend gave us three melons and we wanted to share

that with the world. How could we go about doing this?


The first thing that we’d want to do is adjust the value of melons by

adding 3 to it. Remember that melons just stores a value, so what

we’re trying to do is change the value of melons to be equal to the

current value of melons plus 3. This would look like so:


melons = melons + 3

However, this is rather unwieldy. There’s shorthand for these sorts of

statements. Whenever you’re typing x = x […] as a mathematical

equation, you can model it like so:

melons += 3

This is equivalent to saying “melons is melons + 3”. This applies to

any form of arithmetic, whether it were addition, subtraction,

multiplication, division, or even exponentiation (x is x to the power of

y would be x **= y).


Anyhow, let’s switch back to our code. Type the following:

melons += 3

Now we need to signal the change right below that. The way that
we’re going to do this is like so:

print “My friend gave me 3 melons! I now have %d” % melons.”

Now, if you were to save and run this, the output should be like

follows:

I have 3 melons!

My friend gave me 3 melons! I now have 6 melons.

This forms the basis of values and variables. You can create all sorts

of different variables. Let’s say that you wanted to create a custom

variable for your favorite fruit. Let’s do that below our former code.

Create a variable called favFruit which stores the name of your


favorite fruit and a variable called amountOfFruit for how much of

that fruit you have right now.

For me, this section looked like this:

favFruit = “banana”
amountOfFruit = 2

Yours will look different depending upon your answers to the

questions, obviously.

So how do we take this and announce it to the world? Well, go below

all of the code that we’ve written so far and then print the following:

print “My favorite fruit is the %s. I have %d.” % (favFruit,

amountOfFruit)

This exercise is primarily to teach you how to print out two pieces of

data at once. This may not make much sense right now – basically,

you use %s to print strings and booleans, %d to print out integers, %f


to print out floating point numbers (decimals), and %r to print out raw

value data (primarily used for debugging and testing, but we know

exactly what we’re outputting so we aren’t concerned with it right

now). What we’re outputting is called a formatted string, but that

doesn’t make too much sense to you at this point in your


programming career.

If I were to run this program as it stands, then it would output the

following to the console:

I have 3 melons!

My friend gave me 3 melons! I now have 6 melons.

My favorite fruit is the banana. I have 2.

Now, the last thing that we really have to cover in this chapter is

processing user input. How does one do this? Using the raw_input()

method. What this does is takes the text inside of the method and

prints it to the screen, then it allows the user to respond.


Remember earlier how I was saying that if a function returned a given

value, then you could store it to a variable and then manipulate that

value? Well, this function returns a string in the form of whatever the

user decides to enter, so we get to see that in action. (For the record,

functions and methods are the same thing, just different names.)

Below all that we’ve written so far, write the following code:

userFruit = raw_input(“What is your favorite fruit?\n”)

print “Wow, I love %s!” % userFruit

Then go ahead and save the program, then run it once more. It should

say everything that it has up until now, then ask what your favorite

fruit is. Enter whatever value that you’d like, then press Enter. The

computer will feed that back to you in the following line! This is

because we saved whatever the user entered to the variable userFruit.

With that, we’ve gone through almost everything necessary in this

chapter. In the next chapter we’re going to be talking about the


Boolean types that we covered briefly earlier, as well as how they

apply to your programming!


Chapter 3: Control Flow: Booleans, Conditions, and

Loops

Earlier we said we were going to talk about Booleans. Well, now’s the

time to do that. I briefly explained that Booleans are values which

hold whether something is true or false. This is really all that

Booleans are.

However, there’s a lot of power behind something so simple. In fact,

the entire idea of control flow comes from it. What is control flow?

Control flow is the primary means of controlling what your program


does and when. Your program can branch into completely different

directions depending upon certain variables and conditions, thanks to

control flow. This is what allows your program to truly take on a life

of its own and accommodate the user and the different conditions in

which the program may run. In other words, this is where the logic of

your program truly lies.


But first, we need to talk about Booleans. What defines a Boolean? A

Boolean is simply an expression. You learned about those in high

school, I’m sure. If we were to say 5 > 3, or 5 is greater than 3, it

would be true, because 5 is greater than 3. By comparison, if we were


to say 5 < 3, or 5 is less than 3, it would be false. This is because no

matter what, this statement simply isn’t true.

Booleans reflect these notions of expressions. So, you can store raw

truth or falsehood to them:

varX = True

Or you can store the result of an expression to them:

varX = 3 > 5 #would be False, because the expression is False

For the record, the thing after the hash is a comment. What this means

is that the hash and everything following isn’t read by the compiler, or
the thing which runs your program. This means that you can type

whatever you want after the hash and it won’t be noticed as part of the

code. Anyway, one way or another, these are storing whether or not

the statement referred to is true or not. This in itself isn’t explicitly

useful (yet, anyway), but the underlying concept is incredibly useful:


whether something is true, or whether it’s false.

After all, we incorporate this logic constantly into our daily behavior,

often without even realizing it! For example, let’s say that you get

your paycheck and you go to pay your bills, but you’re also wanting

to buy something off of the internet. What you might be thinking to

yourself is “if I have money left over after I pay my bills, I’ll buy that

new Playstation.” So what you’re going to do, after you pay your

bills, is check your balance. And if your balance is more than enough

to buy the Playstation, you will. If not, you won’t. The inherent logic

of this is that you’re seeing whether or not it’s true that you can buy a

Playstation.

Now, you can see that this sort of thing can be valuable in
programming: being able to make decisions based upon whether or

not something is true is foundational to all sorts of decision making

and related logic.

So before we talk about these expressions and what they mean, we


need to talk about the different ways to form expressions. After all,

just as there are a ton of different possibilities, there are a ton of

different ways to look at and compare outcomes and values.

The way that you compare two values in an expression is by use of a

comparison operator. These are as follows:

Operator Meaning Usage

== is equal to x == y

!= is not equal to x != y

< less than x < y

> greater than x > y

<= less than or equalx <= y

>= grtr than or equal x >= y


Note the massive difference between the assignment operator = and

the comparison operator ==. The first gives a variable a value, while

the second compares the two values to see if they’re equal to one

another. This difference is colossal, and can really mess your program
up if you get the two confused.

So now, what can we do with this? Well, the first thing that we can do

is compare two values and make a decision. The way that you’d do

this is with something known as an if statement. Let’s say that we had

a variable x, containing the value of 6, and a variable y, containing the

value of 8, and we wanted to establish something that would happen if

the value of x was greater than the value of y.

The syntax for setting up an if statement in Python is like so:

if condition:

code goes here


The indentation is very important; indentation controls program flow

to the Python interpreter, and having the wrong indentation means that

your program will function incorrectly. Anyhow, let’s throw use this

syntax in order to define our variables and create an if statement. If

the variable x is greater than y, then we want to print out that x is


greater than y. Create a new file and call it chapter3.py. In this file,

you’re going to want to type the following:

x = 6

y = 8

if x > y: # if x is greater than y, then do the following

print “If x is greater than y”

Now, if you tried to save and then run this, nothing would happen.

This is because the program is checking to see if the expression x > y

is true before doing what the if statement says.

This is what I like to call a potential conditional. This conditional


doesn’t have to execute and it is not guaranteed to run in any way,

shape, or form. This has its own uses and utilities which you’ll

discover naturally. There will be times where you want code to

execute if one given condition is true, but not at all if that condition

isn’t met.

But right now isn’t one of those times. Right now, we’re not learning

anything about the program or the variables that we’ve got. So how

can we change that? Well, we need to change it to be an absolute

conditional. We do this by adding a catch block by way of using an

else statement.

Else statements are statements that you can put after your if statement.

These statements will execute whenever the condition mentioned in

the if statement is not true. This means that no matter what, some of

the code will execute.

Go to the code that we’ve written so far and right below it, add in the

following:

else:

print “X is less than Y.”

Now, save this and run it. What it will do is check to see whether X is
greater than Y in accordance with the first conditional statement.

When it finds that this isn’t true, it will go automatically to the second

half of the statement, the else statement. This will occur anytime that

the condition of the if statement isn’t true.

It should end up printing the following to the console:

X is less than Y.

Fantastic! However, I’m sure you’ve noticed, there’s one essential part

of this that we’ve left out – what if X is neither less than nor greater

than y? What if it is, for example, equal to Y? As it stands, if x simply

wasn’t greater than y, it would print out x is less than y no matter

what, regardless of whether x and y were equal to one another. What


we need to do here is add yet another condition testing for this. The

way we do this is with an if else statement.

Between your if statement and your else statement, type the

following:
elif x == y:

print “X and Y are equal.”

By the end, your entire conditional block should look like this:

if x > y:

print “X is greater than Y.”

elif x == y:

print “X and Y are equal.”

else:

print “X is less than Y.”

Now we’ve provided for the situation that x and y are equivalent to

one another.

With that, you’ve learned one of the first major building blocks of

control flow: conditionals. However, there is one other extremely

important aspect of understanding the order and layout of your

program: loops.

Loops and loop logic find their way into our lives a lot more than we

realize. Take, for example, counting out loud from 1 to 10. Maybe it

doesn’t seem obvious at first that such an action is happening in a

loop, since the number is changing each time. However, in reality,

there are distinct sets of actions that are happening every time you

move to the next number. For example, in your head, you

subconsciously add one to the number; you shape your mouth and say

the word in your brain; and so on and so forth.

The simple fact is that loops are incredibly prevalent in a lot of our

thinking and a lot of your programs will invariably use loops.

There are two different kinds of loops in Python, and unlike languages
which are similar to Python, there’s quite a bit of differentiation in

their purpose in Python specifically. This may come as a shock to

somebody who is used to programming in, for example, Java, where

sometimes while loops and for loops are interchangeable.


First, we’ll cover while loops. The intent of a while loop is simple. All

that it does is check a condition which is declared at the same time as

the while loop. For as long as that condition is true, the loop will

continue to execute.

Let’s say that we wanted to have a while loop that counted from 1 to

10. This is roughly how we would implement such a thing:

i = 1

while i <= 10:

print i

i += 1


When i was no longer less than or equal to 10, the loop would

automatically exit. As you can see, while loops are extremely simple

to set up.

While loops are most often implemented as something called a game


loop. What this does is provide a way for a certain set of code to loop

over and over until a certain condition is met. For example, if you

were writing a blackjack game in the console, obviously you’d want

cards to be dealt and turns to be taken until somebody had lost the

game, which would terminate the game.

The way to implement this sort of thing would be to have a Boolean

variable called noWinner, or something along those lines. It would be

set to True. One would then set up a while loop where the condition

was noWinner being true. The loop in question would then execute for

as long as the variable noWinner was true. When a certain win

condition was met – for example, one player breaking 21 and then

rendering the other player the winner – the variable noWinner would

be set to false, thus breaking out of the loop. This logic most
obviously applies to games, but there are a great many times where

some sort of mechanism similar to this one will be incredibly useful to

you. Therefore, keep it in mind while you’re learning to program.

The other loop in Python is known as a for loop. For loops serve a
specific purpose which will make a lot more sense in the next chapter.

Essentially, the Python for loop is intended to iterate over a list. What

this means is that the Python for loop is meant to go over every

element within a given set of different values and then act

accordingly.

As I said, this will make more sense in the following chapter, but for

now, bear with me.

For now, I’m just going to show you how the syntax of the for loop

works:

for iterator in collection:

do this

“Iterator” means the current instance of the variable which is being

iterated. This is a little of a tricky concept to explain concisely.

Roughly what this means is that the iterator is a direct copy of the

current object o in collection c. Let’s say that collection c contains 5


different objects, o1, o2, o3, and so on. On the first iteration of the

loop, iterator i would be a direct copy of o1; upon completion of the

loop, iterator i then becomes a direct copy of o2. Therefore, the same

logic can be applied upon iterator i throughout the loop, and that logic

would be happening to every single object within the collection.

The simplest way to show this is much like with the while loop:

simply counting from 1 to 10. In order to create a collection of

different numbers, Python has a really useful function: the range()

function. If you were to type:

range(1, 10)

It would create a collection with every number from 1 to 10 as a

different object in the collection. Now, let’s apply this to our loop:

for number in range(1,10):

print number

Note here that the iterator is just the variable name; this could be
“number”, this could be “i”, it can really be anything. The key thing to

remember is that this is the iterator variable which moves through the

collection.

This would print out every number from 1 to 10.

Now, on the tricky subject of lists, we’re going to be getting into those

and file handling in the next chapter, where we delve into these rather

difficult topics in greater depth.


Chapter 4: Lists and Files

Last chapter probably summarily confused you about lists. This

chapter is meant to undo some of that fog. The ultimate goal of this

chapter is to teach you about exporting and importing files, but in

order to do that, we really have to talk about lists first, because files

are generally imported as lists of strings.

So let’s start from there: what are lists exactly? As I’ve already stated,

lists are just collections of objects. Lists can be single-type

(containing only one type, such as only integer or string values) or

multi-type (containing objects of many different types).

Essentially, let’s think of it like this: imagine you’re a teacher trying to

keep up with some grades for three students: Tommy, Lara, and

Milton. With what we know so far, you’d likely do it like so:

TommyAssignment1Grade = 79
LaraAssignment1Grade = 80

MiltonAssignment1Grade = 92

TommyAssignment2Grade = 95

LaraAssignment2Grade = 98

MiltonAssignment2Grade = 24
[…]

You can see almost immediately why this is inefficient and just

generally not a good idea. So how can we go about doing this better?

Well, luckily, there’s a way, and it’s called lists. You’re able to group

these values together using lists.

TommyGrades = [79, 95]

LaraGrades = [80, 98]

MiltonGrades = [92, 24]

You can also declare empty lists, like so:


emptyListExample = []

Lists are great, because they’re really easy to work with and set up. If

you want to add to a list, all that you do is use the append method.

Let’s say the kids finished another assignment, and Tommy scored a
93. You could add the 93 to his grades like so:

TommyGrades.append(93)

You can also work with the objects in a list, called elements directly.

You reference these items in the list by way of their index, or their

place in the list. The reason why is a little beyond the scope of this

book, but the thing to remember about this is that computers start

counting from 0. So if we were to take our TommyGrades list

containing 79, 95, and 93, and we wanted to pull the second number

out of it, we’d have to refer to it by its index:

print tommyGrades[1]


The computer would see this like so:

tommyGrades

[0] [1] [2]

79 95 93

And would thus pull the second item out of the list from index 1.

Deleting things from lists is easy as well. All that you do is use the del

keyword, like so:

del tommyGrades[2]

This would remove the item at index2 from the list tommyGrades.

Now, if instead we wanted to delete something from the middle of the

list, then all of the items ahead of it in terms of index would move

back by one index position. In other words, it cleans itself up

perfectly.


Fortunately, those are the trickiest things about lists, and they’re also

the most foundational things about them. It takes a fair bit of practice

to really get in the groove of using lists, but it’s not too hard once you

really get going with it, and it can massively simplify a lot of the

programming that you’ll be doing. After a while, they’ll become your


best friend.

Now it’s time to move on to the harder part of the chapter: file input

and output. Fortunately, even though it’s the harder part of the chapter,

Python still makes file input and output far easier than it would be in a

lot of other languages. There are plenty of different examples of

where file input and output would be useful, but the most obvious

example is something like Microsoft Word, where you save and load

documents. That, or maybe a program has something like customized

user settings that are loaded each time. One way or another, the point

is that there are many cases where you’re going to need to load data,

and probably save it as well.

The main method with file input and output is the open method. This
allows you to deal with a specific file, either creating it, reading from

it, or appending to it.

Here’s how you’d use it in general:


f = open(“fileExample.txt”, ‘r’)

When you do this, the variable f becomes a workable instance of the

file object, which directly references the file fileExample.txt. This is

the simplest way to open a file.

The r indicates that we only intend to read the file that we’re opening.

If you were to put a w instead of an r, it would indicate that we’re

wanting to write to the file using the file.write() method. This would

overwrite any existing files with the same name and replacing them

with the new one you’re creating, so it’s not wise to use this unless

you know exactly what it is that you’re wanting to do on the file

system. Typing r+ would open read and write mode, which allows

both to happen but requires that you go to the exact place in the file
where you’re wanting to add or read from. In other words, you control

the cursor entirely in this mode. The last one is a, or append mode.

This opens an exist file in order to write more to it. This also takes

you directly to the end of the file.


Exactly which read/write specification you need will really depend

upon what you’re trying to do. If you don’t specific a read/write mode

at all, the default will be mode r.

When you’re trying to read a file, you’ll be primarily using file.read()

and file.readline(). The first allows you to specify a certain number of

bytes for it to read from the file. If you don’t, then it will just read

over the whole file and then return the whole file as a string. The

second one will return the current line of the file up until the next line

break.

As I’ve already said, if you’re only writing to a file, then

file.write(“string goes here”) is the primary method that you’ll be

using in order to add text to the given file.


Now, let’s say that you wanted to iterate through every line on a file

and then feed it into a list.

Maybe you have a file called vegetables.txt, and it contained the


following:

Carrot

Eggplant

Celery

Cabbage

Lettuce

Onion

In your Python program, you would create an empty list called

vegetables.

vegetables = []


Then you’d open the file:

f = open(“vegetables.txt”, ‘r’)

Next, we’d iterate through the file line by line by way of a for loop
and add each line to our list of vegetables:

for lines in f:

vegetables.append(lines)

Finally, we have to close the file that we opened. This is just good

practice, never forget to do this. On bigger projects it could cause

major issues or even corrupt files.

f.close()

Then, if we wanted to, we could print out our whole list to be sure that

everything transferred over fine:


for vegetable in vegetables:

print vegetable

In the end our code would look a bit like this:


vegetables = []

f = open(“vegetables.txt”, ‘r’)

for lines in f:

vegetables.append(lines)

f.close()

for vegetable in vegetables:

print vegetable

So with that, you know quite a bit about the extremely useful concept

of file input and output.


Conclusion

Thank for making it through to the end of this book, let’s hope it was

informative and able to provide you with all of the tools you need to

achieve your goals whatever they may be.

The next step is to venture out. This book only covered the very basics

about Python programming. There’s an entire world of super cool

things for you to learn about this language.

One of the best things that you can do in order to become a better and

more experienced programmer is to go and start working on other

people’s projects. There are a ton of major open source Python

projects out there that you can look into in order to bolster your skill

and become a much better Python programmer, as well as to examine

other people’s practices. It will be a little overwhelming at first,

especially because Python programmers are known for their habit of

making code as succinct as possible, but you’ll pick up more and


more as you go on and you learn more about the language in general.

Another thing that I highly advise doing is to start working on

something that you care about. A great example is video games. I

remember when I had just started programming, I found it difficult to


pick up some key programming concepts. The reason I was

programming in the first place was because I wanted to become a

game developer and produce something that people would love. Once

I knew the very basics of programming, like variables and loops, I

started looking into tutorials for creating video games. It was at that

point that I really started to learn a lot, because I was massively

interested in the subject matter that I was learning in the first place.

People always learn better and more efficiently when they care about

what they’re learning on some level or another. This applies to

programming as much, if not more, than anything else.

In the end, I just really hope that I’ve helped you get on the right path

to becoming a great Python programmer and that I’ve explained some

harsh concepts that may otherwise really confuse you. Starting out as
a programmer can be a very rough course, and it can become really

overwhelming really quickly. The entire purpose of the book is to

teach you the underlying concepts to all of the different foreign

concepts you’re encountering so that they aren’t so intimidating.


To that end, I really hope I’ve succeeded. If I have and this book

ended up helping you in your quest to becoming a fantastic Python

programmer, then I’d very much appreciate it if you’d leave me a

review on Amazon.

Before I sign off on this book, I’d just like to say once more that I

really hope you meet your goal of becoming the best Python

programmer that you can be, and I wish you the best of luck on that

journey!

Book 2

Java: Learn Java Programming in One Week


with Step By Step Tutorials

Dr. Michael Lombard

Table of Contents:

What is Java? 2

Environment Setup 2

Printing “Hello, World!” 3

Basic Data Types(int, double, char, Boolean, String) 3

Logical Operators(!,&&,||) 9

Other data types(long, short,float,byte) 11

Bitwise Operators(&, |) 12

IF ELSE 13

IF ELSE IF 13

SWITCH 14
Input From Console 15

The While Loop 15

The Do While Loop 17

The For Loop 17

Strings 18

Arrays 20

Calculator 21

Modifier Types 22

Methods 23

Object-Oriented Programming 24

Flower Shop 32

GUI 37

Flower Shop GUI 40

AWT Paint 43

Conclusion 44

 Copyright 2016 by ___Lulu Publishing___________________ -

All rights reserved.


The following eBook is reproduced below with the goal of providing

information that is as accurate and reliable as possible. Regardless,

purchasing this eBook can be seen as consent to the fact that both the

publisher and the author of this book are in no way experts on the
topics discussed within and that any recommendations or suggestions

that are made herein are for entertainment purposes only.

Professionals should be consulted as needed prior to undertaking any

of the action endorsed herein.

This declaration is deemed fair and valid by both the American Bar

Association and the Committee of Publishers Association and is

legally binding throughout the United States.

Furthermore, the transmission, duplication or reproduction of any of

the following work including specific information will be considered

an illegal act irrespective of if it is done electronically or in print. This

extends to creating a secondary or tertiary copy of the work or a

recorded copy and is only allowed with express written consent from
the Publisher. All additional right reserved.

The information in the following pages is broadly considered to be a

truthful and accurate account of facts and as such any inattention, use

or misuse of the information in question by the reader will render any


resulting actions solely under their purview. There are no scenarios in

which the publisher or the original author of this work can be in any

fashion deemed liable for any hardship or damages that may befall

them after undertaking information described herein.

Additionally, the information in the following pages is intended only

for informational purposes and should thus be thought of as universal.

As befitting its nature, it is presented without assurance regarding its

prolonged validity or interim quality. Trademarks that are mentioned

are done without written consent and can in no way be considered an

endorsement from the trademark holder.


What is Java?


The java language is a programming language developed by Sun

Microsystems and officially released in 1995. It is a compiled language, thus it’s

platform-independent, which means it runs on multiple platforms, including

Windows, Linux, and Unix. It achieves this by compiling into “byte-code”, that

is then interpreted (translated) into Machine-Code at the given computer, which


can be read directly by the processor.

The fact that java is “High-Level” means that it’s designed in a way that is

much easier to read and work with than “Low-Level” languages, thanks to this,

it’s security features and relatively high performance, it has become the most

popular language in the world.

Java is also Object Oriented, which means that everything (or almost
everything) in the language is an object, which means that everything can store a

series of organized values. We will go over exactly what “Object Oriented


Programming” is later in this course.


Environment Setup

When working with a programming language, in order to avoid manually

compiling programs through the terminal, we use IDE’s, or Integrated

Development Environment’s, which essentially just means it will allow you to


do actions with buttons, and not terminal commands.


For this tutorial we will use Eclipse, as it’s free, intuitive, and has a rich

selection of plugins and features.

For starters install and set up the Java JDK at

http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-

138363.html.


Then, go to https://www.eclipse.org/downloads/ and download the latest

version of eclipse(Make sure you download JavaSE), after you have installed it
and got it open, you will see a “Select Workspace” window, a Workspace is a
Folder located on you Computer that contains all the files needed for creating a

java application. You can select virtually any space on your computer.

After you have created your workspace, you will see “Eclipse Welcome”
page, you can go ahead and close it, here you go to file -> new -> Java Project (if
you don't see it, try other -> Java -> Java Project). Here, under “Project Name”
input any name you like, for simplicities sake let’s name it “prj1”, under “Use an

execution environment” make sure you have

Java SE-(version number) selected. Leave everything else as is, and click
“Finish”.


You can now go to file -> new -> class, here, enter any class name you

like, lets name it “cls1” for now, and check ”public static void main(String[]

args)”. We will go over exactly what all this means later in the course.

After this, go to window -> show view -> package explorer. This will give

you an outline of our files, there you should see the “prj1” project that we

created, inside it, under “src” -> default package you should see the “cls1” class
that we created. If it’s code isn't already open, go ahead and double click it, this

will open the code for our class. Here we could start creating our program! This

may seem complicated at first, but after doing this 5-6 times, it’ll naturally
become practically automatic.

Printing “Hello, World!”

When learning a new language, it’s become a tradition to show students


how to print “Hello, World!” to the screen first. In Java, it’s quite simple,


public class cls1 {

public static void main(String[] args) {

System.out.println("Hello, World!");
}

}
At this point, you might be asking yourself, “What in the world is System?

What is out?what is println()?”

Well, “System” is a built in class, out is an Object that can output text to

the screen, and “println” is a method in the out class, that outputs the text.

“main” is also a method that, in accordance with tradition, is executed when we

launch a program. All of this may seem overwhelming, what in the world is a
method, right? Well, all of this will be covered later in this course.


To run this program, we simply go to run -> run(or click the horizontal
triangle above the document), which will open a console that will contain the

text “Hello, World!” and there we go, we have successfully created a java
program.


Remember: Java is CASE-SENSITIVE, which means that everything must
be written exactly the same.

Basic Data Types(int, double, char, Boolean, String)

In java, just as with any programming language, we have types of data that

we can create and work with. The most basic of these is called an Integer, or int

for short. An Integer is a very simple data type, you can just think of it as any

whole number. Be it negative or positive. It is important to note that the

maximum number it can hold is 2,147,483,647, and the smallest is

-2,147,483,647, we will go over why exactly it can’t hold higher/lower values in

Bitwise operators and other data types later in this course.

Let's get into exactly how to create Integers and what we could do with

them.
public class cls1 {

public static void main(String[] args) {


int i;

i = 1;
System.out.println(i);


}
}
In the code above, we are declaring a new int I:

int i;


And then we are assigning the value 1 to i, which just means we make i

equal to 1, thus the equal sign.


i = 1;

Then we are printing i to the console, thats right, the System.out.println()

method can print Integers too, in fact, it can print any of the data types that we

go over in this chapter.


System.out.println(i);

If you run that program, you will get 1 printed to your console. We can

assign values to an Integer multiple times, and the last one that you assign to it
is will be what it will be equal to:


public class cls1 {

public static void main(String[] args) {


int i = 1;

i = 5;
System.out.println(i);

Here, we are simultaneously declaring and assign i’s value to 1, then


assign 5 to 1. This program will output 5 to the console, as the last value we

have assigned to it is 5. With integers, we can create whole numbers that we can

then use to do math. Exciting.

But doing math with just whole numbers is kind of useless. What if we

wanted to assign 1.5 to an int? Well we cant, it will give us an error, but we can

use a double to hold that value, a double is like an integer, but it can hold values
with a decimal point, and not just whole numbers. It also has a limit as to how

much we can assign to it, but the max and min value is a bit more complicated,

around 1.8 × 10^308.


Computers are generally pretty bad at decimals, so there will be possible


losses of precision at values around .00000000000001, thus they should never be

used to work with things like money. But don't worry about it for now, we will
mostly be working with values that have less numbers.


So how do we create doubles? Well, just like Integers:

public class cls1 {

public static void main(String[] args) {


double d = 1.5;

System.out.println(d);
}

The output of this program will be “1.5”. So thats how we can create

doubles.

You might have heard that computers work with only 0’s and 1’s, or true
and false. Well we have a data type that can only store true or false values. it’s

called a boolean. It really can just hold true or false, we will see what we can do

with it in the chapter if.


public class cls1 {


public static void main(String[] args) {

boolean b = true;
boolean b1 = false;

System.out.println(b);
System.out.println(b1);
}

The program above will output “true” and on the next line “false” to the
console. And thats how we create a boolean!


We went over Integers, doubles, and booleans. But what is we wanted to

print a character? Well we would do just that. The Character, or char for short,

data type holds a character. Pretty simple!

public class cls1 {

public static void main(String[] args) {

char c = ‘t’;
System.out.println(c);

}
The above program will print “t” to the screen. It is important to note that a

char can only hold one letter. But what is we want to print a word?

The String data type is the first complex data type, which essentially
means it is made up of basic data types, in it’s case, it’s made up of a collection

of chars. We already used Strings when we printed “Hello, World!” to the screen.
Now let’s do the same thing, except this time create the String ahead of time:

public class cls1 {

public static void main(String[] args) {


String s = “Hello, World!”;

System.out.println(s);
}

This will output “Hello, World!” to the console. Finally, theres a very

useful operator that we can use with Strings called the + operator, which allows

us to combine 2 Strings together:


public class cls1 {

public static void main(String[] args) {

String s = “Hello, ” + “World!”;


String s1 = “Hello, ”;

String s2 = “World!”;

String s3 = s1 + s2;

System.out.println(s);
System.out.println(s3);

The code above will output “Hello, World!” and “Hello, World!” under

that. That’s because we first create a String that adds “Hello, ” + “World!”

together, and then 2 separate Strings that contain “Hello, ” and “World!”, then

we create a new String s3 that adds s1 and s2 together, and thus will contain

“Hello, World!”. This is one of many operators in the Java language, which leads

us into the next Chapter.

Arithmetic Operators(+,-,*,/,%,++,--)

Arithmetic operators are operators of the java language that essentially do


math. They are:


+ for adding

- for subtracting
* for multiplying
/ for dividing
% for modulus
++ increment

— de-increment


Lets take a look at a block of code that utilizes all these operators with

Integers

class cls1 {

public static void main (String[] args) {

int i1 = 4;
int i2 = i1;

int i3 = i2;

int i4 = i3;

int i5 = i4;

int i6 = i5;
int i7 = i6;


i1 = i1+1; //Add 1

i2 = i2-1; //Subtract 1
i3 = i3 * 2; //Multiply by 2

i4 = i4 / 2; //Divide by 2
i5 = i5%3; //Get the modulus of 3
i6++; //increment by 1
i7--; //decrement by 1

String results = i1+","+i2+","+i3+","+i4+","+i5+","+i6+","+i7;



System.out.println(results);

Thats a pretty big code! The output we get will be: “5,3,8,2,1,5,3”. Now

let’s go over why we get that output.

In the first 7 lines of our code, we are declaring 7 integers, and giving all
of them the value 4. Since i1 has the value 4, when we say int i2 = i1, we are

saying the same thing as int i2 = 4. Then we do the same for i3, and so on:
int i1 = 4;

int i2 = i1;
int i3 = i2;

int i4 = i3;
int i5 = i4;
int i6 = i5;
int i7 = i6;

In the next line of our code, we put the value “i1 + 1” into i1. So, since
4+1=5, i1 will now be equal to 5.

i1 = i1+1; //Add 1

At this point you might be asking what is that after the “//” well, thats a

comment, a comment is quite simple, it is merely text that the computer will

ignore when executing out program. We can use them to explain what a certain

piece of code does, so that other people in the future could more easily

understand our program, and work on it. Commenting is important, as the best

software engineers are also the best commenters.


Our next line of code does pretty much the same thing as the first, but it

subtracts instead of adds. So, since 4-1 = 3, i2 will now be equal to 3:


i2 = i2-1; //Subtract 1

Operator 3, * simply multiplies two numbers together, so since 4 * 2 = 8,


i3 will now be equal to 8:


i3 = i3 * 2; //Multiply by 2
The next operator simple divides any numbers, so since 4 / 2 = 2, i4 will

be equal to 2. It’s important to note that since we are working with Integers, if

we were to divide 5 / 2, and put the result in i4, then i4 = 2, since Integers cant
hold decimals, it will always round down to the nearest whole value:


i4 = i4 / 2; //Divide by 2

The Modulus operator simply returns the remainder of a division. So when

we divide 4 by 3 we get 1 (3 goes into 4 one time) and remainder 1(1 is left

over), well the modulus operator returns a 1, thus i5 will be equal to one:

i5 = i5%3; //Get the modulus of 3


The increment operator is pretty simple, it just adds 1 to our value, so 4++

is the same as 4 + 1, thus this line of code will set i6’s value to 5:

i6++; //increment by 1

The decrement operator does just what the increment operator does, except
it subtracts one from a value, so when we do i7-- , we are just subtracting 1 from

i7, thus it’s value will be 3, as 4-1 = 3:



i7--; //decrement by 1

And those are the arithmetic operators! Now let’s take a look at our next

line, here we create a new String, and assign it first as the String value of r1, and
add an ‘,’. After that, we add r2 to the String, and so on.


String results = i1+","+i2+","+i3+","+i4+","+i5+","+i6+","+i7;

Then we print the String, and in result we get the values of each Integer,

separated by a comma:

“5,3,8,2,1,5,3”

Relational Operators(==,<=,!=,>=,>,<)

The relational operators always return a boolean, let’s take a look

at another code that utilizes every single Relational Operator:

class cls1 {

public static void main(String[] args) {


System.out.println(1 < 2);
System.out.println(1 > 2);
System.out.println(1 == 2);

System.out.println(1 <= 1);

System.out.println(1 >= 1);


System.out.println(1 != 1);

The code above will produce the following result:


true

false

false
true

true
false

Let’s break this down, ‘<’ is the operator for less than, since (1 < 2) is true,
it will return true, and will print “true” to the console. But (1 < 1) will return

false.

‘>’ is the operator for more than, since (1 > 2) is false, it will return false,
and will print “false” to the console.(1 > 1) will also return false.

‘==’ is the operator for equal to, since (1 == 2) is false, it will return false,
and will print “false” to the console.


‘<=’ is the operator for less than or equal to, since (1 <= 1) is true, it will

return true, and will print “true” to the console.

‘>=’ is the operator for more than or equal to, since (1 >= 1) is true, it will

return true, and will print “true” to the console.

‘>’ is the operator for more than, since (1 > 2) is false, it will return false,
and will print “false” to the console.(1 > 1) will also return false.

‘!=’ is the operator for not equal to, so since (1 != 1) is false, it will return

false, and will print “false” to the console.(1 != 2) will return true.

And those are the relational operators! Now let’s take a look at Logical
Operators.

Logical Operators(!,&&,||)


Logical Operators, like Relational Operators return a boolean. The AND

Operator takes two booleans as input, and returns one boolean as input, which

will be true if and only if both inputted booleans are true. Let’s see an example:

class cls1 {

public static void main(String[] args) {


System.out.println(true && false);

System.out.println(true && true);

The output of this code will be:


false

true

In the first line, we get true and false as input, and since we have a false in
there, it will return false. But in the second line, we get true and true as input,
and in result we get true as output, and print true. So this the the and operator.


The OR operator, ‘||’ is pretty simple as well, let’s take a look at the same

code except with the OR operator:



class cls1 {
public static void main(String[] args) {

System.out.println(true || false);

System.out.println(true || true);
System.out.println(false || false);

The output of this code will be:

true

true
false

So the OR operator will return true if one or more than one of its inputs are

true. We could also go ahead and use multiple inputs:


class cls1 {
public static void main(String[] args) {

System.out.println(false || (false && true));


}
}

The above code will output “false” because (false && true) returns false,

and (false || false) will return false. Notice here how we added parentheses
around the second logical operation, this means it will be done first, if we didn't

have that there, it would we done left to right.


Our final logical operator, ! is called the not operator, it simple reverses

whatever boolean we after it. Let’s look at an example:

class cls1 {

public static void main(String[] args) {

System.out.println(!false);

The output of that code will be true, because false reversed is equal to true,
pretty simple! We can put combinations of logical operators together, as many as

we want. And remember, that will work with any boolean, including ones we
have created ahead of time:


class cls1 {
public static void main(String[] args) {

boolean b = !false;

System.out.println(b && !b);


}
}

The output of the following code will be false, as b is true, and true AND

false is false. And those are logical operators!

Other data types(long, short,float,byte)

You might have heard that in computers, everything is don't in 0’s and 1’s.

But what does that mean? It means that it stores number in a Binary data system,

it is also called base2, it is fairly simple, as our number system is called decimal,

or base10. In base 10, we have 10 numbers: 0,1,2,3,4,5,6,7,8,9, thus the 10 in

base10. But in Binary, or base2 we only have 2 numbers, 0 and 1(which then

correspond to on and of in the processor).


In decimal, say in the number 345, we are saying that we have 5 ones, 4
tens and 3 hundredths.

In base2, in the number 111, we have 1 one, 1 two, and one four. Thus the

number (converted to decimal) will be 7. We can represent any number in


binary(except decimal-point numbers, which is why computers usually have

trouble with decimal points).


Integers, in Java are made up of 31(well, 32 but the first one is used to say

whether the number is positive to negative, as with every number data type)

numbers(or bits), which means that the maximum number we can have is:

1111111111111111111111111111111


Which, converted to decimal is 2,147,483,647. Thats why it cant hold

higher values! But what if we wanted to hold higher values? Well, we have a

data type called long, which can hold 63 numbers(bits). That means it’s highest
value is 9,223,372,036,854,775,807. We also have a short data type, which has

15 bits, and it’s highest value is 32,767. And finally we have a byte data type
that holds 7 bits, which can hold a max value of 127.


We can find their max and min values in java by using the following code:

class cls1 {
public static void main(String[] args) {
System.out.println(Byte.MAX_VALUE);

System.out.println(Byte.MIN_VALUE);

System.out.println(Short.MAX_VALUE);
System.out.println(Short.MIN_VALUE);

System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);

System.out.println(Long.MAX_VALUE);

System.out.println(Long.MIN_VALUE);


A float is just like a double, but can hold about half the max value of a

double. float’s are pretty simple, so theres really no point on going over them in

more detail.

Bitwise Operators(&, |)

There are a total of 7 bitwise operators in Java, but for this course we are
only going to look at 2 of them, if you understand these two, understanding the

rest will be pretty easy to do.

The bitwise and operator or & operator is not to be confused with &&, &&

takes 2 booleans as input, & takes 2 Numbers as input.

Let’s look at an example:

byte b = 1001010 & 1000000;

System.out.println(b);

The output of this will be 1000000, because it is the only value the is 1 in

both integer. Note here that this isn't code, as i wrote there to integers in binary,

while java will read them as decimal. So if we have (1 & 1), it will give us 1. (1
& 0) will give us 0, and (0 & 0 will give us 0).


The | (bitwise or) operator or just like the bitwise and operator, but it or’s

values instead of ands them, so (1 & 1) will give us 1, (1 & 0) will give us 1. (0
& 0) will give us 0.

Bitwise operators, like the “other data types”, are usually used in
professional applications where speed and file size can save or lose a company
thousands or even millions of dollars, so for now if you don't fully understand
them don't worry.

IF

The if statement consists of 2 parts, one that takes in a boolean as input,

and one that tells that program what to execute. Let’s look at an example:

class cls1 {

public static void main(String[] args) {


if(10 > 2) {

System.out.println("10 is more than 2");


}
}


In the if statement above, it takes in a comparative operator as input(which

returns a boolean) and if the inputed boolean is true, it will execute what is
between the brackets. In this case, 10 is less than 2, so it will print “10 is more
than 2” to the screen. The if statement is arguably the most useful statement
there is in Java.

It’s important to note that you could have if statements inside if statements,
with as many levels as you want. Ifception.

IF ELSE

In the case that the boolean that is inputed into an if statement is false, it

will move onto the rest of the code, unless we add an else statement, that is.

Let’s look an an example:

class cls1 {

public static void main(String[] args) {


if(10 < 2) {

System.out.println("10 is less than 2");


} else {

System.out.println("10 is not less than 2");


}

}
}

In the code above, we will get "10 is not less than 2” as output, since 10 is

not less than 2, the inputed boolean will return false, and as such it will execute
whatever is in the else statement. If the input would be true, it would execute

what is in-between the brackets of of the if statement, and ignore the else
statement.

IF ELSE IF

We could also add multiple if statements, that will check multiple booleans

and execute different actions based on which boolean is true. Let’s look at an

example:

class cls1 {
public static void main(String[] args) {

if(10 < 10) {


System.out.println("10 is less than 10");

} else if(10 > 10) {


System.out.println("10 is more than 10");
} else if (10 == 10) {

System.out.println("10 is equal to 10");


}

The code above will first check whether 10 is less than 10, since it is not, it
will check the next else if statement, whether 10 is more than 10, since it is false,

it will move on to check whether or not 10 is equal to 10, and since it is true, it

will execute what is between the brackets of the final if else statement, and as

such will print "10 is equal to 10” to the console. Note here that we can add as

many else if statements as we want, we can even ad an else statement at the end

of that code, if we wanted. But we can have only 1 else statement.

SWITCH

The switch statement is used when we need to check whether weather a

value is equal to many other values. The switch statement takes in a value, not a

boolean. Let’s take a look at an example:

class cls1 {
public static void main(String[] args) {
int number = 4;

switch (number) {

case 1:
System.out.println("The number is 1");

break;
case 2:

System.out.println("The number is 2");

break;

case 3:

System.out.println("The number is 3");

break;

case 4:
System.out.println("The number is 4");

break;

case 5:
System.out.println("The number is 5");

break;
default:

System.out.println("The number is not 1-5");


}


}
}

In the switch statement, we input a value into the parentheses(in this case
we input the integer 4), then we use the case keyword to check whether the value

is equal to certain other values, it’s not equal to case 1, so we check case 2, then
case 3, until we get to case 4, and since it is equal to 4, it will print "The number

is 4”. Then we add a break keyword, otherwise it would continue execution and

print "The number is 5” and then "The number is not 1-5”. The break keyword

will stop the execution of a switch statement. We also have the default keyword

which will execute if no cases match the inputted value.

Input From Console

Before this, we always manually assigned values to our integers, but what

if we wanted to get input from the console(where we usually print things)? Well,

we would use the Scanner class. Remember how we created a class in order to

use eclipse and type code? Well, Scanner is just that, it is a class that the creators

of java created precisely for getting input form the console.


To use this class, we have to import it, which just means we have to tell
Java that we are going t use it. Doing it is pretty simple, just type:

import java.util.Scanner;

above where you declare your class, and you can now create a new

Scanner object. Let’s take a look at an example code:

import java.util.Scanner;

class cls1 {

public static void main(String[] args) {

Scanner sc;
sc; = new Scanner(System.in);

int f = sc.nextInt();
System.out.println(f+1);

}
}

Notice how we declare a scanner just like a data type, but when we assign
it a value, we say new Scanner(System.in)which just says that it is a new
Scanner, and that it will receive input from System.in. Remember how when we
want to OUTput something we call System.out? Well to get INput we assign

System.in. Pretty Logical.


In the code above, we declare a new scanner, assign it the value of a new

Scanner, and tell it to get input from system.in, and then declare a new Integer f,
and assign a value of the next integer that is inputed from the console. Then we

print f+1.

If you run this program nothing will happen, until we open the console,

type in a number and press enter. It will then print the number you typed + 1 to

the console.

So thats how we get input from the console! We are getting closer and
closer to being able to build a meaningful application.

The While Loop

We already went over how to write something to the Console.


System.out.println(“Hello, World!”);


Now what if we wanted to output “Hello, World!” to the console 100

times? We could type it out, which would increase our application file size

substantially, or we could use a Loop:


int i = 0;

while(i < 100) {

System.out.println(“Hello, World!”);

i++;
}

System.out.println(“Completed Loop”);

A Loop is, as the name suggests, something that loops. It takes in a

Boolean as an input, and if that Boolean is true, it executes whatever is between


our curly brackets, then it will LOOP until the given Boolean will be false, at

which point it will move on to the rest of the application. In the code above, we
input a comparative operator(which returns a boolean):

while (i < 100) {


And if the operator returns true, it will execute what is between the curly
brackets:

System.out.println(“Hello, World!”);

i++;
It will print “Hello,World!”, add 1 to i, and then check whether (i < 100)

is true, and while it is true, it will repeat, until finally after “Hello,World!” has
been printed 100 times, i will be equal to 100, and thus won’t be less than 100,

and

(i < 100) will return false, after which it will exit the Loop and execute the final

line:

System.out.println(“Completed Loop”);

So if we wanted to essentially crash our program and print “Hello,


World!” to the screen forever(at least until the Operating System doesn’t

forcefully close the application) we could! Simply input true into the

parentheses and the input will always be true, thus the loop will continue
forever:


while(true) {

System.out.println(“Hello, World!”);
}


The Do While Loop

The while loop will execute only while the given boolean is true. The Do

While loop will execute a chuck of code once, and then check whether or not to

execute that code again. Let’s take a look at an example:

class cls1 {
public static void main(String[] args) {

do {

System.out.println("Doing");

} while (false);


The output of the code above will be “Doing” once, even though inserted

boolean is false, it will execute the loop once. Pretty simple! If we inputted true

as the boolean, it would loop forever, just like with the regular while loop.

The For Loop


The final loop we are going to go over is the for loop. It allows us to

declare a variable, add a boolean, and add an action that will be performed at

every loop. In the following example, we do the same thing, at first with a while

loop, and then with a for loop.

class cls1 {
public static void main(String[] args) {

int i = 0;

while(i < 2) {

System.out.println(i);

i++;

for(int i1 = 0;i1 < 2;i1++) {


System.out.println(i1);

}
}

}

In the code above, declare a variable i and assign it a value 0, and then in a

while loop, while i is less than 2, we print it and increment i. So this loops output
will be:

Int the second loop, we do exactly the same thing, we declare a value i1,
tell the loop that while i1 is less than 2, to keep going, and tell it increment i1 at

the end of the loop. Then we print i1, and loop. So the output of this loop will

be:

Exactly the same! We could make a for loop go on forever by simple


inputting nothing between the “;”:

class cls1 {
public static void main(String[] args) {

for(;;) {
System.out.println("Looping");

}
}

}

This code will print “Looping” to the console forever. Neat!

With Loops, like with switch statements, we can use the break keyword,
this will stop the loop, and stop any lines of the loop after the break statement:

import java.util.Scanner;

class cls1 {

public static void main(String[] args) {

for(int i =0;true;i++) {

if(i == 3) {

break;
}

System.out.println(i);

}
}

The output of this code will be:


0
1
2

And then it will exit the loop, as i is equal to 3, and then it breaks the loop,
and exits the program.

Strings

We actually can do quite a bit of actions with Strings. There are over 40

different methods built-in to the String class, here we are going to look at 4 of

them: length, equals, contains and charAt. Let’s take a look at a code that utilizes

all of these methods:


import java.util.Scanner;


class cls1 {

public static void main(String[] args) {


String f = "Hi";
System.out.println("H is in Hi: "+f.contains("H"));
System.out.println("l is in Hi: "+f.contains("l"));
System.out.println("Hi has "+f.length()+" letters");

System.out.println("Hi = Hi: "+f.equals("Hi"));

System.out.println("Hello = Hi: "+f.equals("Hello"));


System.out.println("The second letter in Hi is "+f.charAt(1));

}
}

And the output of that code will be:

H is in Hi: true

l is in Hi: false

Hi has 2 letters
Hi = Hi: true

Hello = Hi: false

The second letter in Hi is i


Let’s break this down, we first create the String f and assign it the value
“Hi” .


String f = "Hi";

Next, we call the method f.contains which checks if a String contains


another String that we input into the method, this method will return a boolean
true if it does contain it, and false if it doesn't. We then print a String that tells us

information and adds the boolean to the end:


System.out.println("H is in Hi: "+f.contains("H"));

System.out.println("l is in Hi: “+f.contains("l"));


So this code will print H is in Hi: true in the first line, and l is in Hi: false

in the second line, as L is not in Hi. We then call the method length, which

returns the amount of letters in a String. In this case, it will return 2:

System.out.println("Hi has "+f.length()+" letters");

And the output will be Hi has 2 letters. Since Hi has 2 letters. Amazing.

Our next method, “equals” checks whether 2 Strings are equal, you might

ask why we don't use the “==” operator. A String is a class, and “==” can only be
used to compare primitive data types. Thats why we have the “equals” method to

compare Strings, this too will return a boolean. True if they are equal, and false
if they are not:


System.out.println("Hi = Hi: "+f.equals("Hi"));

System.out.println("Hello = Hi: "+f.equals("Hello"));



This will output:

Hi = Hi: true
Hello = Hi: false

So since Hi is equal to Hi, it will output true, and since Hello is not equal
to Hi, it will output false. Out final method, charAt will return the Character that

is at the given int, it’s important to note that it starts counting at 0, so the first

letter of a String will be at index 0:

System.out.println("The second letter in Hi is "+f.charAt(1));

This code will output The second letter in Hi is i, since it counts from 0,

H=0, and i=1. And those are some String methods. Now a String itself is an
Array of characters, an Array is a collection of something: let’s take a look.

Arrays

An array is simply a multiple number of values organized together. Let’s

take a look at an example:


class cls1 {
public static void main(String[] args) {
int[] arr = new int[10];

for(int i = 0; i < arr.length;i++) {

arr[i] = i;
}

for(int i = 0; i < arr.length;i++) {


System.out.println(arr[i]);

In the code above, we first create a new array, we do this by declaring a

data type, and then adding ‘[]’ after the data type declaration. This tells out
program that we are creating a new array with specified data type, and not the

specified data type. Then, when we declare “new int”, we put 10 into the array.

This means that our array will have a maximum value of 10.

int[] arr = new int[10];


Our next line as a for loop that declares a value i, said that as long as i is
less than the length of the array, and tells the program to increment i by 1 at each

loop. And so in this example, arr will have the values 0-9 assigned to it.
for(int i = 0; i < arr.length;i++) {
arr[i] = i;


We can access an array value by declaring (arrayName)[arrayIndex], and

after that we can treat it just like a variable of the same type. In the next line we
create another loop that prints the array:

for(int i = 0; i < arr.length;i++) {

System.out.println(arr[i]);

And those are Arrays, remember how we said a String is just an Array of

Characters? Well this is what we meant by that.


Calculator

Now let’s try to use all of our knowledge to create a calculator what will

takes input from the console, first will get what we want to do, add or subtract,

and then gets 2 values, with which we then perform the given operation. First try

to do it yourself, and if you get stuck look here for help.



import java.util.Scanner;

//importing Scanner


class cls1 {

public static void main(String[] args) {


// Creating Scanner

Scanner sc = new Scanner(System.in);

// Creating our loop, so it keeps getting input

while (true) {


// Getting operand

String operationID = sc.nextLine();


if (operationID.equals("+")) {

// if operand is plus, print the sum of the next 2 numbers


int num1 = sc.nextInt();

int num2 = sc.nextInt();


System.out.println(num1 + num2);

sc.nextLine();
} else if (operationID.equals("-")) {
// if the operand is minus, print the difference of the next two numbers

int num1 = sc.nextInt();

int num2 = sc.nextInt();


System.out.println(num1 - num2);

sc.nextLine();
} else if (operationID.equals("exit")) {

//if we write exit, it will stop the program

break;

} else {

// if the operand is neither plus nor minus, print invalid operand

System.out.println("Invalid Operand");

sc.nextLine();
}

In the code above, we:


1. import our scanner


2. create our scanner
3. create a loop that will keep looping until we write exit

4. get the operand(+ or -)

5. if the operand is a +, we get the next 2 values and print their sum, then
we read the next line so the our net operandID doesn't read our output.

6. if the operand is a -, we get the next 2 values and print their difference,
then we read the next line so the our net operandID doesn't read our

output.

7. if the next line is “exit”, then we exit our loop using the break keyword

8. if the operand is neither, we output that we inputed an invalid operand

And that is a very simple calculator, now try to add multiplication and

division on your own.


Modifier Types

When we create a int, it is automatically made into a variable, which

means we could change it’s value. If we wanted to create a constant, whose

value we cant change, we would have to use the Final keyword, which we need

to add before the declaration of the constant:


class cls1 {
public static void main(String[] args) {

final int f = 2;

}
}


In the code above, we use the final keyword to tell the program that we

don't want then be able to change that value. This may be useful when we want

to add certain attributes that we don't want changed, so that if someone in the

future working with our code, they wont be able to mess our code up.

The static modifier is user for creating class methods and variables, such

as public static void main, the method that is run when we start our program.

The Public modifier means that this variable or method will be visible to

the world.

The Private modifier means that this variable or method will be visible
only inside the class.


By default a method or modifier is visible only in the package


There are a couple other Modifier types like abstract, synchronized, etc,
but for the sake of simplicity these are all we are going to go over in this course.

Methods

In order to prevent copy-pasting large chunks of code, we have methods.

Methods allow us to create a certain code, then call it anywhere in our class, as

many times as we want. Let’s look at an example:

class cls1 {

public static void main(String[] args) {

print1();

static void print1() {


System.out.println(1);

}
}


The output of the following code will be: “1”, since in main we call the
method print1, which prints 1 to the screen. We could also input values into

methods, which will then be used int the method:



class cls1 {
public static void main(String[] args) {

print("Hello");

}
static void print(String str) {

System.out.println(str);
}

The code above will print “Hello” to the console, since we call the print

method in main, and then input the String “Hello”, which is then outputted to

the console. Notice how with our methods we add the void keyword, that just

means that we don't return a value, if we were to replace void with a data type,

we could then assign it to a variable of the same data type:


class cls1 {

public static void main(String[] args) {


int sum = add(1,2);

System.out.println(sum);
}

static int add(int a, int b) {


return a+b;

}
}

The output of this code will be 3, as in main we are calling the method

add, inserting 1 and 2, and then add uses the return keyword to return 1 + 2, then
we assign the result of add to sum, and print sum, thus the output is 3.


Methods are incredibly important when working with large-scale

applications, as instead of writing the same code 1,000 times, we could put it in a

method and save a large amount of space. This will also allow us, in the event

we need to edit the given code, to just edit the one method, instead of finding

each of the 1,000 code chunks and edit each one of them. You can see how

important it is to not copy-paste code.

Object-Oriented Programming

Object-Oriented Programming is one of the most important characteristics

of Java. Object-Oriented Programming(OOP) allows us to think of programming

more like real-life. We think of, say a desk. That desk has certain attributes, like

color, material, and size, and then size is made up of it’s own attributes, like

length, width, height. Well thats pretty much what OOP allows us to do in Java,
let’s create a Desk Class, this will contain it’s attributes, before we created our

codes in cls1 class, here we need to create a new class, and insert this code:

public class Desk {


String color;

String material;
Size size;
}

This code will give you an error, as we haven't yet created a class Size,

let’s do that:

public class Desk {

String color;
String material;

Size size;
}

class Size {

int height;
int width;
int length;
}


Now our code will work, we have created the class Desk, which has the

attributes Color, Material, and Size. These ‘Attributes’ are called Objects.

Ok, so we have our desk class, we have our Size class, but we haven't

actually assigned any values to any of these Objects, we haven't really don't

anything with them. Let’s add a constructor to our Size class:


public class Desk {

String color;
String material;

Size size = new Size(10, 14, 5);


}

class Size {
int height;
int width;
int length;


public Size(int height, int width, int length) {
this.height = height;
this.width = width;
this.length = length;


There we go, now we have created a constructor for our Size class. Each
time a new object is created, at least one constructor will be invoked. The main
rule of constructors is that they should have the same name as the class. A class

can have more than one constructor.


Now let’s go ahead and generate a constructor for our Desk class:

public class Desk {


String color;
String material;
Size size = new Size(10, 14, 5);

public Desk(String color, String material, Size size)


{

this.color = color;

this.material = material;
this.size = size;

}

}


class Size {
int height;
int width;

int length;

public Size(int height, int width, int length) {
this.height = height;
this.width = width;

this.length = length;
}

}
Ok, now we have created 2 classes with constructors, let’s go ahead and
add a main method with which we will create a desk, remember, the main
method must always go in the Public class:

public class Desk {


String color;
String material;

Size size;

public Desk(String color, String material, Size size)
{
this.color = color;

this.material = material;
this.size = size;

public static void main(String[] args) {


Desk myDesk = new Desk("Brown", "Wood", new
Size(10, 14, 5));

System.out.println("My Desks' length is " +


myDesk.size.length);
}

}

class Size {
int height;
int width;

int length;

public Size(int height, int width, int length) {

this.height = height;
this.width = width;
this.length = length;
}

The following program will output “My desks’ length is 5”, since we

assigned 5 to the length of the desk in our constructor. Notice here how we

create a Desk object inside the desk class, theres really nothing special here, it
works just as it would if we would create it in another class.

Now let’s look at inheritance, this just means that a class can extend

another class. Let’s create a size2d class, and have size3d extend size2d, and add

3d values:

public class Desk {

String color;
String material;

Size3d size;

public Desk(String color, String material, Size3d

size) {
this.color = color;
this.material = material;
this.size = size;

}

public static void main(String[] args) {
Desk myDesk = new Desk("Brown", "Wood", new
Size3d(10, 14, 5));

System.out.println("My Desks' length is " +


myDesk.size.length);


}

class Size3d extends Size2d {

int height;

public Size3d(int width, int length, int height)
{ super(width, length);

this.height = height;
}

}

class Size2d {
int length;

int width;


public Size2d(int width, int length) {
this.width = width;
this.length = length;

}

}

Here, the Size3d class extends the Size2d class, which means it takes with

it all of it’s objects. You may notice how we have the super(width, length)

keyword, all this does is pass the inputted constructor values to the extended

class’s constructor. The super keyword is required when an extended class has a
constructor.

When a class extends another class, that class is called a child, when a
class has another class extends it, it is called a parent. We can check if a child

extends a parent by using the instanceOf keyword:


public static void main(String[] args) {

Size3d sz = new Size3d(1,2,3);


System.out.println(sz instanceof Size2d);
}


The code above will print “true” to the screen, since sz is of type Size3d,
and Size3d extends Size2d.


When we have a class that extends another class, an object of that class IS-

A object of another class, if we have a class animal, and we have a class deer

which extends animal, a deer IS-A animal. Which means we could assign the

value animal to a deer:

public class main {


public static void main(String[] args) {


deer d = new deer();

Animal a = d;

}
}

class Animal {

}

class deer extends Animal {



}

This is called polymorphism. Every object in java has polymorphism,

because it IS-A object, and it IS-A itself. Polymorphism is the second OOP
concept, after inheritance.


We could also override methods from a parent class. This allows us to

override an inherited method, let’s look at an example:


class Animal {
public void move() {
System.out.println("Animals can move");

}
}

class Deer extends Animal {

public void move() {


System.out.println("Deer can walk and run");
}
}

public class TestDeer {


public static void main(String args[]) {

Animal a = new Animal();


Animal b = new Deer();

a.move();

b.move();
}
}

The code above will output

Animals can move

Deer can walk and run


Since we assign the value of new deer to b, and since Deer has an

overridden method, it will call the System.out.println("Deer can walk and run”);

line instead of the System.out.println("Animals can move”); line. It is important


to note that when we assign a child value to a declared parent object, we can

only call methods that are present in the parent class:


class Animal {

public void move() {


System.out.println("Animals can move");
}

}

class Deer extends Animal {
public void move() {

System.out.println("Deer can walk and run");


}
public void jump() {
System.out.println("Jumped");
}

public class TestDeer {


public static void main(String args[]) {
Animal a = new Animal();
Animal b = new Deer();


a.move();
b.move();
b.jump(); //Throws exception

}
}

The output of this code will be:

Exception in thread "main" java.lang.Error: Unresolved compilation

problem:

The method jump() is undefined for the type Animal

at TestDeer.main(TestDeer.java:25)


So it will throw an exception, as it is not allowed. The 3rd OOP concept
we will look at is Abstraction. We can create an Abstract class using the abstract
keyword, an abstract class will have abstract methods which we will then

Override. Abstract classes cannot be instantiated. They can only be extended by

a non-abstract class. We can create methods without body’s in abstract classes:


let’s look at an example:

abstract class Employee {


abstract void printClassName();
}
class Mechanic extends Employee {

@Override
void printClassName() {

System.out.println("Mechanic");

}
}


Here, Employee has an abstract method printClassName(), which doesn't
contain any body. We override it in Mechanic, using the @Override annotation,
which just tells the compiler that it’s overriding a method. It’s important to note

that a class that extends an abstract class must override all of it’s abstract

methods, so if we were to remove printClassName from the Mechanic class it


would give us an error.

The 4th and final OOP concept we will go over is Encapsulation, this

simply means the protection of our attributes in a class with a private keyword.

To implement encapsulation, we simply must create a class with private

attributes, and add getter and setter methods for the attributes: let’s take a look at

an example:

public class Deer {


private String color;

private int height;


public String getColor() {

return color;
}

public void setColor(String color) {


this.color = color;
}

public int getHeight() {


return height;
}
public void setHeight(int height) {

this.height = height;
}
}

Here, the color and height attributes are private which means it could only

be accessed within the class, if we were to create an object of type Deer, we


couldn't access the color or height attributes directly, we would need to use

getColor, or getHeight to get attributes, and setHeight or setColor to set


attributes. Pretty Simple.

Flower Shop
Let’s create an object-oriented Flower Shop Program, we will need the
following classes:

Flower

-lily
-rose

-tulip
Shop

Manager

Our flower shop will have a flower class, and then 3 flower types which

extend the Flower class, they will have the attributes: inStock, price, color. Our

program will also have a manager class, which will have an id and name
attribute. Finally we will also have our Shop program that will have an array of

managers, and an array of flowers, all classes must implement encapsulation.

When we will print our Shop, we should get a string of all values. Try and do
this on your own, and if you get stuck look here for help.

class Shop {

private Manager[] managers = new Manager[10];



private Flower[] flowers = new Flower[10];

public Manager[] getManagers() {


return managers;
}

public void setManagers(Manager[] managers) {


this.managers = managers;
}

public Flower[] getFlowers() {

return flowers;
}

public void setFlowers(Flower[] flowers) {


this.flowers = flowers;
}

@Override
public String toString() {
String toReturn = "";
for (int i = 0; i < managers.length; i++) {

toReturn = toReturn + managers[i].toString();


toReturn = toReturn + ",";
}
toReturn = toReturn + "\n";
for (int i = 0; i < flowers.length; i++) {

toReturn = toReturn + flowers[i].toString();


toReturn = toReturn + ",";


return toReturn;

}

}
public class Implem {
public static void main(String[] args) {
Shop shop = new Shop();

Manager[] arr = new Manager[10];


Flower[] arr1 = new Flower[10];
for(int i = 0; i < arr1.length;i++) {
arr[i] = new Manager(i,"Steve");
arr1[i] = new Lily(10,"white",true);

}
shop.setFlowers(arr1);

shop.setManagers(arr);

System.out.println(shop);
}
}

class Flower {
private int price;
private String color;
private boolean inStock;


public Flower(int price, String color, boolean
inStock) {
super();
this.price = price;

this.color = color;
this.inStock = inStock;


public int getPrice() {
return price;
}


public void setPrice(int price) {
this.price = price;
}


public String getColor() {
return color;
}

public void setColor(String color) {


this.color = color;


public boolean isInStock() {
return inStock;
}


public void setInStock(boolean inStock) {
this.inStock = inStock;
}


}

class Lily extends Flower {

public Lily(int price, String color, boolean inStock) {


super(price, color, inStock);

}

@Override
public String toString() {

return "Lily";
}

}


class Rose extends Flower {

public Rose(int price, String color, boolean inStock)
{

super(price, color, inStock);



@Override
public String toString() {
return "Rose";

}

}

class Tulip extends Flower {



public Tulip(int price, String color, boolean inStock)
{
super(price, color, inStock);

@Override
public String toString() {
return "Tulip";
}


}

class Manager {

private int ID;


private String name;

public Manager(int iD, String name) {
super();

ID = iD;
this.name = name;



@Override
public String toString() {

return "Name = " + name + ", ID = " + ID;


}
}

There we go, a couple new things here: When we call System.out.println()

method, it calls the toString method on whatever object we put in there, by

overriding that method we could create custom toString actions for each object,

this when we invoke toString on shop, since it is redefined, it gives us an

organized string of managers and values.

Another new addition is the fact that we add a “/n” in between our strings,
this is just the equivalent of “/br” in html, which just creates a new line.


Reading code is an important part of programming, try to understand what

the code above does, and why it does it. We went over every aspect of it in this
course.

GUI


Before, when interacting with out program, we always used the console.

But realistically, what good does that do? We create a program, and every user

has to download eclipse, copy in our code, and interact with the console?

Well, no. To solve this problem we have a Graphical User Interface, or

GUI for short. This simply allows us to create graphics, with which we can then
interact, and send inputs to our code! The simplest library to use for this is AWT,

a java library created for simple GUI, let’s take a look at an example of a

program that opens a frame with the words “Hello, World” printed in it:

import java.awt.*;

public class Implem {


public static void main(String[] args) {

Frame f = new Frame("Our First Frame");

Label l = new Label("Hello, world!");


f.add(l);
f.setSize(100,100);
f.setVisible(true);

}
}

In the code above, we first import all classes in the AWT library, then

create a Frame(which is just a program window), and in the constructor of the

Frame we add a name that will be displayed at the top of the window, in this case
it’s “Our first frame”, we then create a label, which is a component of AWT

which allows us to add plain text, assign it’s value as “Hello, World!”, we then

add l to f, set f’s size to 100 by 100, and set it’s visibility to true.

And if we run this program, we get a frame with the text “Hello, World!”

printed in it. Note that we wont be able to close our program with the x at the
top, we need to click the red square in our eclipse console, which will end the

program.

Ok, so thats how we could output things to a GUI, but what if we want to
get input from a user? Well, we would have to use a TextField, it is simply a
textField in which we could input text, let’s take a look at an example:

import java.awt.*;


public class Implem {

public static void main(String[] args) {


Frame f = new Frame("Our First Frame");
TextField t = new TextField();

f.add(t);
f.setSize(100,100);
f.setVisible(true);
}

}
Ok, there we go, our frame will now contain a textfield in which we could
input text.


Now let’s create a button that, when clicked will allow us print whatever
we have in the TextField to the console:


import java.awt.*;
import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;


public class Implem {

public static void main(String[] args) {


Frame f = new Frame("Our First Frame");

TextField t = new TextField();

Button b = new Button("Print");

b.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {


System.out.println(t.getText());

});
f.setLayout(new GridLayout(1,2));

f.add(t);
f.add(b);

f.setSize(100,100);
f.setVisible(true);

}
}

A couple new things here, we create a Button b, assign it the text “print”,

then add an action listener to the button, which just an abstract class which
contains a method actionPerformed which is called when we press the button.


When i say ActionEvent is an abstract class, i am lying, it is actually an

interface, which is almost like an abstract class, except it cant contain methods

with a body and is extended using the implements keyword. But for now just

think of it as an Abstract Class.

So we input a new ActionEvent object, in which we override the

actionPerformed method, yes we could do it using (classname)() {}.


Next we add a GridLayout to our frame, which just means that

components that we add will be automatically arranged in a grid, the dimensions


of which we assign in the constructor, by inputting 2 integers.


Now when we run this program, which will have a textField and a button,

if we input something into the TextField, and click the button, it will print it to
the Screen. Now you can see how we could create legitimate programs that

could work without the console, we could for example set the buttons text to
whatever we put into our textField, let’s look at that code:

import java.awt.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Implem {

public static void main(String[] args) {

Frame f = new Frame("Our First Frame");

TextField t = new TextField();

Button b = new Button("Print");

b.addActionListener(new ActionListener() {


@Override

public void actionPerformed(ActionEvent e) {

b.setLabel(t.getText());
}

});
f.setLayout(new GridLayout(1,2));

f.add(t);
f.add(b);

f.setSize(100,100);
f.setVisible(true);
}


Here, when we click the button it sets the buttons label as the text we have

in our TextField. Now let’s add a GUI to our flower shop program.

Flower Shop GUI


For this part of the lesson, we are going to put this program in 2 separate

files, as long as they are in the same package we could access their classes just

as if it was in the same file. One will be our Flower Shop program that we have

already created, and the other will be out GUI, let’s take a look:

import java.awt.Button;

import java.awt.Frame;
import java.awt.GridLayout;

import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class FlowerShopGUI {

static int current;



public static void main(String[] args) {

Shop shop = new Shop();

Manager[] arr = new Manager[10];


Flower[] arr1 = new Flower[10];

for (int i = 0; i < arr1.length; i++) {


arr[i] = new Manager(i, "Steve");

arr1[i] = new Lily(10, "white", true);

shop.setFlowers(arr1);

shop.setManagers(arr);

Frame f = new Frame("FlowerShop");


Button next = new Button("next");

Label flowers = new Label();

Label managers = new Label();


current = 0;

next.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

if (current == shop.getFlowers().length) {
current = 0;
}

String t = shop.getFlowers()[current].toString();


flowers.setText("name = " + t);

t = shop.getManagers()[current].toString();

managers.setText(t);

current++;

});
f.setLayout(new GridLayout(2, 3));


f.add(next);

f.add(flowers);
f.add(managers);

f.setVisible(true);

}
}

And there we go! Now let’s add the functionality for it to close when we

click the ‘x’ at at the top of the frame:


import java.awt.Button;
import java.awt.Frame;

import java.awt.GridLayout;

import java.awt.Label;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowEvent;

import java.awt.event.WindowListener;

public class FlowerShopGUI {

static int current;


public static void main(String[] args) {


Shop shop = new Shop();

Manager[] arr = new Manager[10];


Flower[] arr1 = new Flower[10];

for (int i = 0; i < arr1.length; i++) {


arr[i] = new Manager(i, "Steve");
arr1[i] = new Lily(10, "white", true);

shop.setFlowers(arr1);
shop.setManagers(arr);


Frame f = new Frame("FlowerShop");

Button next = new Button("next");

Label flowers = new Label();

Label managers = new Label();

f.addWindowListener(new WindowListener() {

@Override
public void windowOpened(WindowEvent e) {

// TODO Auto-generated method stub

@Override
public void windowClosing(WindowEvent e) {

f.dispose();
}


@Override
public void windowClosed(WindowEvent e) {

// TODO Auto-generated method stub

@Override
public void windowIconified(WindowEvent e) {

// TODO Auto-generated method stub

@Override

public void windowDeiconified(WindowEvent e) {

// TODO Auto-generated method stub


}

@Override
public void windowActivated(WindowEvent e) {

// TODO Auto-generated method stub


}


@Override

public void windowDeactivated(WindowEvent e) {


// TODO Auto-generated method stub
}

});

current = 0;
next.addActionListener(new ActionListener() {


@Override

public void actionPerformed(ActionEvent e) {

if (current == shop.getFlowers().length) {

current = 0;

String t = shop.getFlowers()[current].toString();


flowers.setText("name = " + t);

t = shop.getManagers()[current].toString();


managers.setText(t);

current++;

});
f.setLayout(new GridLayout(2, 3));
;

f.add(next);
f.add(flowers);

f.add(managers);
f.setVisible(true);

And there we go! Now we can close this window with the ‘x’ at at the top

of the frame. We simply add a Window Event Listener, which is an abstract class
and override the “window closing” method to delete our frame when we click it!

AWT Paint


We could also paint things to the screen, here we will go over a simple
example where we will paint a blue triangle with the size 100x100 to our Frame:

import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;

import java.awt.Panel;


public class Paint {

static Frame f;
static Panel p;
public static void main(String[] args) {
f = new Frame();
p = new Panel(){

public void paint(Graphics g) {


g.setColor(Color.BLUE);

g.fillRect(0,0, 100, 100);

}
};
f.add(p);
f.setVisible(true);

}
}
Here we have a panel, which is a component the acts like a frame-within a

frame, and we Override it’s paint method, and input graphics g, which is a class

that allows us to draw graphics, draw a rectangle, after which we add p to f, set f

to visible and now if we run this program we will get a frame with a blue square
in it. There we go!


Conclusion:

And that’s java, from here you could learn about interfaces, files,

loggers, algorithms, data structures, perhaps even the basics of server

programming, but it will all be, in one way or another - an extension

of what you learned here.


Java is an incredibly powerful language, its syntax is elegant and

easy to read, it’s got a giant community of amazing developers behind

it, and it runs on most every device out there. With determination and

time, most anything could be created with Java.


If you are interested in learning more about programming languages,

check out my guide on python: Learn Python Programming in one

week with step by step tutorials

You might also like