[Web Site Design, Programming ... and Technology, HTML 5, JAVA 1] David Lawfield - JAVA_ JAVA for Beginners - The Quick and Simple Way to Learn JAVA - Programming Language for JAVA_ JAVASCRIPT_ Java Programm
[Web Site Design, Programming ... and Technology, HTML 5, JAVA 1] David Lawfield - JAVA_ JAVA for Beginners - The Quick and Simple Way to Learn JAVA - Programming Language for JAVA_ JAVASCRIPT_ Java Programm
For Beginners
Table of Contents
Table of Contents
What Will This Book Teach You?
A Brief History of Java
The Popularity of Java
Platform Independence
Java API
Object Orientation
Classes
Getting Started
Using a Dedicated IDE
Netbeans
Using a Text Editor
Learning the Lingo (Acronyms)
CPU - Central Processing Unit
CRT - Cathode Ray Tube
ALU - Arithmetic Logic Unit
LAN - Local Area Network
IDE - Integrated Development Environment
DOS - Disk Operating System
OOP - Object Oriented Programming
ROM - Read Only Memory
RAM - Random Access Memory
Basics of Programming Languages
Variables
Variable Types
Control Structures
Syntax
Data Structures
Arithmetic Operators
Your First Application: Hello World
Making Your IDE Project
Build Project (Hello World App).
How Hello World! Works
Comments in the Source Code
Your Main Method
More Definitions
Objects
Classes
Inheritance
Java Code Examples
Calling Methods
Example of Strings
Value Parameters
Pointers As Value Parameters
Array Examples
Connecting to a Webpage and Reading from It
List That Can Store Anything, and Not Only Ints
Writing Ints onto File
Word Counting Code
Using Scanner Class to Read Ints From File
Introduction
If you are at least slightly interested in programming, you have probably
heard about Java. It is a language for programming that follows in the style of
C and C++. These are also very common languages, so anyone who already
has experience with them, should feel comfortable picking up with Java.
However, there are some important differences with these language, which
will be discussed in the next chapter.
What Will This Book Teach You?
There is a lot to learn in the world of programming, and many languages have
similarities. As mentioned, if you are already familiar with another language,
you should find it easier to get started with Java. However, for everyone else,
there are some basics to learn in the beginning. They might seem quite
unusual at first, but you need to build a firm understanding of the basics,
before you can start to create your own applications.
While this book is helpful to beginners, it is also a great resource for people
who already know a little about computer use, and possibly even
programming.
As for the name “Java”, it was named by its creator. In the beginning, it was
called “Oak”. However, it was soon found out that there was already a
programming language with that name. After quite some time trying to think
of a suitable name to replace Oak, Gosling’s team of developers decided to
take a break and grab some coffee. Since java is another term for the popular
beverage, it gave them the idea for a new name for their programming
language.
People often think of Java as a programming language that is just for Internet
applications. However, it is actually intended for a variety of purposes, for
use on many different platforms. That is one of the things that make it so
popular, to those who understand its power.
The Popularity of Java
One of the reasons that Java is so popular, is that it’s so popular. Basically, it
is one of the most commonly used programming languages in the world.
Many programmers have had some experience with Java at one point or
another in their careers. If you are thinking about getting into programming,
but you cannot decide which language to learn first, Java is a recommended
choice for you.
As well as being popular, Java is great because it is easy to use for cross-
platform applications. That means that it can be used to create programming
for a variety of different operating systems and platforms. Java is dominant
on the server’s side of a system.
Take a look at some of the different things that Java can do, and why it is a
great programming language to learn:
Platform Independence
This is a key reason for Java being so popular. Platform independence refers
to its ability to run on a range of different computers. If you have a system
that is able to run an appropriate JRE (Java Runtime Environment), it will be
capable of running Java applications. This includes Windows, Mac, Linux,
Unix, computer mainframes, and even many mobile devices.
Java API
Actually learning Java is fairly simple, because there are just 50 different
keywords within the language. However, there is an library that contain
thousands of different classes. In addition to this, there is a far greater number
of methods for use in programs. The contents of a library is what gives Java a
range of different functions. Without a library, Java would not be able to have
its functionality, so it is as integral to Java as the language itself. The library
of classes is known as the Java API. You are not limited to just one library
either. There are many options, and they have a range of purposes. Suppose
that wanted to create a certain genre of game, for example. You could
probably find a special library that was created to make that task easier. In
this way, you can basically acquire a customized environment to work in, so
you don’t have to build everything from the ground, up.
Before you start to panic, understand that there is no need to learn the Java
API entirely. Programmers typically only learn smaller parts of it in entirety.
If someone needs to use some classes that they are not comfortable with, it is
easy to look up more details about them.
Object Orientation
Inherently, Java is an object-oriented language. Programs made using it will
be comprised of objects. These are elements of programs that are
representative of abstract concepts, or real objects.
Imagine that you were making an application for dealing with a payroll. The
employees of the business would need to be represented by objects. In order
to make these objects, you would need to create a class for defining the
method and data for making every employee an object. You might choose to
title this class “Employees”. While the name of your class isn’t going to show
up to users who run the payroll application, it will be very helpful for you in
the coding process.
Getting Started
There are several different ways to get what you need to start programming
with Java. You are going to need these three basic things:
You can simply download them from the Oracle’s website, the company that
acquired Sun Microsystems. They have two different downloads for you two
choose from:
● The software development kit (SDK). This contains the three tools
that you need. You can use this to program Java applications. Make
sure to get the version that is compatible with your computer and
operating system.
● The Java runtime environment (JRE). This only contains a virtual
machine, and an application programming language. However, for the
purposes of learning Java, this will not be enough. The JRE is only
good for running Java applications, but does not include an actual
compiler.
Even if you do decide to use third-party Java development tools, you should
use Oracle’s Java runtime environment as well. This is great way to make
sure that your programs are as compatible as possible
Using a Dedicated IDE
These allow you to create code, but they offer many great features that make
working with Java easy, although they can work with other programming
languages. If you would like to, you can simply use a text editor. However, a
dedicated IDE will make the job of learning much easier, so that’s what this
book will use for learning purposes.
Netbeans
There are many of these to choose from. Some will cost you money to buy,
but there are also some great free choices. For the purposes of this book, you
should download NetBeans IDE, which is an open-source, free piece of
software. Make sure that you download a version of Netbeans that is
compatible with your operating system. Complete the installation process,
and then you will be ready to get started with your very first piece of Java
coding.
For the instructions contained in this book, you will need to download and
install the NetBeans IDE.
Later, once you are more comfortable with programming in Java, you might
want to find something else to use, but that is really a personal choice.
Using a Text Editor
Computer programs are created using code, and that is made up of text, in its
raw form. It stands to reason that to write and edit pieces of code (which is
text), you will need a text editor. You are probably familiar with word
processors, which can also create text. However, those are great for making
formatted text, including letters, reports, books, etc. You will need to work
with plain, unformatted text, so something like Word will not be acceptable.
There are a lot of text editors for writing your code, including one that you
have probably used already, called Notepad, which comes with Windows.
These are small and often free, although there are some commercial text
editors that cost money to buy.
While you can use a very basic text editor like Notepad, it will be much
easier to use something with more features. A text editor that is made
specifically for coding will be most useful for programming. Here are some
good features to look for in a text editor:
Here is an easier way to think of variables: they are a way for storing
information, so it can be used later. To access that information, a specific
name is used. As an example, imagine that a website asks for your name. A
text box would appear, requesting that you enter your name. That box would
be representing variable. The person who owns the website might have
named that box “usernames”, and that would be the symbolic name. As for
the name that you entered, that would be a value. Wherever this information
is stored, would be the storage location.
Variable Types
Now that you know what a variable is, you can learn about the different
types. Simply knowing that something is a variable is not enough for Java. It
also needs to know what kind of information you want to store with your
variables.
This book will not go too deeply into types of variables. For now, it is more
important that you understand what a variable is used for, and that there are
different types available.
Control Structures
A control structure is any chunk of code that looks at variables, analyzes
them, and then chooses what to do, based on the elements of the variables.
Within that control structure, the computer will make certain decisions based
on the state of your variables. You have looked at states earlier in this book.
So, now you can see how objects can affect the way that the computer reacts
while running different codes. If you were running a car racing game, and the
state of your car object indicated that it had crashed into a wall, the computer
would cause your car to crash. It does get much more complex than this, but
it’s a good example for now.
Syntax
This word has already been used in this book, but you have likely already
heard it before. It has its own definition in regards to languages that people
speak and write. However, it is a little different for programming. A
programming language’s syntax is basically the rules that define how
different symbols work, and what they do when used together in certain
ways.
Java uses symbols like brackets, curly brackets, variables, and different
things. You can think of syntax kind of like the grammar rules that a
programming language follows. You need to use certain symbols, in certain
ways, and then position things properly. If you fail to use proper syntax, Java
will not be able to understand what you are trying to do. This will lead to
errors when you run your applications.
Using correct syntax is something that you should learn early on. Always
make sure that you enter coding correctly, and check that your syntax is right.
Data Structures
In the world of computer programming, data structures are a way to organize
and store data within a computer. It is done in a way that allows a computer
to use it efficiently. It is possible to simply store data in a big bunch, and it
would be possible for a computer to use it. There are many different ways to
code things, and to store data. However, if it is not done efficiently, you will
probably end up with a very unstable application. It might be extremely slow,
or it might not work properly all of the time.
● Addition +
● Subtraction -
● Division /
● Multiplication *
● Modulo %
You will probably recognize these from your days of of math classes in
school. To get an idea of what you can use them for in Java, take a look at
these examples, which use operators named op1 and op2:
There is a chance that you will need to add the version of the JDK that you
have. This would be due to having a new version that is not already listed
with Netbeans, but it’s not likely.
● Click on Tools.
● Go to Java Platform and select it.
● You will be able to see listings with the number of the JDK, and
easily be able to tell if yours is already listed.
Next you are going to add some code to the Generated Source File. As you
were creating your project in the New Project wizard, you left the check box
titled Create Main Class. This lead the IDE to make a skeleton class
automatically.
You will need to replace that line with the following one:
/**
*
* @author
*/
/**
* This app simply prints “Hello World!”
*
*/
When you are writing your code, be very careful to type exactly the right
things. Be sure that you use the right case as well, because the Java launcher
and compiler and both case-sensitive.
Next, you will save your new app. Click on File > Save.
You will now run your very first application. In Netbeans main menu, click
Run >
Build Project (Hello World App).
The output window will not show you the built code beneath the source
editor. You should be able to see “Hello World!” printed. More importantly,
however, you should see the words “BUILD SUCCESSFUL”. If so, you have
just made your first successful application.
What if you see the words “BUILD FAILED”? Your code likely has some
sort of syntax error. Don’t worry, because dealing with such errors is easier to
do with a dedicated IDE, like Netbeans. Errors will be displayed in your
Output widow, and they will be displayed as hyperlinks. If you want to find
out an error’s source, double click on its hyperlink. This will make it easy for
you to change the error. After that, you can run your project again, and see if
you solved the problem.
In the navigation window, you click on the Files tab, then expand Hello
World App > build > classes > helloworldapp . This is the class file that was
generated for your project.
Once you have built the project, and seen that there are no issues with it, you
can officially run it. The the main menu, click Run > Run Main Project.
The program will print the text “Hello World!” in your Output window, as
well as some other build script output.
class HelloWorldApp {
System.out.println("Hello World!"); // Display string.
}
}
There are three basic components that make up your application, which are:
This creates a class definition, telling the code which class to use for the
following code. The curly brackets that follow will then surround the code
that you want to use for that particular class. This can get quite a lot more
complicated, but you only need to learn the basics for now.
Comments in the Source Code
Take a look at the text that was written after the // in your code. That is a
comment, which the compiler will have ignored completely. They are for the
eyes of programmers only. You might feel that you don’t need to add
comments in your codes, since you already know why you did certain things.
Keep in mind that many codes become extremely long and complicated. It is
easy to become lost, or forget why you did certain things, so creating
comments is always important. They are also helpful when other
programmers need to work with code that you create, so they can easily find
their way around, and understand everything.
There are three different types of comments, and they each work a little
differently:
The compiler will ignore everything between the /** and */ but the comment
will be considered a “doc comment”. This is short for documentation
comment. All doc comments can be compiled with an automated tool later,
making it easy to create a reference document.
// text
/* your comment */
When you use this type of comment, everything withing the */ and */ will be
ignored by your compiler.
Your Main Method
Finally, take a look at the line that actually tells your application what your
HelloWorldApp class does:
System.out.println("Hello World!");
The System class comes from Java’s fundamental library. It simply tells it to
print “Hello World!” as standard output. This is why, when you run your
application, it prints these words on the screen.
More Definitions
Objects
You have already dealt with objects, and learned a little about them. Now that
you have completed a practical exercise in coding, it is time to look at some
more theory about objects, and what they do. In Java, objects are essential, as
it is an object-oriented language. It’s not the only language that works in this
way, but this is one of the most popular features of Java.
To get a better understanding of objects, look around you right now. You can
probably see many different objects, from the computer that you are using, to
your chair, your dog, and even other people near you. Consider a dog as if it
were an object in Java. It has its own state (name, breed, color), as well as
behavior (wagging its tail, sleeping, barking). To get a better understanding
of how objects work in Java, try thinking of different real-world objects in
terms of their state, and their behavior.
Pay careful attention here, because this is one of the things that makes object-
oriented languages so unique. An object’s behavior is exposed through a
method. These methods are guided by the state of an object, and tell it how to
act with other objects. Objects in Java work with internal states, which other
objects cannot directly access. This is called data encapsulation.
Think about a dog as an object in Java again. While that object has certain
behaviors (methods), which let you observe and interact with the dog, you are
not aware of its internal state. You cannot change the dogs internal state
directly, unless you deal with its outside behavior.
This type of programming has some great advantages over coding that isn’t
object-oriented:
● Inbuilt hiding. Other objects only interact with the methods
(behaviors) of an object, so the internal state can remain hidden.
● Modular. Objects can be coded and worked on outside of a larger
piece of code (application). After an object is finished, it can then be
introduced to the source code, where it can interact with other objects.
● Debugging and pluggability. If you find that an object isn’t
working properly, it is easy to remove for debugging. Plugging in a
different object is then simple, to see if that will work better. In this
way, programmers only need to replace objects, instead of fixing entire
applications.
● Re-using Code. If someone has already created a certain object that
is appropriate for another application, it’s easy to re-use it.
Classes
You have also looked at classes, and even worked with using one in your
own application. Take a look into them more deeply, to find out what they
are really about. Think about the real world that you live in again. There are
plenty of different objects that are the same type. For example, there are
many different cars in the world. Even those that are the same model, will
have differences.
All cars are essentially the same kind of object, with the same basic
components, even when there are variations. You can think of one car as a
particular instance of a class of objects, called cars. You can think of a class
as a kind of basic plan for an object.
Inheritance
Many objects are different, but they often have a certain number of things in
common with other objects. Think about cars again, and the many different
models and types that are out in the world. They all have a number of the
same characteristics at any point in time, such as a current speed, the gear
they are in, and an amount of petrol in their engine.
All of those cars will have certain features that are different from some other
cars. These include the number of seats they have, the type of engine, and the
legal class of car that they are.
In object-oriented languages like Java, a class can inherit other behaviors and
states from different classes. The class of car could become truck, bus, or
van. The general class of car would then be considered a superclass for these
other classes. A class can have just one superclass, which can in turn have as
many subclasses as you would like.
If you want to make a subclass (truck) for your superclass (car), you can use
the following syntax:
This would tell your code that truck contains the same methods and fields as
car. However, it would allow you to create new features that make a truck
different from a car.
When you are making a new superclass, be sure that you write documentation
notes to describe any new behavior and state that you give it. This is
important, because you will not be able to see this information in the source
files of your subclasses.
Java Code Examples
This section assumes that you know a little about coding, or that you are
willing to experiment yourself. As you can see, there are notes within the
codes, so that you can see what they do. This is where you can just have
some fun, and play around with some pre-built codes. First, paste them into
your Netbeans source editor window, built them, and run them. You will see
that they work, and you can then play around to experience how they work.
Calling Methods
Here is a coding some that calls methods within the same class.
/* CallingMethodsInSameClass.java
*
* illustrates how to call static methods a class
* from a method in the same class
*/
x = 3;
int y = 5;
String s6 = x + y + "total";
String s7 = "total " + x + y;
String s8 = " " + x + y + "total";
System.out.println("s6: " + s6);
System.out.println("s7: " + s7);
System.out.println("s8: " + s8);
}
}
Value Parameters
Parameters are all passed by value in Java. This example code shows you value
parameter’s behavior.
alterPointer(r1);
System.out.println("In method go. r1 " + r1 + "\n");
}
}
Array Examples
//Mike Scott
//examples of array manipulations
int indexOfMin = 0;
for(int i = 1; i < list.length; i++)
{ if(list[i] < list[indexOfMin])
{ indexOfMin = i;
}
}
return indexOfMin;
}
/*
*pre: list != null, newSize >= 0
*post: nothing. the method does not succeed it resizing the
* argument
*/
public static void badResize(int[] list, int newSize)
{ assert list != null && newSize >= 0 : "failed precondition";
/*
*pre: list != null, newSize >= 0
*post: returns an array of size newSize. Elements from 0 to newSize - 1
* will be copied into the new array
*/
public static int[] goodResize(int[] list, int newSize)
{ assert list != null && newSize >= 0 : "failed precondition";
return result;
}
/*
*pre: list != null
*post: prints out the indices and values of all pairs of numbers
*in list such that list[a] + list[b] = target
*/
public static void findAndPrintPairs(int[] list, int target)
{ assert list != null : "failed precondition";
/*
*pre: list != null;
*post: sort the elements of list so that they are in ascending order
*/
public static void bubblesort(int[] list)
{
assert list != null : "failed precondition";
int temp;
boolean changed = true;
for(int i = 0; i < list.length && changed; i++)
{ changed = false;
for(int j = 0; j < list.length - i - 1; j++)
{ assert (j > 0) && (j + 1 < list.length) : "loop counter j "
+j+
"is out of bounds.";
if(list[j] > list[j+1])
{ changed = true;
temp = list[j + 1];
list[j + 1] = list[j];
list[j] = temp;
}
}
}
return ascending;
}
}
Connecting to a Webpage and Reading from It
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
/**
* A class to provide a simple list.
* List resizes automatically. Used to illustrate
* various design and implementation details of
* a class in Java.
*
* @author scottm
*
*/
public class GenericList{
// class constant for default size
private static final int DEFAULT_CAP = 10;
//instance variables
// iValues store the elements of the list and
// may have extra capacity
private Object[] iValues;
private int iSize;
/**
* Default add method. Add x to the end of this IntList.
* Size of the list goes up by 1.
* @param x The value to add to the end of this list.
*/
public void add(Object x){
insert(iSize, x);
}
/**
* Insert obj at position pos.
* post: get(pos) = x, size() = old size() + 1
* @param pos 0 <= pos <= size()
* @param obj The element to add.
*/
public void insert(int pos, Object obj){
ensureCapcity();
for(int i = iSize; i > pos; i--){
iValues[i] = iValues[i - 1];
}
iValues[pos] = obj;
iSize++;
}
/**
* Return a String version of this list. Size and
* elements included.
*/
public String toString(){
// we could make this more efficient by using a StringBuffer.
// See alternative version
String result = "size: " + iSize + ", elements: [";
for(int i = 0; i < iSize - 1; i++)
result += iValues[i].toString() + ", ";
if(iSize > 0 )
result += iValues[iSize - 1];
result += "]";
return result;
}
/**
* Default constructor. Creates an empty list.
*/
public GenericList(){
//redirect to single int constructor
this(DEFAULT_CAP);
//other statments could go here.
}
/**
* Constructor to allow user of class to specify
* initial capacity in case they intend to add a lot
* of elements to new list. Creates an empty list.
* @param initialCap > 0
*/
public GenericList(int initialCap) {
assert initialCap > 0 : "Violation of precondition. IntListVer1(int initialCap):"
+ "initialCap must be greater than 0. Value of initialCap: " + initialCap;
iValues = new Object[initialCap];
iSize = 0;
}
/**
* Return true if this IntList is equal to other.<br>
* pre: none
* @param other The object to compare to this
* @return true if other is a non null, IntList object
* that is the same size as this IntList and has the
* same elements in the same order, false otherwise.
*/
public boolean equals(Object other){
boolean result;
if(other == null)
// we know this is not null so can't be equal
result = false;
else if(this == other)
// quick check if this and other refer to same IntList object
result = true;
else if( this.getClass() != other.getClass() )
// other is not an IntList they can't be equal
result = false;
else{
// other is not null and refers to an IntList
GenericList otherList = (GenericList)other;
result = this.size() == otherList.size();
int i = 0;
while(i < iSize && result){
result = this.iValues[i].equals( otherList.iValues[i] );
i++;
}
}
return result;
}
}
Writing Ints onto File
import java.io.PrintStream;
import java.io.IOException;
import java.io.File;
import java.util.Random;
// show results
for(String word : wordCount.keySet())
System.out.println(word + " " + wordCount.get(word));
System.out.println(wordCount.size());
}
catch(IOException e) {
System.out.println("Unable to read from file.");
}
}
}
Published By:
C Tech Publishing
Manufactured in Canada
Copyright 2015 © All Rights Reserved