Java Basics
Java Basics
Java Basics
Java Basics 2
What is Java?
Java Example
Let's have a quick look at Java programming example. A detailed description of hello Java
example is available in next page.
class Simple{
System.out.println("Hello Java");
}
3
}
Application
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:
Mobile
Embedded System
Smart Card
Robotics
Games, etc.
There are mainly 4 types of applications that can be created using Java programming:
4
Application
1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called enterprise application.
It has advantages of the high-level security, load balancing, and clustering. In Java, EJB is used for creating
enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android and
Java ME are used for creating mobile applications.
5
Application
Object-oriented
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
6
Java Basics 7
8
Application
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which are
compiled into platform specific machines while Java is a write once, run anywhere language. A platform is
the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-based
platform.
The Java platform differs from most other platforms in the sense that it is a software-based platform that runs
on the top of other hardware-based platforms. It has two components:
Runtime Environment
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java
code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms, i.e., Write Once and Run Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
9
Java Basics 10
The Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual
Machine. The Java run time system does not need to know about files and file systems because of classloaders.
Java classes aren’t loaded into memory all at once, but when required by an application. At this point, the Java
ClassLoader is called by the JRE and these ClassLoaders load classes into memory dynamically.
11
Java Basics 12
Java Basics 13
Application
Creating Hello World Example
1. class Simple{
3. System.out.println("Hello Java");
4. }
5. }
To compile:
javac Simple.java
To execute:
java Simple
Output:Hello Java
14
Difference between JDK, JRE, and JVM
We must understand the differences between JDK, JRE, and JVM before proceeding further to Java. See the
brief overview of JVM here.
If you want to get the detailed knowledge of Java Virtual Machine, move to the next page. Firstly, let's see
the differences between the JDK, JRE, and JVM.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can be
executed. It can also run those programs which are written in other languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent
because the configuration of each OS is different from each other. However, Java is platform independent.
There are three notions of the JVM: specification, implementation, and instance.
Loads code
Verifies code
Executes code
15
Difference between JDK, JRE, and JVM
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to provide
the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries +
other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development
environment which is used to develop Java applications and applets. It physically exists. It contains JRE +
development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to
complete the development of a Java Application.
16
Difference between JDK, JRE, and JVM
Example to understand the types of variables in java
class A{
void method(){
}//end of class
17
Difference between JDK, JRE, and JVM
Java Variable Example: Add Two Numbers
class Simple{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}}
Output:
20
18
Difference between JDK, JRE, and JVM
Java Variable Example: Widening
class Simple{
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}}
Output:
1010.0
19
Difference between JDK, JRE, and JVM
Java Variable Example: Narrowing (Typecasting)
class Simple{
float f=10.5f;
//int a=f;
int a=(int)f;
System.out.println(f);
System.out.println(a);
Output:
10.510
20
Java Type Casting
Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
21
How Java Works
Java's platform independence is achieved by the use of the Java Virtual Machine
A Java program consists of one or more files with a .java extension
– these are plain old text files
When a Java program is compiled the .java files are fed to a compiler which produces a
.class file for each .java file
The .class file contains Java bytecode.
Bytecode is like machine language, but it is intended for the Java Virtual Machine not a
specific chip such as a Pentium or PowerPC chip
Java Basics 22
More on How Java Works
To run a Java program the bytecode in a .class file is fed to an interpreter which converts
the byte code to machine code for a specific chip (IA-32, PowerPC)
Some people refer to the interpreter as "The Java Virtual Machine" (JVM)
The interpreter is platform specific because it takes the platform independent bytecode
and produces machine language instructions for a particular chip
So a Java program could be run an any type of computer that has a JVM written for it.
– PC, Mac, Unix, Linux, BeaOS, Sparc
Java Basics 23
A Picture is Worth…
The output of the
compiler is .class
file
Java Basics 34
Data Types
Primitive Data Types
– byte short int long float double boolean char
//dataType identifier;
int x;
int y = 10;
int z, zz;
double a = 12.0;
boolean done = false, prime = true;
char mi = 'D';
– stick with int for integers, double for real numbers
Classes and Objects
– pre defined or user defined data types consisting of constructors,
methods, and fields (constants and fields (variables) which may be
primitives or objects.)
CS 307 Fundamentals of Java Basics 35
Computer Science
Java Primitive Data Types
Data Characteristics Range
Type
byte 8 bit signed integer -128 to 127
Java Basics 38
Built in Classes
Java has a large built in System
library of classes with lots Arrays
of useful methods Scanner
Ones you should become File
familiar with quickly
Object
String
Random
Math
Look at the Java API
Integer, Character, page
Double
Java Basics 39
import
import is a reserved word
packages and classes can be imported to another
class
does not actually import the code (unlike the C++
include preprocessor command)
statement outside the class block
import java.util.ArrayList;
import java.awt.Rectangle;
public class Foo{
// code for class Foo
}
CS 307 Fundamentals of Java Basics 40
Computer Science
More on import
can include a whole package
– import java.util.*;
or list a given class
– import java.util.Random;
instructs the compiler to look in the package for types it
can't find defined locally
the java.lang.* package is automatically imported to all
other classes.
Not required to import classes that are part of the same
project in Eclipse
Java Basics 41
The String Class
String is a standard Java class
– a whole host of behaviors via methods
also special (because it used so much)
– String literals exist (no other class has literals)
String name = "Mike D.";
– String concatenation through the + operator
String firstName = "Mike";
String lastName = "Scott";
String wholeName = firstName + lastName;
– Any primitive or object on other side of + operator from
a String automatically converted to String
Java Basics 42
Standard Output
To print to standard output use
System.out.print( expression ); // no newline
System.out.println( expression ); // newline
System.out.println( ); // just a newline
Java Basics 45
Operators
Basic Assignment: =
Arithmetic Operators: +, -, *, /, %(remainder)
– integer, floating point, and mixed arithmetic and
expressions
Assignment Operators: +=, -=, *=, /=, %=
increment and decrement operators: ++, --
– prefix and postfix.
– avoid use inside expressions.
int x = 3;
x++;
CS 307 Fundamentals of Java Basics 46
Computer Science
Expressions
Expressions are evaluated based on the
precedence of operators
Java will automatically convert numerical
primitive data types but results are sometimes
surprising
– take care when mixing integer and floating point
numbers in expressions
The meaning of an operator is determined by its
operands
/
is it integer division or floating point division?
CS 307 Fundamentals of Java Basics 47
Computer Science
Casting
Casting is the temporary conversion of a variable from its original
data type to some other data type.
– Like being cast for a part in a play or movie
With primitive data types if a cast is necessary from a less
inclusive data type to a more inclusive data type it is done
automatically.
int x = 5;
double a = 3.5;
double b = a * x + a / x;
double c = x / 2;
if a cast is necessary from a more inclusive to a less inclusive data
type the class must be done explicitly by the programmer
– failure to do so results in a compile error.
double a = 3.5, b = 2.7;
int y = (int) a / (int) b;
y = (int)( a / b );
y = (int) a / b; //syntax error
Java Basics 50
Control Structures
linear flow of control
– statements executed in consecutive order
Decision making with if - else statements
if(boolean-expression)
statement;
if(boolean-expression)
{ statement1;
statement2;
statement3;
}
A single statement could be replaced by a statement
block, braces with 0 or more statements inside
Java Basics 53
for Loops
for loops
for(init-expr;boolean-expr;incr-expr)
statement;
init-expr and incr-expr can be more zero or more
expressions or statements separated by commas
statement could be replaced by a statement block
false
execute evaluate
init-expr boolean-expr skip to 1st statement after
body of loop
true
execute execute
body of loop incr-expr
Java Basics 54
while loops
while loops
while(boolean-expression)
statement; //or statement block
do-while loop part of language
do
statement;
while(boolean-expression);
Again, could use a statement block
break, continue, and labeled breaks
– referred to in the Java tutorial as branching statements
– keywords to override normal loop logic
– use them judiciously (which means not much)
Java Basics 55
Attendance Question 3
True or false: Strings are a primitive data type in
Java.
A. TRUE
B. FALSE
56
Attendance Question 4
What is output by the following Java code?
int x = 3;
double a = x / 2 + 3.5;
System.out.println(a);
A. a
B. 5
C. 4.5
D. 4
E. 5.0
Java Basics 57
Arrays
Java Basics 58
Arrays in Java
"Should array indices start at 0 or 1? My compromise of 0.5 was rejected
without, I thought, proper consideration. "
– S. Kelly-Bootle
Java has built in arrays. a.k.a. native arrays
arrays hold elements of the same type
– primitive data types or classes
– space for array must be dynamically allocated with new operator. (Size is
any integer expression. Due to dynamic allocation does not have to be
constant.)
public void arrayExamples()
{ int[] intList = new int[10];
for(int i = 0; i < intList.length; i++)
{ assert 0 >= i && i < intList.length;
intList[i] = i * i * i;
}
intList[3] = intList[4] * intList[3];
}
CS 307 Fundamentals of Java Basics 59
Computer Science
Array Details
all arrays must be dynamically allocated
arrays have a public, final field called length
– built in size field, no separate variable needed
– don't confuse length (capacity) with elements in use
elements start with an index of zero, last index is length -
1
trying to access a non existent element results in an
ArrayIndexOutOfBoundsException (AIOBE)
Java Basics 60
Array Initialization
Array variables are object variables
They hold the memory address of an array object
The array must be dynamically allocated
All values in the array are initialized (0, 0.0, char
0, false, or null)
Arrays may be initialized with an initializer list:
int[] intList = {2, 3, 5, 7, 11, 13};
double[] dList = {12.12, 0.12, 45.3};
String[] sList = {"Olivia", "Kelly", "Isabelle"};
Java Basics 61
Arrays of objects
A native array of objects is actually a native array
of object variables
– all object variables in Java are really what?
– Pointers!
public void objectArrayExamples()
{ Rectangle[] rectList = new Rectangle[10];
// How many Rectangle objects exist?
rectList[5].setSize(5,10);
//uh oh!
for(int i = 0; i < rectList.length; i++)
{ rectList[i] = new Rectangle();
}
rectList[3].setSize(100,200);
}
Java Basics 62
Array Utilities
In the Arrays class, static methods
binarySearch, equals, fill, and sort methods for
arrays of all primitive types (except boolean) and
arrays of Objects
– overloaded versions of these methods for various data
types
In the System class there is an arraycopy method
to copy elements from a specified part of one
array to another
– can be used for arrays of primitives or arrays of
objects
Java Basics 63
The arraycopy method
static voidarraycopy(Object src, int srcPos,
Object dest, int destPos, int length)
Copies an array from the specified source
array, beginning at the specified position, to
the specified position of the destination array.
int[] list = new int[10];
// code to fill list
// list needs to be resized
int[] temp = new int[list.length * 2];
System.arraycopy(list, 0, temp, 0,
list.length);
list = temp;
Java Basics 64
2D Arrays in Java
Arrays with multiple dimensions may be
declared and used
int[][] mat = new int[3][4];
the number of pairs of square brackets
indicates the dimension of the array.
by convention, in a 2D array the first number
indicates the row and the second the column
Java multiple dimensional arrays are
handles differently than in many other
programming languages.
CS 307 Fundamentals of 65
Computer Science 2D Arrays
Two Dimensional Arrays
0 1 2 3 column
0 0 0 0 0
1 0 0 0 0
2 0 0 0 0
row
This is our abstract picture of the 2D array and treating
it this way is fine.
mat[2][1] = 12;
CS 307 Fundamentals of 66
Computer Science 2D Arrays
The Real Picture
0 1 2 3
0 0 0 0 0
0 1 2 3
mat 1 0 0 0 0
0 1 2 3
2 0 0 0 0
mat holds the memory address of an array with 3
elements. Each element holds the memory address
of an array of 4 ints
CS 307 Fundamentals of 67
Computer Science 2D Arrays
Arrays of Multiple Dimension
because multiple dimensional arrays are
treated as arrays of arrays of
arrays……multiple dimensional arrays can
be ragged
– each row does not have to have the same
number of columns
int[][] raggedMat = new int[5][];
for(int i = 0; i < raggedMat.length; i++)
raggedMat[i] = new int[i + 1];
CS 307 Fundamentals of 68
Computer Science 2D Arrays
Ragged Arrays
Ragged arrays are sometime useful, but
normally we deal with rectangular matrices
– each row has the same number of columns as
every other row
– use this a lot as precondition to methods that
work on matrices
working on matrices normally requires
nested loops
– why is this so hard?
CS 307 Fundamentals of 69
Computer Science 2D Arrays
Enhanced for loop
New in Java 5.0
a.k.a. the for-each loop
useful short hand for accessing all elements in an
array (or other types of structures) if no need to
alter values
alternative for iterating through a set of values
for(Type loop-variable : set-expression)
statement
logic error (not a syntax error) if try to modify an
element in array via enhanced for loop
Java Basics 74
Methods
methods are analogous to procedures and functions
in other languages
– local variables, parameters, instance variables
– must be comfortable with variable scope: where is a
variable defined?
methods are the means by which objects are
manipulated (objects state is changed) - much more
on this later
method header consists of
– access modifier(public, package, protected, private)
– static keyword (optional, class method)
– return type (void or any data type, primitive or class)
– method name
– parameter signature
Java Basics 75
More on Methods
local variables can be declared within methods.
– Their scope is from the point of declaration until the end
of the methods, unless declared inside a smaller block
like a loop
methods contain statements
methods can call other methods
– in the same class: foo();
– methods to perform an operation on an object that is in
scope within the method: obj.foo();
– static methods in other classes:
double x = Math.sqrt(1000);
Java Basics 76
static methods
the main method is where a stand alone Java program normally
begins execution
common compile error, trying to call a non static method from a
static one
public class StaticExample
{ public static void main(String[] args)
{ //starting point of execution
System.out.println("In main method");
method1();
method2(); //compile error;
}
Java Basics 79
Value Parameters vs.
Reference Parameters
A value parameter makes a copy of the argument it is sent.
– Changes to parameter do not affect the argument.
A reference parameter is just another name for the argument it is
sent.
– changes to the parameter are really changes to the argument
and thus are permanent
Java Basics 80
Value vs. Reference
// value // C++, reference
void add10(int x) void add10(int& x)
{ x += 10; } { x += 10; }
12 12 12
y x y x
Java Basics 82
Creating Correct Programs
methods should include pre conditions and post conditions
Preconditions are things that must be true before a method
is called
Postconditions are things that will be true after a method is
complete if the preconditions were met
it is the responsibility of the caller of a method to ensure the
preconditions are met
– the class must provide a way of ensuring the precondition is true
– the preconditions must be stated in terms of the interface, not the
implementation
it is the responsibility of the class (supplier, server) to
ensure the postconditions are met
Java Basics 83