Python and Java
Python and Java
Python:
Step Tutorials
Dr. Michael Lombard
Table of Contents
Introduction
Conclusion
Copyright 2016 by ___Lulu Publishing___________________ -
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
This declaration is deemed fair and valid by both the American Bar
recorded copy and is only allowed with express written consent from
The information in the following pages is broadly considered to be a
truthful and accurate account of facts and as such any inattention, use
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
Introduction
so.
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
every concept that we encounter. One thing that Python does is leave
important details out, sometimes; this is why so many people are keen
when left out, can be extremely helpful to programmers and make the
language easy to learn for hobbyists. However, for people who would
where Python (and the other quick-and-easy Python books) fall short.
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
So if you’re reading this book, it means that for one reason or another
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
So, if you are one of those people that came to this book out of
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
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
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.
can run the Python interpreter. This means that whether your end user
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
framework out there to help you accomplish your end goal. There are
even some more esoteric APIs and frameworks out there, if you’re
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
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
you aren’t walking away confused on things where Python does fall
short compared to other languages.
easy. That’s the long and short of it. You can have a Python program
C++:
#include <iostream>
int main() {
cout << “hello world!\n”;
return 0;
Python:
that, you find the reason you should start off with Python – it lets you
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
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
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
that should acquaint you quite adequately (and more effectively than
Python installed. If not, then you’re going to need to install it. This is,
to cover Python 2 specifically. Why? For the simple fact that almost
all legacy Python code – and almost all projects that you can work
bad thing. For a new programmer, it is a bad thing. You should learn
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
running. You’re not quite ready to start cracking open Python code
Notepad and write your Python code from within there. However, I
highly discourage this. Rather, I’d recommend that you get a text
several free options that are all equally incredible: Atom (at
The primary reason for using one of these is that they offer syntax
highlighting. This helps you keep track of the various different things
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
start a new file. Save it preemptively so that you can get the syntax
like.
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:
If you see that, then congrats! With that, you’ve written your first
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
Stick around, because you’re only just getting started on the path to
Okay, so we’re going to hit the ground running in this chapter. There
value here being defined as any number of different things; the value
to store some kind of data. Variables are what allow you to do that.
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
something else.
leave you a bit confused? This is one of those times where it’s more
think involve much math – drawing a dialog box onto the screen, for
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
This is where the idea of data types comes from. Data types are a way
There are many different kinds of data that computers can understand.
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
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
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
Anyhow, moving on. Let’s prove to you that you just created a
variable. Below your lost line of code, type the following line:
Save the file and then try running it from the command line. It should
I have 3 melons!
If it does so, then perfect! You followed instructions and it turned out
Let’s say that our friend gave us three melons and we wanted to share
The first thing that we’d want to do is adjust the value of melons by
melons = melons + 3
melons += 3
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:
Now, if you were to save and run this, the output should be like
follows:
I have 3 melons!
This forms the basis of values and variables. You can create all sorts
variable for your favorite fruit. Let’s do that below our former code.
favFruit = “banana”
amountOfFruit = 2
questions, obviously.
all of the code that we’ve written so far and then print the following:
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,
value data (primarily used for debugging and testing, but we know
I have 3 melons!
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
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:
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
Loops
Earlier we said we were going to talk about Booleans. Well, now’s the
Booleans are.
the entire idea of control flow comes from it. What is control flow?
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
Booleans reflect these notions of expressions. So, you can store raw
varX = True
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
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
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
== is equal to x == y
!= is not equal to x != y
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
if condition:
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
x = 6
y = 8
Now, if you tried to save and then run this, nothing would happen.
shape, or form. This has its own uses and utilities which you’ll
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
else statement.
Else statements are statements that you can put after your if statement.
the if statement is not true. This means that no matter what, some of
Go to the code that we’ve written so far and right below it, add in the
following:
else:
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
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
following:
elif x == y:
By the end, your entire conditional block should look like this:
if x > y:
elif x == y:
else:
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
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
there are distinct sets of actions that are happening every time you
subconsciously add one to the number; you shape your mouth and say
The simple fact is that loops are incredibly prevalent in a lot of our
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
First, we’ll cover while loops. The intent of a while loop is simple. All
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
i = 1
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.
over and over until a certain condition is met. For example, if you
cards to be dealt and turns to be taken until somebody had lost the
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
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
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
accordingly.
As I said, this will make more sense in the following chapter, but for
For now, I’m just going to show you how the syntax of the for loop
works:
do this
Roughly what this means is that the iterator is a direct copy 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
The simplest way to show this is much like with the while loop:
range(1, 10)
different object in the collection. Now, let’s apply this to our loop:
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.
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
chapter is meant to undo some of that fog. The ultimate goal of this
order to do that, we really have to talk about lists first, because files
So let’s start from there: what are lists exactly? As I’ve already stated,
keep up with some grades for three students: Tommy, Lara, and
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
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
containing 79, 95, and 93, and we wanted to pull the second number
print tommyGrades[1]
The computer would see this like so:
tommyGrades
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
del tommyGrades[2]
This would remove the item at index2 from the list tommyGrades.
list, then all of the items ahead of it in terms of index would move
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
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
where file input and output would be useful, but the most obvious
example is something like Microsoft Word, where you save and load
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,
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
f = open(“fileExample.txt”, ‘r’)
The r indicates that we only intend to read the file that we’re opening.
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
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
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
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.
Now, let’s say that you wanted to iterate through every line on a file
Carrot
Eggplant
Celery
Cabbage
Lettuce
Onion
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
f.close()
Then, if we wanted to, we could print out our whole list to be sure that
for vegetable in vegetables:
print vegetable
vegetables = []
f = open(“vegetables.txt”, ‘r’)
for lines in f:
vegetables.append(lines)
f.close()
print vegetable
So with that, you know quite a bit about the extremely useful concept
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
The next step is to venture out. This book only covered the very basics
One of the best things that you can do in order to become a better and
projects out there that you can look into in order to bolster your skill
game developer and produce something that people would love. Once
started looking into tutorials for creating video games. It was at that
interested in the subject matter that I was learning in the first place.
People always learn better and more efficiently when they care about
In the end, I just really hope that I’ve helped you get on the right path
harsh concepts that may otherwise really confuse you. Starting out as
a programmer can be a very rough course, and it can become really
To that end, I really hope I’ve succeeded. If I have and this book
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
Table of Contents:
What is Java? 2
Environment Setup 2
Logical Operators(!,&&,||) 9
Bitwise Operators(&, |) 12
IF ELSE 13
IF ELSE IF 13
SWITCH 14
Input From Console 15
Strings 18
Arrays 20
Calculator 21
Modifier Types 22
Methods 23
Object-Oriented Programming 24
Flower Shop 32
GUI 37
AWT Paint 43
Conclusion 44
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
This declaration is deemed fair and valid by both the American Bar
recorded copy and is only allowed with express written consent from
the Publisher. All additional right reserved.
truthful and accurate account of facts and as such any inattention, use
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
What is Java?
The java language is a programming language developed by Sun
Windows, Linux, and Unix. It achieves this by compiling into “byte-code”, that
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
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
Environment Setup
When working with a programming language, in order to avoid manually
For this tutorial we will use Eclipse, as it’s free, intuitive, and has a rich
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
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.
public class cls1 {
System.out.println("Hello, World!");
}
}
At this point, you might be asking yourself, “What in the world is System?
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.
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.
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
Let's get into exactly how to create Integers and what we could do with
them.
public class cls1 {
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
i = 1;
method can print Integers too, in fact, it can print any of the data types that we
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 {
i = 5;
System.out.println(i);
have assigned to it is 5. With integers, we can create whole numbers that we can
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,
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:
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
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,
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:
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
public class cls1 {
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
Arithmetic Operators(+,-,*,/,%,++,--)
+ 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 {
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
Thats a pretty big code! The output we get will be: “5,3,8,2,1,5,3”. Now
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
Our next line of code does pretty much the same thing as the first, but it
i2 = i2-1; //Subtract 1
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
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:
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
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(==,<=,!=,>=,>,<)
class cls1 {
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
‘>=’ is the operator for more than or equal to, since (1 >= 1) is true, it will
‘>’ 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 {
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
System.out.println(true || false);
System.out.println(true || true);
System.out.println(false || false);
true
true
false
So the OR operator will return true if one or more than one of its inputs are
class cls1 {
public static void main(String[] args) {
}
}
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
Our final logical operator, ! is called the not operator, it simple reverses
class cls1 {
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;
}
}
The output of the following code will be false, as b is true, and true AND
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,
base10. But in Binary, or base2 we only have 2 numbers, 0 and 1(which then
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
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
The bitwise and operator or & operator is not to be confused with &&, &&
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
and one that tells that program what to execute. Let’s look at an example:
class cls1 {
}
}
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.
class cls1 {
}
}
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) {
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
SWITCH
value is equal to many other values. The switch statement takes in a value, not a
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:
break;
case 3:
break;
case 4:
System.out.println("The number is 4");
break;
case 5:
System.out.println("The number is 5");
break;
default:
}
}
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
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
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
import java.util.Scanner;
class cls1 {
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
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.
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
int i = 0;
System.out.println(“Hello, World!”);
i++;
}
System.out.println(“Completed Loop”);
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):
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”);
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
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 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
class cls1 {
public static void main(String[] args) {
int i = 0;
while(i < 2) {
System.out.println(i);
i++;
}
}
}
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:
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 {
for(int i =0;true;i++) {
if(i == 3) {
break;
}
System.out.println(i);
}
}
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
import java.util.Scanner;
class cls1 {
}
}
H is in Hi: true
l is in Hi: false
Hi has 2 letters
Hi = Hi: true
Let’s break this down, we first create the String f and assign it the value
“Hi” .
String f = "Hi";
System.out.println("H is in Hi: "+f.contains("H"));
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
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"));
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
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
class cls1 {
public static void main(String[] args) {
int[] arr = new int[10];
arr[i] = i;
}
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.
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:
System.out.println(arr[i]);
And those are Arrays, remember how we said a String is just an Array of
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
//importing Scanner
class cls1 {
// Creating Scanner
while (true) {
// Getting operand
if (operationID.equals("+")) {
sc.nextLine();
} else if (operationID.equals("-")) {
// if the operand is minus, print the difference of the next two numbers
sc.nextLine();
} else if (operationID.equals("exit")) {
break;
} else {
System.out.println("Invalid Operand");
sc.nextLine();
}
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
And that is a very simple calculator, now try to add multiplication and
Modifier Types
value we cant change, we would have to use the Final keyword, which we need
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
Methods allow us to create a certain code, then call it anywhere in our class, as
class cls1 {
print1();
}
}
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
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,
class cls1 {
System.out.println(sum);
}
}
}
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
Object-Oriented 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:
String material;
Size size;
}
This code will give you an error, as we haven't yet created a class Size,
let’s do that:
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
String color;
String material;
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
Now let’s go ahead and generate a constructor for our Desk class:
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:
Size size;
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;
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:
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));
}
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
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
deer d = new deer();
Animal a = d;
}
}
class Animal {
}
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
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Deer extends Animal {
b.move();
}
}
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”);
class Animal {
}
class Deer extends Animal {
public void move() {
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:
problem:
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
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
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.
attributes, and add getter and setter methods for the attributes: let’s take a look at
an example:
return color;
}
this.height = height;
}
}
Here, the color and height attributes are private which means it could only
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
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 {
return flowers;
}
@Override
public String toString() {
String toReturn = "";
for (int i = 0; i < managers.length; i++) {
return toReturn;
}
}
public class Implem {
public static void main(String[] args) {
Shop shop = new Shop();
}
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 boolean isInStock() {
return inStock;
}
public void setInStock(boolean inStock) {
this.inStock = inStock;
}
}
class Lily extends Flower {
}
@Override
public String toString() {
return "Lily";
}
}
class Rose extends Flower {
public Rose(int price, String color, boolean inStock)
{
@Override
public String toString() {
return "Rose";
}
}
@Override
public String toString() {
return "Tulip";
}
}
class Manager {
ID = iD;
this.name = name;
@Override
public String toString() {
overriding that method we could create custom toString actions for each object,
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?
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.*;
}
}
In the code above, we first import all classes in the AWT library, then
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 {
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 {
b.addActionListener(new ActionListener() {
@Override
});
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
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 {
b.addActionListener(new ActionListener() {
@Override
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.
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 {
shop.setFlowers(arr1);
shop.setManagers(arr);
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
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;
shop.setFlowers(arr1);
shop.setManagers(arr);
Frame f = new Frame("FlowerShop");
f.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
@Override
public void windowClosing(WindowEvent e) {
f.dispose();
}
@Override
public void windowClosed(WindowEvent e) {
@Override
public void windowIconified(WindowEvent e) {
@Override
@Override
public void windowActivated(WindowEvent e) {
@Override
});
current = 0;
next.addActionListener(new ActionListener() {
@Override
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(){
}
};
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,
it, and it runs on most every device out there. With determination and