You are on page 1of 16

INTRODUCTION TO PROGRAMMING USING JAVA

What is JAVA?

Java is a programming language which was developed in 1995 by James Gosling of Sun Microsystems
(now Oracle).

Brief History of Java

James Gosling initiated the Java language project in June 1991 for use in one of his many set-top box
projects. The language, initially called Oak after an oak tree that stood outside Gosling’s office, also went
by the name Green and ended up later being renamed as Java, from a list of random words.

The original motivation for Java was the need for platform-independent language that could be embedded
in various consumer electronic products like toasters and refrigerators. One of the first projects developed
using Java was a personal hand-held remote control named Star 7.

Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere
(WORA), providing no-cost run-times on popular platforms.

On November 13, 2006, Sun released much of Java as free and open source software under the terms of
the GNU General Public License (GPL).

On May 8, 2007, Sun finished the process, making all of Java’s core code free and open-source, aside from
a small portion of code to which Sun did not hold the copyright.

JAVA is:
 Object-oriented: In Java, everything is an object. Java can be easily extended since it is based on
the object model.
 Platform-independent: Unlike many other programming languages including C and C++, when
Java is complied, it is not complied into platform specific machine, rather into platform-
independent byte code. This byte code is distributed over the web and interpreted by virtual
machine (JVM) on whichever platform it is being run.
 Simple: With Java’s secure feature, it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
 Architecture-neutral: Java compiler generates an architecture-neutral object file format, which
makes the compiled code to be executable on many processors, with the presence of Java runtime
system.
 Portable: Being architecture-neutral and having no implementation-dependent aspects of the
specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability
boundary which is a POSIX subset.
 Robust: Java makes an effort to eliminate error-prone situations by emphasizing mainly on
compile time error checking and runtime checking.
 Multithreaded: With Java’s multithreaded feature, it is possible to write programs that can do
many tasks simultaneously. This design feature allows developers to construct smoothly running
interactive applications.
 Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an
incremental and lightweight process.
 High Performance: With the use of Just-In-Time compilers, Java enables high performance.
 Distributed: Java is designed for the distributed environment of the internet.
 Dynamic: java is considered to be more dynamic than C or C++ since it is designed to adapt to an
evolving environment. Java programs can carry extensive amount of run-time information that
can be used to verify and resolve accesses to objects on run-time.

Phases of a Java Program


Basic Java Program

public class Hello


{
/**
* My first Java program
*/
public static void main (String[] args)
{
//prints the string “Hello World!” on screen
System.out.println(“Hello World!”);

}
}

Output:

Hello World!

Basic Syntax:

About Java programs it is very important to keep in mind the following points:

 Case sensitivity – Java is case sensitive, which means the identifier Hello and hello would have
different meaning in Java.
 Class names – For all class names, the first letter should be in upper case

If several words are used to form a name of the class, each inner word’s first letter should be in
upper case.

Example: public class MyFirstJavaClass

 Method Names – all method names should start with a lower-case letter.

If several words are used to form a name of the method, then each inner word’s first letter should
be in upper case.

Example: public void myMethodName()

 Program File Name – The name of the program file should exactly match the class name.

When saving the file, you should save it using the class name (Remember Java is case-sensitive)
and append ‘.java’ to the end of the name (if the file name and the class name do not match, your
program will not compile).
Example: Class name is “MyFirstJavaProgram”, then the file should be saved as
“MyFirstJavaProgram.java”

COMMENTS

Comments are notes written to a code for documentation purposes. Those text are not part of the
program and does not affect the flow of the program.

Java supports three types of comments: C++ style single line comments, C-style multiline comments and
special Javadoc comments.

C++ Style Comments

C++ style comments start with //. All the text after // are treated as comments.

Example:

//This is a C++ style or single line comment.

C-Style Comments

C-style comments or also called multiline comments starts with a /* and ends with a */. All text in between
the two delimiters are treated as comments. Unlike C++ style comments, it can span multiple lines.

Example:

/* This is an example of a
C-style or multiline comments*/

Special Javadoc Comments

Special Javadoc comments are used for generating HTML documentation for your Java programs. You can
make Javadoc comments by starting the line with /** and ending it with */. Like C-style comments, it can
also span lines. It can also contain certain tags to add more information to your comments.

Example:

/**
This is an example of special Javadoc comment used for
generating an HTML documentation. It uses tags like:
@author Juan dela Cruz
@version 2.0
*/
Java Statements and Blocks

A statement is one or more lines of code terminated by a semicolon.

Example:

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

A block is one or more statements bounded by an opening and closing curly braces that groups the
statements as one unit. Block statements can be nested indefinitely. Any amount of white space is
allowed.

Example:

public static void main (String[] args){

System.out.println(“Hello”);
System.out.println(“Hi”);

Java Identifiers

Identifiers are tokens that represent names of variables, methods, classes, etc.

Examples: Hello, main, System, out

Java identifiers are case-sensitive. This means that the identifier: Hello is not the same as hello.
Identifiers must begin with either a letter, an underscore “_”, or a dollar sign “$”. Letters may be lower
or upper case. Subsequent characters may use numbers 0 to 9.

NOTE:
 For names of classes, capitalize the first letter of the class name. For names of methods and
variables, the first letter of the word should start with a small letter.

Example:

MyClass, ClassName

myMethod, methodName

degreesToFahrenheit

 All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
 After the first character, identifiers can have any combination of characters.
 A keyword cannot be used as an identifier.
 Avoid using underscores at the start of the identifier such as _read or _write.
 Examples of legal identifiers: age,$salary, _value, _1_value
 Examples of illegal identifiers: 123abc, -salary

Java Keywords

Keywords are predefined identifiers reserved by Java for a specific purpose. You cannot use keywords as
names for your variables, classes, methods, etc.

Note: true, false and null are not keywords but they are reserved words, so you cannot use them as
names in your programs either.

JAVA LITERALS

Literals are tokens that do not change or are constant. The different types of literals in Java are: integer
literals, floating-point literals, Boolean literals, character literals and String literals.

Integer Literals

Integer literals come in different formats: decimal (base 10), hexadecimal (base 16), and octal (base 8).
In using integer literals in our program, we have to follow some special notations.

For decimal numbers, there are no special notations. Just write a decimal number as it is. For hexadecimal
numbers, it should be preceded by “0x” or “0X”. For octal, they are preceded by “0”.
Example:

Consider the number: 12

Decimal: 12
Hexadecimal: 0xC
Octal: 014

Integer literals default to the data type int. An int is a signed 32-bit value. In some cases, you may wish to
force integer literal to the data type long by appending the “l” or “L” character.

Floating-Point Literals

Floating point literals represent decimals with fractional parts. An example is 3.1415. Floating point literals
can be expressed in standard or scientific notations.

Example:

583.45 – standard notation


5.8345e2 – scientific notation

Floating point literals default to the data type double which is a 64-bit value. To use a smaller (32-bit)
float, just append the “f” or “F” character.

Boolean Literals

Boolean literals have only two values, true or false.

Character Literals

Character literals represent single Unicode characters. A Unicode character is a 16-bit character set that
replaces the 8-bit ASCII character set. Unicode allows the inclusion of symbols and special characters from
other languages.

To use a character literal, enclose the character in single quote delimiter.

Example:

Letter a is represented as ‘a’

To use special characters such as a newline character, a backslash is used followed by the character code.
For example, ‘\n’ for the newline character, ‘\r’ for the carriage return, ‘\b’ for backspace.

String Literals

String literals represent multiple characters and are enclosed by double quotes. An example of a string
literal is, “Hello world!”
DATA TYPES

Primitive Data Types

The Java programming language defines eight primitive data types:


1. boolean (for logical)
2. char (textual)
3. byte
4. short
5. int
6. long (integral)
7. double (floating point)
8. float (floating point)

Logical – boolean

A boolean data type represents two states: true and false.

Example:

boolean result = true;

Textual – char

A character data type (char), represents a single Unicode character. It must have its literal enclosed in
single quotes (‘ ’)

Example:

char letter = ‘A’;


‘a’ //The letter a
‘\t’ //A tab

To represent special characters like ‘ (single quote) or “ (double quotes), use the escape character \.

Example:

‘\’’ //for single quotes


‘\”’ //for double quotes

String is not a primitive data type (it is a Class). A String represents a data type that contains multiple
characters. It is not a primitive data type, it is a class. It has it’s literal enclosed in double quotes (“ ”).

Example:

String message = “Hello, how are you?”;


Integral – byte, short, int & long

Integral data types in Java uses three forms – decimal, octal or hexadecimal.

Example:

2 //The decimal value 2


077 //The leading 0 indicates an octal value
0xABC //The leading 0x indicates a hexadecimal value

Integral data types has int as default data type. You can it as long value by appending the letter l or L.
Integral data types have the following ranges:

Floating Point – float and double

Floating point types has double as default data type. Floating-point literal includes either a decimal point
or one of the following:

E or e //add exponential value


F or f //float
D or d //double

Example:

3.14 //A simple floating-point value (a double)


6.02E23 //A large floating-point value
2.718F //A simple float size value
123.4E+360D //A large double value with redundant D
VARIABLES

A variable is an item of data used to store state of objects.

A variable has a data type and a name. The data type indicates the type of value that the variable can
hold. The variable name must follow rules for identifiers.

Declaring and Initializing Variables

To declare a variable is as follows,

<data type> <name> [=initial value];

NOTE: Values enclosed in <> are required values, while those values enclosed in [] are optional.

Coding Guidelines:
1. It is always good to initialize the variables as you declare them.
2. Use descriptive names for your variables.

Example:

If you want to have a variable that contains a grade for a student, name it as, grade and
not just random letters you choose.

3. Declare one variable per line of code.

Example:

Preferable:

double exam = 0;
double quiz = 10;
double grade = 0;

Not preferable:

double exam = 0, quiz = 10, grade=0;


Example:

public class VariableSamples{


public static void main(String[] args){

//declare a data type with variable name


//result and boolean data type

boolean result = true;

//declare a data type with variable name


//option and char data type
char option;
option = 'C'; //assign 'C' to option

//declare a data type with variable name


//grade, double data type and initialized to 0.0

double grade = 0;

//make a conditional for the variable grade


//if grade is equal to 0.0 then print the variable result
//else print the variable option
if (grade==0.0){
System.out.print(result);
}else{
System.out.print(option);
}

}
}

Displaying the Variable Data

In order to output the valued of a certain variable, we can use the following commands,

System.out.println();
System.out.print();

Example:

public class Hello{


public static void main(String[] args){

int value = 10;


char x;
x = 'A';

System.out.println(value);
System.out.print("The value of x is " + x);
}
}
System.out.println() vs. System.out.print()

System.out.println(); - appends a newline at the end of the data to output


System.out.printn(); - does not append a newline at the end of the data

public class Hello{


public static void main(String[] args){

System.out.print("Hello ");
System.out.print("World!");

OUTPUT:

Hello World!

public class Hello{


public static void main(String[] args){

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

OUTPUT:

Hello
World!

Reference Variables vs. Primitive Variables

Primitive Variables are variables with primitive data types. They store data in the actual memory location
of where the variable is.

Reference Variables are variables that stores the address in the memory location. It points to another
memory location of where the actual data is. When you declare a variable of a certain class, you are
actually declaring a reference variable to the object with that certain class.
Example:

int num = 10;


String name = “Hello”;

 For the primitive variable num, the data is on the actual location where the variable is. For the
reference variable name, the variable just holds the address of where the actual data is.

OPERATORS

In Java, there are different types of operators. There are arithmetic operators, relational operators, logical
operators and conditional operators. These operators follow a certain kind of precedence so that the
compiler will know which operator to evaluate first in case multiple operators are used in one statement.
Arithmetic Operators

Increment and Decrement Operators

Aside from the basic arithmetic operators, Java also includes a unary increment operator (++) and unary
decrement operator (--). Increment and decrement operators increase and decrease a value stored in a
number variable by 1.

Example:

count = count + 1; //increment the value of count by 1

is equivalent to,

count++;

The increment and decrement operators can be place before or after an operand.

When used before an operand, it causes the variable to be incremented or decremented by 1, and then
the new value is used in the expression in which it appears.

Example:

int i = 10;
int j = 3;
int k = 0;

k = ++j + i; //will result to k = 4 + 10 = 14


When the increment and decrement operators are placed after the operand, the old value of the
variable will be used in the expression where it appears.

Example:

int i = 10;
int j = 3;
int k = 0;
k = j++ + k; //will result to k = 3 + 10 = 13

Relational Operator

Relational operators compare two values and determines the relationship between those values. The
output of evaluation are the boolean values true or false.