Tải bản đầy đủ (.pdf) (101 trang)

Java for beginners the complete guide to learning java for beginners

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (491.48 KB, 101 trang )


JAVA FOR BEGINNERS
THE COMPLETE GUIDE TO LEARNING JAVA FOR BEGINNERS

Bruce Berke
© 2018


Copyright 2018 by Bruce Berke - All rights reserved.

This document is geared towards providing exact and reliable information in regards to the topic and
issue covered. The publication is sold with the idea that the publisher is not required to render
accounting, officially permitted, or otherwise, qualified services. If advice is necessary, legal or
professional, a practiced individual in the profession should be ordered.
- From a Declaration of Principles which was accepted and approved equally by a Committee of the
American Bar Association and a Committee of Publishers and Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic
means or in printed format. Recording of this publication is strictly prohibited and any storage of this
document is not allowed unless with written permission from the publisher. All rights reserved.
The information provided herein is stated to be truthful and consistent, in that any liability, in terms of
inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained
within is the solitary and utter responsibility of the recipient reader. Under no circumstances will any
legal responsibility or blame be held against the publisher for any reparation, damages, or monetary
loss due to the information herein, either directly or indirectly.
Respective authors own all copyrights not held by the publisher.
The information herein is offered for informational purposes solely, and is universal as so. The
presentation of the information is without contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark is without
permission or backing by the trademark owner. All trademarks and brands within this book are for
clarifying purposes only and are the owned by the owners themselves, not affiliated with this
document.




Table of Contents
Introduction
Chapter 1: Getting Started with java
Chapter 2: Java Variables
Chapter 3: Java operators
Chapter 4: Java arrays
Chapter 5: Decision making
Chapter 6: looping
Chapter 7: Inheritance
Chapter 8: overriding
Chapter 9: Polymorphism
Chapter 10: Abstraction
Chapter 11- encapsulation
Chapter 12- Interfaces
Chapter 13- Packages
Chapter 14- Command-Line Arguments
Chapter 15- Recursion
Chapter 16- Method Calls
Chapter 17- Java Applets
Conclusion


INTRODUCTION
Java is a wide programming language, packed with lots of features good for application development.
It’s a good coding language for the design/development of desktop apps. These are popular as
standalone applications. If you need a distributed application, Java is the best language to use. Java
applets can be embedded/added on web pages. The many features offered by Java have made it a
popular coding language. Its wide features make it applicable in the development of apps applicable

in various industries. To code in Java, you should get the Java compiler. Java is compiled, not
interpreted. You need an editor in which you can write your Java codes. Notepad is good for this.
With these, you can start writing and running your Java codes. This means it’s easy to get started with
Java, making Java a good language for beginners. The Java bytecode, normally generated after
compiling Java source codes, is platform-independent, meaning it can be run on any platform
including Windows, Solaris, Linux, etc. Java apps are secured via public-key cryptography, making
them safe/secure. Java apps can be linked to various database management systems, for example,
MySQL, Oracle, SQL Server, etc. This book is an excellent guide on Java programming. Get it and
know every aspect of Java and transition from Java Beginner to Java Expert!


CHAPTER 1: GETTING STARTED WITH JAVA
Java is a platform as well as a coding language. It is a robust, high-level, object-oriented and
secured programming language. It was released in 1995 by the Sun Microsystems. Java treats
everything as an object. Its object model makes it easy to extend. The language is compiled, meaning
that we have a Java compiler. Java is also platform independent. After compiling your Java source
code, you get the byte code which can be executed on any platform. Java is also well known for being
easy to learn. If you know some basic concepts about object-oriented programming, it will be easy
for you to learn Java. It is packed with numerous features, making it widely functional.
Authentication in Java is done using a public-key encryption, making its systems very secure. This is
the reason we can develop temper-free and virus-free systems with Java. In Java, errors are
identified during the compile time, meaning that you cannot go to the run phase without first sorting
out the error.


ENVIRONMENT SETUP
For you to write and run Java programs, you need a text editor and the Java compiler. The Java
compiler comes with the JDK (Java Development Kit) which can be downloaded and installed for
free. You also need to have a text editor where you will be writing your Java programs. You can even
use a basic text editor like Notepad and it will be okay. However, there are advanced text editors for

Java such as Eclipse and Netbeans.
First, download and install the JDK on your computer. After that, you will have installed Java on
your machine. Open your browser then type or paste the following URL:
/>From there, you can get the latest version of the JDK. You will then have to set the environment
variables to know the right Java installation directories. This means you should set the path variable.
Mostly, the installation is done in the c:\Program Files\java\jdk directory. To set the path on
Windows, correctly “My Computer”, choose “Properties”, open the “Advanced” tab then choose
“Environment variables”. Add the “c:\Program Files\java\jdk\bin” path. For Linux users, read the
documentation of your shell.


JAVA SYNTAX
A Java program consists of objects communicating via invocation of methods from each other. Below
are the main constructs in a Java program:
Object- Objects are characterized by state and behavior. For example, a cat has states
like color, breed name and behaviors like eating, meowing and wagging tail.
Class- This is a blueprint/template describing the state/behaviors supported by its
objects.
Method- A method is a behavior. Logic is written in methods, and they are usable in data
manipulation.


FIRST PROGRAM
This is our first Java program. It should print “Hello World” once executed:
public class OurFirstProgram{
public static void main(String args[]){
System.out.println("Hello World");
}
}
Open your text editor like Notepad and create a new file named “FirstProgram.java. Save the file.

The .java extension marks the file as a Java file. Type the above program code in the file and save the
changes. Open the command prompt then navigate to the directory in which you have saved the file.
Run the commands given below from that directory:
javac FirstProgram.java
java FirstProgram
In my case, I saved the file on the desktop. I executed the commands as follows:


The program prints “Hello World” as the result. In the command “javac FirstProgram.java”, we are
invoking the java compiler (javac) to compile the program. The command returned nothing on the
command prompt since the program has no error, and no warning was generated. The command
generates a .class file (FirstProgram.class) in the directory; please confirm. In the command “java
FirstProgram”, we are simply running the program to give us the result.
Consider the following line extracted from the code:
public class FirstProgram{
The line simply declares a class named FirstProgram. Java is a case sensitive language, hence this
class must always be referred to as it is written above. The “public” keyword declares that class as
public, meaning it is accessible from any other class within the same package. The { declares the
beginning of the class body, and it should be closed by a }.
Note: The filename in which we write the program should match the class-name; otherwise, you
will experience trouble when running the program. In our case, the class was named
“FirstProgram”, hence the filename should be FirstProgram.java.
Consider the following line extracted from the code:
public static void main(String args[]){
That’s the main method. A java program cannot be executed or run without this method. Consider the
following line extracted from the code:
System.out.println("Hello World");
We are simply invoking or calling the “println” method to print the text Hello World on the terminal
of the command prompt.
Lastly, we have two closing curly braces, }}. The first one closes the opening brace for the main

method while the second one closes the opening brace for the class.


CHAPTER 2: JAVA VARIABLES
A variable can be seen as a container responsible for holding a value during the life of a program.
Each variable is of a certain data type, designative the kind of value that it can hold. There are two
steps in using Java variables, that is, variable declaration and variable initialization.


VARIABLE DECLARATION
The declaration of a variable involves giving it a name and specifying its data type. Below are
examples of valid variable declaration:
int x,j,z;
float pi;
double a;
char c;
The int, float, double and char are the data types, specifying the type of value each variable can or
should hold. To declare several variables in one line, separate them using a comma (,) as in the first
example. A variable declaration should end with a semicolon (;).


VARIABLE INITIALIZATION
Variable initializing involves assigning it a valid value. The value to be assigned to the variable is
determined by the variable’s data type. Below are examples of valid variable initializations.
pi =3.14f;
a =20.22778765;
c=’v’;
Both the declaration and initialization of a variable can be done at once as shown below:
int x=1,z=4,y=5;
float pi=3.14f;

double d=19.12d;
char c=’v’;


VARIABLE TYPES
Java supports three variable types:
1. Local Variables
2. Static Variables
3. Instance Variables


LOCAL VARIABLES
These are variables declared within a method body. They can only be accessed from within that
method.


INSTANCE VARIABLES
These are the variables that have been defined without the use of STATIC keyword. These variables
are specific to an object.


STATIC VARIABLES
These are variables initialized once at the beginning of the program execution. You should initialize
them before instance variables.
The following example demonstrates the different types of Java variables:
class JavaVariables {
int i = 10; //an instance variable
static int b = 2; //a static variable
void methodExample() {
int c = 3; //a local variable

}
}
The variable integer b is a static variable since it has been defined with the static keyword. The
variable int c has been declared within the methodExample method, making it a local variable. It can
only be accessed from within that method.


DATA TYPES
In Java, a data type can be either primitive or non-primitive.

PRIMITIVE DATA TYPES
These are the predefined data types that are already provided by Java. They are 8 in number including
byte, short, long, char, int, float, Boolean and double data types.

NON-PRIMITIVE DATA TYPES
These are defined by the use of defined class constructors. They help programmers access objects.
The example given below demonstrates the use of variables:
public class VariableAddition{
public static void main(String[] args){
int ax=5;
int jk=12;
int z=ax+jk;
System.out.println(z);
}
}
We have defined three integer variables x, j and z. The values for x and j have been initialized, while
the value for z is the addition of the previous two variables. We have then invoked the “println”
function to print the value of z. It should print 17, the result of the addition of 5 and 12.



TYPE CASTING AND TYPE CONVERSION
It is possible for a variable of a particular type to get a value of some other type. Type conversion is
when a variable of a smaller capacity is assigned a variable of a bigger capacity. Example:
double db;
int x=5;
db-x;
Type casting is when a variable of a larger capacity is assigned some other variable of a smaller
capacity. Example:
db =5;
int x;
x= (int) db;
The (int) is known as the type cast operator. If it is not specified, you get an error. Typecasting
example:
public class TypecastingExample{
public static void main(String[] args){
float ft=11.8f;
//int x=ft;//a compile time error
int x=(int)ft;
System.out.println(ft);
System.out.println(x);
}
}


CHAPTER 3: JAVA OPERATORS
Operators are symbols used to perform operations. For example, the + symbol is used for arithmetic
operations. Java supports different operators:


UNARY OPERATOR

This is an operator that takes one operand. They increment/decrement a value. They include ++
(increment) and - -(decrement). Example:
public class UnaryOperatorExample{
public static void main(String args[]){
int j=0;
System.out.println(j++);//from 0 to 1
System.out.println(++j);//2
System.out.println(j--);//1
System.out.println(--j);//0
}
}
The program will print 0, 2, 2, 0. The j++ means that the value of j is read first before the increment
is done, hence we got the value of j as 0. If it was ++j, then we would get a 1 as the first value of j.
You can try it.


ARITHMETIC OPERATORS
These operators are used for performing mathematical operations like multiplication, addition,
division, subtraction etc. They are used as mathematical operators. Example:
public class JavaArithmeticOperatorsExample{
public static void main(String args[]){
int x=0;
int y=10;
System.out.println(x+y);//10
System.out.println(x-y);//-10
System.out.println(x*y);//0
System.out.println(x/y);//0
System.out.println(x%7);//0
}
}

The only operator that may look unfamiliar is the % (modulus operator), which returns the remainder
after division.


LOGICAL OPERATORS
These operators are used together with the binary values. They help in evaluation of conditions in
loops and conditional statements. They include ||, &&, !. Suppose we have two Boolean variables, a1
and a2, the following conditions apply:
a1&&a2 will return true if both a1 and a2 are true; otherwise, they will return false.
a1||a2 will return false if both a1 and a2 are false; otherwise, they will return true.
!a1 will return opposite of a1.
Example:
public class LogicalOperatorExample {
public static void main(String args[]) {
boolean a1 = true;
boolean a2 = false;
System.out.println("a1 && a2: " + (a1&&a2));
System.out.println("a1 || a2: " + (a1||a2));
System.out.println("!(a1 && a2): " + !(a1&&a2));
}
}
The program will return false, true, true.


COMPARISON OPERATORS
Java supports 6 types of comparison operators, ==, !=, <, >, >=, <=:
== will return true if both the left and right sides are equal.
!= will return true if the left and right sides of the operator are not equal.
Returns true if the left side is greater than the right side.
< returns true if the left side is less than the right side.

>= returns true if the left side is greater than/equal to the right.
<= returns true if the left side is less than the right side.
Example:
public class JavaRelationalOperatorExample {
public static void main(String args[]) {
int n1 = 20;
int n2 = 30;
if (n1==n2) {
System.out.println("n1 and n2 are equal");
}
else{
System.out.println("n1 and n2 aren’t equal");
}
if( n1 != n2 ){
System.out.println("n1 and n2 aren’t equal");
}
else{
System.out.println("n1 and n2 are equal");
}
if( n1 > n2 ){
System.out.println("n1 is greater than n2");
}
else{
System.out.println("n1 isn’t greater than n2");


}
if( n1 >= n2 ){
System.out.println("n1 is equal to or greater than n2");
}

else{
System.out.println("n1 is less than n2");
}
if( n1 < n2 ){
System.out.println("n1 is less than n2");
}
else{
System.out.println("n1 isn’t less than n2");
}
if( n1 <= n2){
System.out.println("n1 is equal to or less than n2");
}
else{
System.out.println("n1 is greater than n2");
}
}
}
The program uses the if statement which is discussed in the next chapters.


×