Introduction To Java Programming
Introduction To Java Programming
James Tam
Java Vs. Java Script
James Tam
Java: History
James Tam
Java: History (2)
Intel microprocessor
James Tam
Java: History (3)
•It was believed that the logical next step for microprocessors
was to have them run intelligent consumer electronics
James Tam
Java History (4)
Wav file from “The Simpsons” © Fox, Image from the website of Sun Microsystems James Tam
Java History (5)
James Tam
Java: History (6)
James Tam
Java: History (7)
James Tam
Java: History (8)
James Tam
Java: Write Once, Run Anywhere
James Tam
History
•B led to C, C evolved into C++, and C++ set the stage for Java
•BCPL, developed by Martin Richards.
•BCPL influenced a language called B, invented by Ken
Thompson, which led to the development of C in the 1970s
•Throughout the history of programming, the increasing
complexity of programs has driven the need for better ways to
manage that complexity. C++ is a response to that need, C++ was
invented by Bjarne Stroustrup in 1979.
•Java was conceived by James Gosling, Patrick Naughton , Chris
Warth , Ed Frank, and Mike Sheridan at Sun Microsystems, Inc.
in 1991.
• This language was initially called “Oak” but was renamed “Java”
in 1995.
James Tam
Java and C++
James Tam
Byte Code
• Byte code is a highly optimized set of instructions designed to
be executed by the Java run-time system, which is called the
Java Virtual Machine (JVM). That is, in its standard form, the
JVM is an interpreter for bytecode.
• Translating a Java program into bytecode helps makes it much
easier to run a program in a wide variety of environments.
• Sun supplies its Just In Time (JIT) compiler for bytecode, which
is included in the Java 2 release. When the JIT compiler is part
of the JVM, it compiles bytecode into executable code.
James Tam
Java Virtual Machine(JVM)
• Programs written in Java are compiled into Java Byte Code, which
is then interpreted by a special Java Interpreter for a specific
platform, which is known as Java Virtual Machine(JVM).
• The Machine language for the Java Virtual Machine is called Java
Byte Code.
• The Java Interpreter running on any machine appears and behaves
like “virtual” processor chip, that is why the name-JVM.
• The JVM is an abstract machine designed to be implemented on the
top of existing processor. It hides the underlying operating system
from Java applications.
• JVM combines with Java API makes java Platform.
James Tam
Java: Write Once, Run Anywhere
James Tam
Compiled Programs With Different
Operating Systems
Windows
compiler
Executable (Windows)
Mac OS
Computer compiler
program
Executable (Mac)
UNIX
compiler
Executable (UNIX)
James Tam
Java Compiler
James Tam
Java Interpreter
• Java interpreter translates the Java bytecode into the code that can be
understood by the Operating System.
• Basically, A Java interpreter is a software that implements the Java virtual machine
and runs Java applications. As the Java compiler compiles the source code into the
Java bytecode, the same way the Java interpreter translates the Java bytecode into
the code that can be understood by the Operating System.
• When a Java interpreter is installed on any platform that means it is JVM (Java
virtual machine) enabled platform. It (Java Interpreter) performs all of the
activities of the Java run-time system. It loads Java class files and interprets the
compiled byte-code.
• some web browsers like Netscape and the Internet Explorer are Java enabled. This
means that these browsers contain Java interpreter. With the help of this Java
interpreter we download the Applets from the Internet or an intranet to run within
a web browser.
• The interpreter also serves as a specialized compiler in an implementation that
supports dynamic or "just in time," compilation which turns Java byte-code into
native machine instructions.
• Example: C:\> Java File1
James Tam
A High Level View Of Translating/Executing Java
Programs
Stage 1: Compilation
James Tam
A High Level View Of Translating/Executing Java
Programs (2)
James Tam
Creating, Compiling And Running Java Programs
On The Computer Science Network
filename.java
(Unix file)
Java compiler
javac
Java byte code
filename.class
To compile the program at the (UNIX file)
command line type "javac
filename.java"
Java Interpreter
java
To run the interpreter, at
the command line type
"java filename" James Tam
Which Java?
James Tam
Structured Programming
James Tam
Structured Programming
James Tam
Object-Oriented Programming
•Object-oriented programming organizes a program around its data
(that is, objects) and a set of well-defined interfaces to that data. An
object-oriented program can be characterized as data controlling
access to code
•All object-oriented programming languages provide mechanisms that
help us implement the object-oriented model. They are Abstraction,
encapsulation, inheritance, and polymorphism
•Abstraction: An essential element of object-oriented programming
is abstraction. Abstraction refers to the act of representing essential
features without including the background details or explanations.
• Encapsulation : Encapsulation is the way of combining both data
and the functions that operate on that data under a single unit. So
Encapsulation is the wrapping upof data and function that oprate on
the data into a single unit(called class) is known as Encapsulation.
James Tam
Inheritance: Inheritance is the process by which objects of one class acquire the properties of
objects of another class. Inheritance supports the concept of hierarchical classification.In OOP
,the concept of Inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it.This is possible by deriving a new
class from the existing one.
Polymorphism:Polymorphism allows one interface to be used for a set of actions i.e. one
name may refer to different functionality. There are two types of polymorphism :
Compile-time polymorphism
Runtime Polymorphism
In compiletime Polymorphism, method to be invoked is determined at the compile time.
Compile time polymorphism is supported through the method overloading concept in java.
In rumtime polymorphism, the method to be invoked is determined at the run time. The
example of run time polymorphism is method overriding. When a subclass contains a method
with the same name and signature as in the super class then it is called as method overriding.
James Tam
Java Program Structure
Documentation Section (Optional)
James Tam
• Documentation Section: It comprises a set of comments line giving the name
of the program,and other.
• Package Statement : The first statement allowed in a Java file is a package
statement. this statement declare a package name and informs the compiler that
the classes defined here belong to this package. Ex: package student;
• Import Statement: This statement instruct the interpreter to load the class
contained in the mentioned package followed by the import statement. Ex:
import student.*;
• Interface Statement: An interface is like a class and is used when we wish to
implement the multiple inheritance feature in program.
• Class Definition: A Java program may contain multiple class definition. these
classes are used to map the objects of real-world problem.
• Main Method Class: This class is the essential part of the program. The main
method creates objects of various classes and establish communication between
them.
James Tam
A Simple Application
Example 1.1
//This application program prints Welcome
//to Java!
package student;
James Tam
Program Explanation
• “class Welcome” defines the class Welcome. Here class is a keyword.
The main line Public static void main(String[]args):
• Public: The key word public is an access specifier that declare the main method is
accessible to all other classes.
• Static: The key word static declares this method as one that belongs to the entire class
and not a part of an objects of the class.Interpreter use this method before any objects
are created.
• Void: The type modifier void states that the main method does not return any value.
• main: main( ) is a method,must be declared as public, since it must be called
by code outside of its class when the program is started. The keyword static allows
main( ) to be called without having to instantiate a particular instance of the class. This
is necessary since main( ) is called by the Java interpreter before any objects are made.
• In main( ), there is only one parameter, String args[ ] declares a parameter named
args, which is an array of instances of the class String. args receives any command-
line arguments present when the program is executed.
James Tam
Java Output
• The Output Line: System.out.println(“………….”); The
Println Method is a member of the out object, which is a static
member of System class.
•Format:
System.out.print(<string or variable name one> + <string or variable name
two>..);
OR
System.out.println(<string or variable name one> + <string or variable name
two>..);
\t Horizontal tab
\r Carriage return
\n New line
\” Double quote
\\ Backslash
James Tam
Example Formatting Codes
James Tam
Variables
James Tam
Variable Naming Conventions In Java
• Compiler requirements
- Can’t be a keyword nor can the names of the special constants: true,
false or null be used
- Can be any combination of letters, numbers, underscore or dollar sign
(first character must be a letter or underscore)
James Tam
Declaring Variables: Syntax
•Format:
<type of information> <name of variable>;
•Example:
char myFirstInitial;
James Tam
Location Of Variable Declarations
}
}
James Tam
Scope of Variables
James Tam
Local Variable
•Local variables :
•Local variables are declared in methods, constructors, or blocks.
•Local variables are created when the method, constructor or block is
entered and the variable will be destroyed once it exits the method,
constructor or block.
•Access modifiers cannot be used for local variables.
•Local variables are visible only within the declared method,
constructor or block.
•Local variables are implemented at stack level internally.
•There is no default value for local variables so local variables should
be declared and an initial value should be assigned before the first
use
James Tam
Local Variable Example
Here age is a local variable. This is defined inside pupAge() method
and its scope is limited to this method only.
public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[])
{ Test test = new Test();
test.pupAge();
}
} This would produce following result: Puppy age is: 7
James Tam
Instance variables
• Instance variables are declared in a class, but outside a method, constructor or any block.
• When a space is allocated for an object in the heap a slot for each instance variable value is
created.
• Instance variables are created when an object is created with the use of the key word 'new'
and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object through out the class.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block in the class.
Normally it is recommended to make these variables private (access level).However
visibility for subclasses can be given for these variables with the use of access modifiers.
• Instance variables have default values. For numbers the default value is 0, for Booleans it is
false and for object references it is null. Values can be assigned during the declaration or
within the constructor.
• Instance variables can be accessed directly by calling the variable name inside the class.
However within static methods and different class ( when instance variables are given
accessibility) the should be called using the fully qualified name .
ObjectReference.VariableName.
James Tam
Instance Variable Example
• import java.io.*;
public class Employee{
public String name; // this instance variable is visible for any child class.
private double salary; // salary variable is visible in Employee class only.
public Employee (String empName)//The name variable is assigned in the constructor.
{ name = empName; }
public void setSalary(double empSal) // The salary variable is assigned a value.
{ salary = empSal; }
public void printEmp() // This method prints the employee details.
{ System.out.println("name : " + name );
System.out.println("salary :" + salary); }
public static void main(String args[])
{ Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
} } Output: name : Ransika salary :1000.0
James Tam
Class/Static Variable
• Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
• There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
• Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program stops.
• Visibility is similar to instance variables. However, most static variables are declared public
since they must be available for users of the class.
• Default values are same as instance variables. For numbers the default value is 0, for
Booleans it is false and for object references it is null. Values can be assigned during the
declaration or within the constructor. Additionally values can be assigned in special static
initializer blocks.
• Static variables can be accessed by calling with the class name . ClassName.VariableName.
• When declaring class variables as public static final, then variables names (constants) are all
in upper case. If the static variables are not public and final the naming syntax is the same
as instance and local variables.
James Tam
Class/Static variable example
•import java.io.*;
public class Employee{
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[])
{ salary = 1000;
System.out.println(DEPARTMENT+"average salary:"+salary);
} } This would produce following result:
•Development average salary:1000
•Note: If the variables are access from an outside class the constant
should be accessed as Employee.DEPARTMENT
James Tam
Java Constants
Example:
final int SIZE = 100;
James Tam
Atomic elements(Tokens) of Java
James Tam
•Separators
In Java, there are a few characters that are used as separators. The
most commonly used separator in Java is the semicolon.
Symbol Name Purpose
() Parentheses Used to contain lists of parameters in method
{} Braces Used to contain the values of automatically
initialized arrays. Also used to define a block
of code, for classes, methods, and local
scopes.
[ ] Brackets Used to declare array types
; Semicolon Terminates statements.
, Comma Separates consecutive identifiers in a variable
declaration
. Period Used to separate package names from
subpackages and classes. Also used to separate
a variable or method from a reference variable
James Tam
Java Keywords
James Tam
Common Java Operators / Operator Precedence
James Tam
Common Java Operators / Operator Precedence
James Tam
Common Java Operators / Operator Precedence
James Tam
Common Java Operators / Operator Precedence
James Tam
Common Java Operators / Operator Precedence
James Tam
Post/Pre Operators
The name of the online example is: Order1.java
James Tam
Conditional(Ternary) Operator
James Tam
Data Types
•Data types specify the size and type of values that can be stored.
•Two types : Primitive type(intrinsic,built-in)and Non-
Primitive(derived)
•Primitive type(intrinsic,built-in): Numeric(Integer,Floating),Non-
Numeric(Character,Boolean)
•Non-Primitive(Derived): Classes,Interface,Arrays
James Tam
Primitive Data Types
•Example:
import java.util.Scanner;
James Tam
Control Statement In Java
1.Simple If Statement
2.If … else Statement
3. Nested if … else statement
4.Else if ladder
James Tam
Simple if Statement
•The if statement is Java’s conditional branch statement. It can be
used to route program execution through two different paths.
•Syntax :
if (condition)
{
statement1;
}
•When the condition is true the Statement within the if is
executed. After that execution continues with the next statement
after the if statement.
• If the condition is false then the statement within the if is not
executed and the execution continues with the statement after the
if statement.
James Tam
Example of If Statement
•EX.
import java.util.Scanner;
class larger1
{
public static void main(String args[])
{
int x1,x2,x3,large;
Scanner s = new Scanner(System.in);
System.out.println("Enter value for x1 : ");
x1=s.nextInt();
System.out.println("Enter value for x2 : ");
x2=s.nextInt();
System.out.println("Enter value for x3 : ");
x3=s.nextInt();
large = x1;
if (x2 > large)
large = x2;
if (x3 > large)
large = x3;
System.out.println("\n\n\tLargest number = " + large);
}
} Output : Largest number = 20 James Tam
Decision Making: Simple If
Format:
if (test Expression)
{
Body
}
Example:
if (x != y)
{ System.out.println("X and Y are not equal");}
James Tam
Decision Making: If, Else
Syntax :
if (condition)
{
statement1;
}
else If the condition is true, then
{ statement1 is executed. Otherwise,
statement2 is executed. In no case
statement2;
will both statements be executed.
}
Example:
if (x < 0)
{ System.out.println("X is negative");}
else
{ System.out.println("X is non-negative");}
James Tam
Example Program: If-Else
import java.util.Scanner;
class result
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter marks : ");
int marks = s.nextInt();
if (marks<40)
System.out.println("\nThe student has failed .. ");
else
System.out.println("\nThe student has Passed .. ");
}
}
James Tam
Nested –If..Else
•Format:
if(test expression)
{
if(test expression)
{
body;
}
else
{ }
else
{
} James Tam
Else if Ladder
James Tam
Switch:
• The switch statement is Java’s is a multiway branch statement. It provides an
easy way to dispatch execution to different parts of your code based on the
value of an expression.
• The expression must be of type byte, short, int, or char; each of the values
specified in the case statements must be of a type compatible with the expression.
• Each case value must be a unique literal (constant, not a variable). Duplicate case
values are not allowed.
• The value of the expression is compared with each ‘case’ values. If a match is
found, the corresponding statement or statements are executed.
• If no match is found, statement or statements in the default case are executed.
Default statement is optional.
• If default statement is absent, then if no matches are found, then the switch
statement completes without doing anything.
• The break statement is used inside the switch to terminate a statement sequence
James Tam
Alternative To Multiple Else-If’s: Switch
1 The type of variable in the brackets can be a byte, char, short, int or long
James Tam
Alternative To Multiple Else-If’s: Switch (2)
1 The type of variable in the brackets can be a byte, char, short, int or long
James Tam
Switch: Example
import java.util.Scanner;
James Tam
Switch: Example
line = in.nextLine ();
letter = line.charAt(FIRST);
switch (letter)
{
case 'A':
case 'a':
gpa = 4;
break;
case 'B':
case 'b':
gpa = 3;
break;
case 'C':
case 'c':
gpa = 2;
break;
James Tam
Switch: When To Use/When Not To Use (4)
case 'D':
case 'd':
gpa = 1;
break;
case 'F':
case 'f':
gpa = 0;
break;
default:
gpa = -1;
}
System.out.println("Letter grade: " + letter);
System.out.println("Grade point: " + gpa);
}
}
James Tam
Iteration Statement(Loops)
James Tam
Iteration Statement(Loops)
Entry-controlled(Pre-test) loop:
•The control conditions are tested before the start of the loop
execution. If the conditions are not satisfied, then the body of
the loop will not be executed.
Example: for, while
exit-controlled(Post-test) loop:
• The control conditions are performed at the end of the body of
the loop and therefore the body of the loop executed at least
once.
Example: do-while
James Tam
For Loops
Format:
for (initialization; test condition; update control)
{ Body of the loop;
}
Example:
for (i = 1; i <= 4; i++)
{
// Call function
createNewPlayer();
i = i + 1;
}
Nested for Loop: Format: for(i=0li<10;i++)
{
for(j=0;j<10;j++)
{ }
}
James Tam
For loop variation
Format: Initialization;
while (test condition)
{
Body of the loop;
updating;
}
Example:
int i = 1;
while (i <= 4)
{
// Call function
createNewPlayer();
i = i + 1;
}
James Tam
Post-Test Loop: Do-While
•Recall: Post-test loops evaluate the text condition after the body
of the loop has executed.
•This means that post test loops will execute one or more times.
•Pre-test loops generally execute zero or more times.
James Tam
Do-While Loops
Format:
Initialization;
do
{
Body of the loop;
updating;
}while (test condition);
Example:
char ch = 'A';
do
{
System.out.println(ch);
ch++;
}
while (ch <= 'K');
James Tam
The Enhanced for Loop
• The enhanced for loop is also called for each loop , is an extended language feature
introduced with the J2SE5.0 release. This feature helps us to retrieve the array of
elements efficiently rather than using array indexes.
Format: for(Type identifier : Expression) { //statements; } where, type represents
the data type or object used, Identifier refers to the name of a variable; and
Expression is an instance of the java.lang.Iterable interface or an array.
• Example: public class Test {
public static void main(String args[])
{ int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){ System.out.print( x );
System.out.print(","); }
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names )
{ System.out.print( name );
System.out.print(","); } } }
James Tam
Jump Statements
James Tam