Java Language Basics:
Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,
Expressions, Statements and Arrays.
Introduction to Java Technology
Java technology is:
A programming language
A development environment
An application environment
A deployment environment
It is similar in syntax to C++.
It is used for developing both applets and
applications
Primary Goals of the Java Technology
Provides an easy-to-use language by:
◦ Avoiding many pitfalls of other languages
◦ Being object-oriented
◦ Enabling users to create streamlined and clear code
Provides an interpreted environment for:
◦ Improved speed of development
◦ Code portability
Primary Goals of the Java Technology
Loads classes dynamically; that is, at the time they are actually needed
Supports changing programs dynamically during runtime by loading classes from disparate sources
Furnishes better security
Primary Goals of the Java Technology
The following features fulfill these goals:
◦ The Java Virtual Machine
◦ Garbage collection
◦ The Java Runtime Environment (JRE)
Feature of Java
Simple
Object-Oriented
Platform independent
Secured
Robust
Architecture neutral
Portable
Dynamic
Interpreted
High Performance
Multithreaded
Distributed
The Java Virtual Machine
Provides hardware platform specifications
Reads compiled byte codes that are platform-independent
Is implemented in a Java technology
development tool or a Web browser
Garbage collection
Allocated memory that is no longer needed should be deallocated.
In other languages, deallocation is the programmer’s responsibility.
The Java programming language provides a system-level thread to track memory
allocation.
Garbage collection
Garbage collection has the following characteristics:
◦ Checks for and frees memory no longer needed Is done automatically
◦ Can vary dramatically across JVM
implementations
The Java Runtime Environment
The Java application environment performs as
follows:
JVM™ Tasks
The JVM performs three main tasks:
Loads code
Verifies code
Executes code
The Class Loader
Loads all classes necessary for the execution of a program
Maintains classes of the local file system
in separate namespaces
The Bytecode Verifier
Ensures that:
◦ The code adheres to the JVM specification.
◦ The code does not violate system integrity.
◦ The code causes no operand stack overflows.
◦ The parameter types for all operational code are correct.
◦ No illegal data conversions (the conversion of
integers to pointers) have occurred.
Primitive Data Type
They are in-built part of the language.
These data type have the same size and
characteristics no matter what operating
system and platform you are on.
Primitive Data Types
Primitive Data Types
◦ Logical – boolean
◦ Textual – char
◦ Integral – byte, short, int, and long
◦ Floating – double and float
Logical
The boolean primitive has the following characteristics:
The boolean data type has two literals, true and false.
For example, the statement:
◦ boolean truth = true;
declares the variable truth as boolean type
and assigns it a value of true.
Textual – char
The textual char primitive has the following characteristics:
Represents a 16-bit Unicode character
Must have its literal enclosed in single quotes (’ ’)
Uses the following notations:
◦ 'a' The letter a
◦ '\t' The tab character
◦ '\u????' A specific Unicode character, ????, is replaced with exactly four hexadecimal digits .
For example, ’\u03A6’ is the Greek letter phi [Φ].
Textual - String
The textual String type has the following characteristics:
Is not a primitive data type; it is a class
Has its literal enclosed in double quotes ("
")
◦ "The quick brown fox jumps over the lazy dog."
Can be used as follows:
String greeting = "Good Morning !! \n";
String errorMessage = "Record Not Found
!";
Integral – byte, short, int, and long
The integral primitives have the following characteristics:
◦ Integral primates use three forms: Decimal, octal, or hexadecimal
◦ 2 : in Decimal
◦ 02: in Octal
◦ 0XB: in Hexadecimal
◦ Literals have a default type of int.
◦ Literals with the suffix L or l are of type long.
Integral:
Byte: 8 bits
Short: 16 bits
int: 32 bits
long: 64 bits
Floating – double and float
The floating point primitives have the following characteristics:
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)
◦ 3.14: A simple floating-point value (a double)
◦ 6.02E23: A large floating-point value
◦ 2.718F: A simple float size value
Floating – double and float
Literals have a default type of double.
Floating-point data types have the following sizes:
Float Length Name or Type
◦ 32 bits: float
◦ 64 bits: double
Java Reference Types
In Java technology, beyond primitive types all others are reference types.
A reference variable contains a handle to
an object.
Class Type
In addtion to the 8 basic data types, a variable can have a class as its type,
◦ String myName=“abhilasha”;
◦ Color Hair;
Identifiers
Identifiers have the following characteristics:
Are names given to a variable, class, or method
Can start with a Unicode letter, underscore (_), or dollar sign ($)
Are case-sensitive and have no maximum length
Examples:
◦ identifier
◦ userName
◦ user_name
◦ _sys_var1
◦ $change
Variable
A variable is a place where information
can be stored while a program is running.
The value can be changed at any point in the program.
There are three types of variables in Java
◦ Instance Variable
◦ Class Variable
◦ Local Variable
Variable
Instance variable: These are used to define an object’s attribute.
Class Variable: These are used to define the property of class
Local Variables: these are used inside
method definition or even smaller blocks
of statements with in a method.
Global Variable
Unlike other programming languages Java
doesn’t support global variable, a variable
can be used in all parts of progarm.
Comments
The three permissible styles of comment in a Java technology
program are:
First Type:
◦ // comment on one line
Second Type:
◦ /* comment on one
◦ * or more lines
◦ */
Third Type:
◦ /** documentation comment
◦ * can also span one or more lines
◦ */
Operators
These are special symbols used for
mathematical functions, some types of assignment statements, and logical
comparisons.
Arithmetic
Addition: +
Subtraction: -
Multiplication: *
Division: /
Modulus: %
Assignment
+=
-=
*=
/=
=
Incrementing and Decrementing
These are called prefix operators if listed before a variable name, and postfix
operators if listed after a name.
Comparison Operators
Equal: ==
Not Equal: !=
Less than: <
Greater than: >
Less than or equal to: <=
Greater than or equal to: >=
Logical Operators
and: &&
or: ||
Expressions
Expressions perform operations on data and move data around. Some expressions will be evaluated for their results, some
for their side effects, some for both.
An expression can have three kinds of result:
◦ a value, such as the result of: (4 * i)
◦ a variable, such as the result of: i = 4
◦ nothing (in the case of an invocation of a
method declared as void)
Expressions
An expression that results in a variable is called an lvalue in C++ and many other languages.
A variable expression in Java is the same thing, the Java Language Specification just uses the name variable instead of lvalue.
Such an expression can be used on the left hand side of an assignment operator.
Side effects come about when an expression includes an assignment, increment,
decrement, or method invocation.
Statements
A Java method body is a series of zero or more statements.
In the Java programming language,
statements are the fundamental unit of execution.
All statements except blocks are
terminated by a semicolon.
Statements
Statements are executed for their effects;
they do not have values.
There are many different kinds of statements in Java:
◦ local variable declaration statements
◦ the if and if-else statements
◦ the while statement
◦ the do-while statement
◦ the for statement
◦ the switch statement
◦ the break statement
◦ the continue statement
Variable declaration Statement
int i;
String A=“BCA 6 SEM”;
double d=3.0;
boolean b=“true”;
Simple if, else Statements
The if statement syntax:
if ( <boolean_expression> )
<statement_or_block>
Example:
if ( x < 10 )
System.out.println(“x less than 10?");
or (recommended):
if ( x < 10 ) {
System.out.println(“x less than 10?");
}
Complex if, else Statements
The if-else statement syntax:
if ( <boolean_expression> )
<statement_or_block>
else
<statement_or_block>
Example:
if ( x < 10 ) {
System.out.println("Are you finished yet?");
} else {
System.out.println("Keep working...");
}
Complex if, else Statements
The if-else-if statement syntax:
if ( <boolean_expression> )
<statement_or_block>
else if ( <boolean_expression> )
<statement_or_block>
Example:
int count = getCount(); // a method defined in the class
if (count < 0) {
System.out.println("Error: count value is negative.");
} else if (count > getMaxCount()) {
System.out.println("Error: count value is too big.");
} else {
System.out.println("There will be " + count +
" people for lunch today.");
}
Switch Statements
The switch statement syntax:
switch ( <expression> ) {
case <constant1>:
<statement_or_block>*
[break;]
case <constant2>:
<statement_or_block>*
[break;]
default:
<statement_or_block>*
[break;]
}
Looping Statements
The for loop:
for (<init_expr>;<test_expr>;
<alter_expr> )
<statement_or_block>
Example:
for ( int i = 0; i < 10; i++ )
System.out.println(i + " squared is " + (i*i));
or (recommended):
for ( int i = 0; i < 10; i++ ) {
System.out.println(i + " squared is " + (i*i));
}
Looping Statements
The while loop:
while ( <test_expr> )
<statement_or_block>
Example:
int i = 0;
while ( i < 10 ) {
System.out.println(i + " squared is " + (i*i));
i++;
}
Looping Statements
The do/while loop:
do
<statement_or_block>
while ( <test_expr> );
Example:
int i = 0;
do {
System.out.println(i + " squared is " + (i*i));
i++;
} while ( i < 10 );
Special Loop Flow Control
The break [<label>]; command
• The continue [<label>]; command
Special Loop Flow Control
break quits the loop without executing the rest of the statements in the loop.
continue stops the execution of the
current iteration and goes back to the
beginning of the loop to begin the next
iteration.
The break Statement
do {
statement;
if ( condition ) {
break;
}
statement;
} while ( test_expr );
Example
Output
Example
Output
Continue
do {
statement;
if ( condition ) { continue;
}
statement;
} while ( test_expr );
Example
Output
Array
Arrays are used typically to group objects of the same type.
Arrays enable you to refer to the group of objects by a common name.
The declaration of an array creates a
reference that you can use to refer to an array.
The actual memory used by the array elements is allocated dynamically either by a new statement or by an array
initializer.
Declare Array
Declare arrays of primitive or reference types:
◦ char s[];
◦ Point p[];
◦ char[] s;
◦ Point[] p;
Initializing Array
Use the new keyword to create an array object.
For example, a primitive (char) array:
public char[] createArray()
{
char[] p;
char s[]=new char[26];
p = new char[26];
for ( int i=0; i<26; i++ )
{
s[i] =i;
}
return s;
}
Examples:
String
names={“name1”,”name2”,”name3”};
This code is equivalent to:
◦ names=new String[3];
◦ names[0]=“name1”;
◦ names[1]=“name2”;
◦ names[2]=“name3”;
Multidimensional Array
Java language does not provide
multidimensional array in the same way that other language do.
In this you can create arrays of arrays.
Example:
int[][] twoDim = new int[4][];
twoDim[0] = new int[5];
twoDim[1] = new int[50];
int[][] twoDim = new int[][4]; //illegal
Multidimensional Array
The object that is created by the first call to new is an array that contains four
elements.
Each element is a null reference to an
element of type array of int and you must
initialize each element separately so that
each element points to its array.
Multidimensional Array
Because of this separation, you can create non-rectangular arrays of arrays. Example:
twoDim[0] = new int[2];
twoDim[1] = new int[4];
twoDim[2] = new int[6];
twoDim[3] = new int[8];
• Array of four arrays of five integers each:
int[][] twoDim = new int[4][5];
Array bound
All array subscripts begin at 0:
public void printElements(int[] list) {
for (int i = 0; i < list.length; i++) { System.out.println(list[i]);
}
}
Using the Enhanced for Loop
Java 2 Platform, Standard Edition (J2SE) version 5.0
introduced an enhanced for loop for iterating over arrays:
public void printElements(int[] list) {
for ( int element : list ) {
System.out.println(element);
}
}