1. Java Program Constructs or
Language Basics
K.Khaja Mohideen, M.E., M.C.A., M.Phil, MCSA
Assistant Professor
Aalim Muhammed Salegh College of Engineering
2. FEATURES OF JAVA
• The main objective of Java programming
language creation was to make it portable,
simple and secure programming language.
• The features of Java are also known as java
buzzwords.
3. FEATURES OF JAVA: Simple
• A list of most important features of Java :
• Simple
• Java is very easy to learn and its syntax is simple, clean
and easy to understand. According to Sun, Java
language is a simple programming language because:
• Java syntax is based on C++ (so easier for programmers
to learn it after C++).
• Java has removed many confusing and rarely-used
features e.g. explicit pointers, operator overloading etc.
• There is no need to remove unreferenced objects
because there is Automatic Garbage Collection in java.
4. FEATURES OF JAVA: Object-oriented
• Java is object-oriented programming language. Everything in Java is
an object. Object-oriented means we organize our software as a
combination of different types of objects that incorporates both
data and behaviour.
• Object-oriented programming (OOPs) is a methodology that
simplifies software development and maintenance by providing
some rules.
• Basic concepts of OOPs are:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
5. FEATURES OF JAVA: 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
1. software-based and
2. hardware-based.
– Java provides software- based platform.
8. Java development process
• These bytecodes are loaded and executed in the Java virtual
machine (JVM), which is embeddable within other environments,
such as Web browsers and operating systems.
9. The Java 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:
1. Runtime Environment
2. API(Application Programming Interface)
• Java code can be run on multiple platforms e.g. 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).
10. Secured
• Java is best known for its security. With Java,
we can develop virus-free systems. Java is
secured because:
• No explicit pointer
• Java Programs run inside virtual machine
sandbox
12. Secured
• Classloader: Classloader in Java is a part of the Java
Runtime Environment(JRE) which is used to dynamically
load Java classes into the Java Virtual Machine. It adds
security by separating the package for the classes of the
local file system from those that are imported from
network sources.
• Bytecode Verifier: It checks the code fragments for illegal
code that can violate access right to objects.
• Security Manager: It determines what resources a class can
access such as reading and writing to the local disk.
• These security are provided by java language. Some
security can also be provided by application developer
through SSL, JAAS, Cryptography etc.
13. Robust
• Robust simply means strong. Java is robust because:
• It uses strong memory management.
• There are lack of pointers that avoids security
problems.
• There is automatic garbage collection in java which
runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application
anymore.
• There is exception handling and type checking
mechanism in java. All these points makes java robust.
14. Architecture-neutral
• Java is architecture neutral because there is
no implementation dependent features e.g.
size of primitive types is fixed.
• In C programming, int data type occupies 2
bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. But
in java, it occupies 4 bytes of memory for both
32 and 64 bit architectures.
15. Portable
• Java is portable because it facilitates you to
carry the java bytecode to any platform. It
doesn't require any type of implementation.
16. Other Features
• High-performance
• Java is faster than other traditional interpreted
programming languages because Java bytecode is "close"
to native code. It is still a little bit slower than a compiled
language (e.g. C++). Java is an interpreted language that is
why it is slower than compiled languages e.g. C, C++ etc.
• Distributed
• Java is distributed because it facilitates users to create
distributed applications in java. RMI and EJB are used for
creating distributed applications. This feature of Java makes
us able to access files by calling the methods from any
machine on the internet.
17. Other Features
• Multi-threaded
• A thread is like a separate program, executing concurrently. We can
write Java programs that deal with many tasks at once by defining
multiple threads. The main advantage of multi- threading is that it
doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web
applications etc.
• Dynamic
• Java is a dynamic language. It supports dynamic loading of classes.
It means classes are loaded on demand. It also supports functions
from its native languages i.e. C and C++.
• Java supports dynamic compilation and automatic memory
management (garbage collection).
19. 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 runtime environment. It is the
implementation of JVM. It physically exists. It
contains set of libraries + other files that JVM
uses at runtime.
• Implementation of JVMs are also actively
released by other companies besides Sun Micro
Systems.
21. 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:
– Standard Edition Java Platform
– Enterprise Edition Java Platform
– Micro Edition Java Platform
22. JDK
• The JDK contains a private Java Virtual
Machine (JVM) and a few other resources
• an interpreter/loader (Java),
• a compiler (javac), an archiver (jar),
• a documentation generator (Javadoc) etc.
– to complete the development of a Java
Application.
24. JVM (Java Virtual Machine)
• JVM (Java Virtual Machine) is an abstract machine. It is a
specification that provides runtime environment in which java
bytecode can be executed.
• JVMs are available for many hardware and software platforms (i.e.
JVM is platform dependent). The JVM performs following
operation:
– Loads code
– Verifies code
– Executes code
– Provides runtime environment JVM provides definitions for the:
– Memory area
– Class file format
– Register set
– Garbage-collected heap
– Fatal error reporting etc.
26. Java source file (.java)
• Any Java source file (.java) has this physical
structure:
• import statements; class definition
{ instance variable definitions;
method definition (argumentList) { local variable
definitions statements; }
// end of method definition // more methods ...
} // end of class definition
27. A first Simple Java Program
A first Simple Java Program
class Simple
{
public static void main(String args[])
{
System.out.println("Java World");
}
}
To compile:
javac Simple.java
To execute:
java Simple
28. A first Simple Java Program
• class keyword is used to declare a class in java.
• public keyword is an access modifier which represents visibility, it
means it is visible to all. static is a keyword, if we declare any
method as static, it is known as static method. The core advantage
of static method is that there is no need to create object to invoke
the static method. The main method is executed by the JVM, so it
doesn't require to create object to invoke the main method. So it
saves memory.
• void is the return type of the method, it means it doesn't return any
value.
• main represents the starting point of the program. String[] args is
used for command line argument. System.out.println() is used print
statement.
30. Internal Architecture of JVM
• Classloader
• Classloader is a subsystem of JVM that is used to load class files.
• Class(Method) Area
• Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code
for methods.
• Heap
• It is the runtime data area in which objects are allocated.
• Stack
• Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and
return.
• Each thread has a private JVM stack, created at the same time as thread.
• A new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.
• Program Counter Register
• PC (program counter) register contains the address of the Java virtual machine instruction currently being
executed.
• Native Method Stack
• It contains all the native methods used in the application.
• Execution Engine
• Contains a virtual processor, Interpreter to read bytecode stream then execute the instructions and Just-In-
Time(JIT) compiler is used to improve the performance. JIT compiles parts of the byte code that have similar
functionality at the same time, and hence reduces the amount of time needed for compilation. Here, the term
"compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a
specific CPU.
31. Internal Architecture of JVM
• A program is written in JAVA, the javac compiles
it. The result of the JAVA compiler is the .class file
or the bytecode and not the machine native code
(unlike C compiler).
• The bytecode generated is a non-executable code
and needs an interpreter to execute on a
machine. This interpreter is the JVM and thus the
Bytecode is executed by the JVM.
• And finally program runs to give the desired
output.
33. Java Program Constructs or Language
Basics
1. Character Set
2. Identifiers
3. Keywords
4. Data types
5. Constants
6. Variables and it's declaration
7. Operators and Expressions
8. Statements or Commands
34. 1. Character Set:
A allowed set of symbols which will be used to form any program elements
such as identifier, Varaible name, constant, method name, etc.
a) Numerals : 0 to 9 = 10
b) Alphabets: a to z
A to Z = 52
c) special :
i) Operators: + - * / %
ii) brackets: [ ] ( ) { }
iii) Separators: , . ; :
iv) Quotes : ' "
v) Others: / | ~ & ! #
= < > ^ space
Note : The character set varied based verisons of Language.
The above list is the one version's character set.
35. 3. Java Language Keywords
• Java's keywords: Those words are reserved--you cannot use any of
these words as names in your Java programs. true, false, and null
are not keywords but they are reserved words, so you cannot use
them as names in your programs either.
abstract double int strictfp **
boolean else interface super
break extends long switch
byte final native synchronized
case finally new this
catch float package throw
char for private throws
class goto * protected transient
const * if public try
continue implements return void
default import short volatile
do instanceof static while
* indicates a
keyword that is
not currently
used
** indicates a
keyword that
was added for
Java 2
36. 4. Data types
• Primitive Data Types
• A primitive data type specifies the size and
type of variable values, and it has no
additional methods.
• There are eight primitive data types in Java:
37. 4. Data types
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter or ASCII values
38. Numbers
• Primitive number types are divided into two
groups:
• Integer types stores whole numbers, positive or
negative (such as 123 or -456), without decimals.
Valid types are byte, short, int and long. Which
type you should use, depends on the numeric
value.
• Floating point types represents numbers with a
fractional part, containing one or more decimals.
There are two types: float and double.
39. Numbers
• Even though there are many numeric types in
Java, the most used for numbers are int (for
whole numbers) and double (for floating point
numbers).
• However, we will describe them all as you
continue to read.
40. Integer Types
• Byte
• The byte data type can store whole numbers
from -128 to 127. This can be used instead
of int or other integer types to save memory
when you are certain that the value will be
within -128 and 127:
• Example
• byte myNum = 100;
System.out.println(myNum);
41. Short
• The short data type can store whole numbers
from -32768 to 32767:
• Example
• short myNum = 5000;
System.out.println(myNum);
42. Int
• The int data type can store whole numbers
from -2147483648 to 2147483647. In general,
and in our tutorial, the int data type is the
preferred data type when we create variables
with a numeric value.
• Example
• int myNum = 100000;
System.out.println(myNum);
43. Long
• The long data type can store whole numbers
from -9223372036854775808 to
9223372036854775807. This is used when int
is not large enough to store the value. Note
that you should end the value with an "L":
• Example
• long myNum = 15000000000L;
System.out.println(myNum);
44. Floating Point Types
• You should use a floating point type whenever you
need a number with a decimal, such as 9.99 or
3.14515.
• Float
• The float data type can store fractional numbers from
3.4e−038 to 3.4e+038. Note that you should end the
value with an "f":
• Example
• float myNum = 5.75f; System.out.println(myNum);
45. Double
• The double data type can store fractional
numbers from 1.7e−308 to 1.7e+308. Note
that you should end the value with a "d":
• Example
• double myNum = 19.99d;
System.out.println(myNum);
46. Use float or double?
• The precision of a floating point value
indicates how many digits the value can have
after the decimal point. The precision
of float is only six or seven decimal digits,
while double variables have a precision of
about 15 digits. Therefore it is safer to
use double for most calculations.
47. Scientific Numbers
• A floating point number can also be a
scientific number with an "e" to indicate the
power of 10:
• Example
• float f1 = 35e3f; double d1 = 12E4d;
System.out.println(f1); System.out.println(d1);
48. Booleans
• A boolean data type is declared with
the boolean keyword and can only take the
values true or false:
• Example
• boolean isJavaFun = true; boolean isFishTasty
= false; System.out.println(isJavaFun); //
Outputs true System.out.println(isFishTasty);
// Outputs false
49. Characters
• The char data type is used to store
a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
• Example
• char myGrade = 'B';
System.out.println(myGrade);
50. Characters
• Alternatively, you can use ASCII values to
display certain characters:
• char a = 65, b = 66, c = 67;
System.out.println(a); System.out.println(b);
System.out.println(c);
51. Strings
• The String data type is used to store a
sequence of characters (text). String values
must be surrounded by double quotes:
• Example
• String greeting = "Hello World";
System.out.println(greeting);
52. Strings
• The String type is so much used and
integrated in Java, that some call it "the
special ninth type".
• A String in Java is actually a non-
primitive data type, because it refers to an
object.
• The String object has methods that are used
to perform certain operations on strings.
53. Non-Primitive Data Types
• Non-primitive data types are called reference
types because they refer to objects.
• The main difference between primitive and non-
primitive data types are:
• Primitive types are predefined (already defined)
in Java. Non-primitive types are created by the
programmer and is not defined by Java (except
for String).
• Non-primitive types can be used to call methods
to perform certain operations, while primitive
types cannot.
54. Non-Primitive Data Types
• A primitive type has always a value, while non-
primitive types can be null.
• A primitive type starts with a lowercase letter,
while non-primitive types starts with an
uppercase letter.
• The size of a primitive type depends on the data
type, while non-primitive types have all the same
size.
• Examples of non-primitive types
are Strings, Arrays, Classes, Interface, etc.
55. Default Values
• It's not always necessary to assign a value
when a field is declared.
• Fields that are declared but not initialized will
be set to a reasonable default by the compiler.
• Generally speaking, this default will be zero
or null, depending on the data type.
• Relying on such default values, however, is
generally considered bad programming style.
56. Default Values
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char 'u0000'
String (or any object) null
boolean false
57. Exercise:
• Add the correct data type for the following
variables:
• __________myNum = 9;
• ___________myFloatNum = 8.99f;
• ____________myLetter = 'A';
• ____________ myBool = false;
• _____________myText = "Hello World";
58. 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
• Narrowing Casting (manually) - converting a larger type to
a smaller size type
double -> float -> long -> int -> char -> short -> byte
59. Java Type Casting: Widening Casting
• Widening casting is done automatically when
passing a smaller size type to a larger size type:
• Example:
• public class Main { public static void main(String[]
args) { int myInt = 9; double myDouble = myInt; //
Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0 } }
60. Java Type Casting: Narrowing Casting
• Narrowing casting must be done manually by
placing the type in parentheses in front of the
value:
• Example:
• public class Main { public static void main(String[]
args) { double myDouble = 9.78; int myInt = (int)
myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9 } }
61. Variables in Java
• An object stores its state in variables.
• Definition: A variable is an item of data
named by an identifier.
• You must explicitly provide a name and a type
for each variable you want to use in your
program. The variable's name must be a legal
identifier --an unlimited series of Unicode
characters that begins with a letter.
62. Variables in Java
• To give a variable a type and a name, you write a
variable declaration , which generally looks like
this:
• type name In addition to the name and type that
you explicitly give a variable, a variable has scope.
The section of code where the variable's simple
name can be used is the variable's scope. The
variable's scope is determined implicitly by the
location of the variable declaration, that is, where
the declaration appears in relation to other code
elements.
63. Variables in Java
• Variable Names
• A program refers to a variable's value by the variable's
name. For example, when it displays the value of the
largestByte variable, the MaxVariablesDemo program
uses the name largestByte.
• A name, such as largestByte, that's composed of a
single identifier, is called a simple name.
• Simple names are in contrast to qualified names, which
a class uses to refer to a member variable that's in
another object or class.
64. Variables in Java
• In the Java programming language, the following must
hold true for a simple name:
• It must be a legal identifier. An identifier is an unlimited
series of Unicode characters that begins with a letter.
• It must not be a keyword , a boolean literal (true or
false), or the reserved word null.
• It must be unique within its scope. A variable may have
the same name as a variable whose declaration
appears in a different scope. In some situations, a
variable may share the same name as another variable
if it is declared within a nested block of code. (We will
cover this in the next section, Scope.)
65. Variables in Java
• Primitive and object variables
• Variables are represented on the stack as
either:
• A built-in primitive type (byte, short, int, long,
char, float, double, or boolean) that uses value
semantics
• int i = 42; /* i holds value (42) */
66. Variables in Java
• An object type (extended from
java.lang.Object) that uses reference
semantics (like a pointer)
• Button helpButton = new Button("Help");/*
helpButton is an object ref */
68. Scope
• A variable's scope is the region of a program within
which the variable can be referred to by its simple
name.
• Secondarily, scope also determines when the system
creates and destroys memory for the variable.
• Scope is distinct from visibility, which applies only to
member variables and determines whether the
variable can be used from outside of the class within
which it is declared.
• Visibility is set with an access modifier.
69. Lifetime of a variable
• A variable has a storage class, which sets its lifetime.
• Local variables are local to a block of code, that is, allocated at entry
to a block and discarded at exit. (A block of code can be either a
class or a method.)
• Instance variables are local to an object, that is, allocated when an
object is instantiated and discarded when it is garbage-collected.
• Class (static) variables are local to a class, that is, allocated when a
class is loaded and discarded when it is unloaded. Static variables
are not associated with objects and the classes they are defined in
cannot be instantiated.
• An object (referred to by a variable) is marked for garbage
collection when there are no references to it.
70. Lifetime of a variable
• The location of the variable declaration within your program
establishes its scope and places it into one of these four categories:
1. member variable
2. local variable
3. method parameter
4. exception-handler parameter
• A member variable is a member of a class or an object. It is
declared within a class but outside of any method or constructor. A
member variable's scope is the entire declaration of the class.
72. OPERATORS
• Arithmetic Operators
• Relational and Conditional Operators
• Shift and Logical Operators
• Assignment Operators
• Other Operators
73. Arithmetic Operators
• The Java programming language supports
various arithmetic operators for all floating-
point and integer numbers. These operators
are + (addition), - (subtraction), *
(multiplication), / (division), and % (modulo).
74. Arithmetic Operators
Operator Use Description
+ op1 + op2 Adds op1 and op2
- op1 - op2 Subtracts op2 from op1
* op1 * op2 Multiplies op1 by op2
/ op1 / op2 Divides op1 by op2
% op1 % op2
Computes the remainder
of dividing op1 by op2
75. Arithmetic Operators
Data Type of Result Data Type of Operands
long
Neither operand is a float or a
double (integer arithmetic); at
least one operand is a long.
int
Neither operand is a float or a
double (integer arithmetic);
neither operand is a long.
double At least one operand is a double.
float
At least one operand is a float;
neither operand is a double.
76. increment/decrement operators
Operator Use Description
++ op++
Increments op by 1; evaluates to the
value of op before it was incremented
++ ++op
Increments op by 1; evaluates to the
value of op after it was incremented
-- op--
Decrements op by 1; evaluates to the
value of op before it was decremented
-- --op
Decrements op by 1; evaluates to the
value of op after it was decremented
77. Relational and Conditional Operators
• A relational operator compares two values
and determines the relationship between
them. For example, != returns true if the two
operands are unequal. This table summarizes
the relational operators:
78. Relational and Conditional Operators
Operator Use Returns true if
> op1 > op2
op1 is greater than
op2
>= op1 >= op2
op1 is greater than
or equal to op2
< op1 < op2 op1 is less than op2
<= op1 <= op2
op1 is less than or
equal to op2
== op1 == op2
op1 and op2 are
equal
!= op1 != op2
op1 and op2 are not
equal
79. UNARY AND BINARY OPERATORS
Operator Use Returns true if
&& op1 && op2
op1 and op2 are both true,
conditionally evaluates op2
|| op1 || op2
either op1 or op2 is true,
conditionally evaluates op2
! ! op op is false
& op1 & op2
op1 and op2 are both true,
always evaluates op1 and
op2
| op1 | op2
either op1 or op2 is true,
always evaluates op1 and
op2
^ op1 ^ op2
if op1 and op2 are different--
that is if one or the other of
the operands is true but not
both
80. UNARY AND BINARY OPERATORS
Operator Use Operation
>> op1 >> op2
shift bits of op1 right
by distance op2
<< op1 << op2
shift bits of op1 left
by distance op2
>>> op1 >>> op2
shift bits of op1 right
by distance op2
(unsigned)
81. UNARY AND BINARY OPERATORS
Operator Use Operation
& op1 & op2 bitwise and
| op1 | op2 bitwise or
^ op1 ^ op2 bitwise xor
~ ~op2 bitwise complement
83. OTHER OPEATORS
Operator Use Description
?: op1 ? op2 : op3 If op1 is true, returns op2. Otherwise, returns op3.
[] type []
Declares an array of unknown length, which contains type
elements.
[] type[ op1 ]
Creates and array with op1 elements. Must be used with the
new operator.
[] op1[ op2 ]
Accesses the element at op2 index within the array op1.
Indices begin at 0 and extend through the length of the array
minus one.
. op1.op2 Is a reference to the op2 member of op1.
() op1(params)
Declares or calls the method named op1 with the specified
parameters. The list of parameters can be an empty list. The
list is comma-separated.
(type) (type) op1
Casts (converts) op1 to type. An exception will be thrown if
the type of op1 is incompatible with type.
new new op1
Creates a new object or array. op1 is either a call to a
constructor, or an array specification.
instanceof op1 instanceof op2 Returns true if op1 is an instance of op2