Language Fundamentals
Language Fundamentals
Topics
Keywords
Identifiers
Data Types
Literals
Type Conversion
Formatted Output
Operators
Comments
Conditional Constructs
Looping Constructs
Break and Continue
Processing Arrays
Recursion
Copyright 2008 Pratian Technologies
www.pratian.com
Basic Java
Keywords
Keywords are standard words that constitute Java.
Have pre-defined meaning and cannot be redefined.
Are always in lowercase.
There are about 50 keywords in Java.
Basic Java
Identifiers
Identifiers are user-defined names that are given to variables, functions,
arrays, classes, etc.
Naming Rules
Basic Java
Data Types
Data type determines the values that a variable can contain and the
operations that can be performed.
Two types:
Primitive Types
Reference Types
Basic Java
Primitive Types
Basic Java
Primitive
type
Size
boolean
1-bit
char
16-bit
byte
8-bit
short
16-bit
int
32-bit
long
64-bit
float
32-bit
double
64-bit
Literals
Literals are values assigned to identifiers.
Examples of literals:
3L
Long literals take constant L.
100
Integer literal
98.6 or 98.6D
Double literals optionally take double
constant D.
98.6f
Float literals take floating point constant f.
A
Character literals are enclosed in .
This is a test
String literals are enclosed in .
Basic Java
Declaring Variables
General format of variable declaration: type var1, var2, varN;
Few examples:
int num1, num2, sum;
char ch;
double x, y;
You can also initialize the variables at the time of declaration:
int a = 10 , b = 20;
char ch = A;
Sample Code : PrimitiveDemo.java
Basic Java
Knowledge Check
Question
Write a program to swap the values of two numbers. Display the numbers
before swapping and display them again after values are swapped.
Basic Java
Basic Java
Knowledge Check
Question
Write a program to extract the whole and decimal parts of a fractional
number by developing a DecimalSplitter class with methods:
getWhole(double d): Contains logic of extracting the
whole part of d
getFraction(double d): Contains logic of extracting
the fractional part of d
Basic Java
The built-in library class String provides support for representing string
of characters and performing basic operations on them.
Concatenation of strings is done by using the + operator.
Sample Code : StringDemo.java
Basic Java
Formatted Output
Consider the below code and its output:
class Unformatted
{
public static void main(String[] args)
{
double pi = 22.0/7;
System.out.println ("Value of pi is : " + pi);
}
}
What if you
want to display
the value as
3.143?
Basic Java
Formatted Output
Java 1.5 introduces the C-style printf() method for making formatted
output.
// where i is an integer
Basic Java
Formatted Output
class Unformatted
{
public static void main(String[] args)
{
double pi = 22.0/7;
System.out.printf ("Value of pi is : %.3f" + pi);
}
}
Basic Java
Formatted Output
The table below lists some important format specifiers:
Specifier
Description
%n
%d
%f
%e
%%
%c
Basic Java
Formatted Output
For a complete list of all format specifiers, please refer to java docs for
class Formatter.
Sample Code : PrintfDemo.java
Basic Java
Description
Examples
Unary
num++;
Binary
num1 = num2;
Ternary
num1>0 ? num1=100 :
num1=200;
Arithmetic
+ (addition), - (subtraction), *
(multiplication), / (division),
and % (modulo)
Relational and
Conditional
Bitwise and
Logical
Assignment
Basic Java
Conditional: &&, ||
Operator Precedence
The operators in this table are listed in precedence order: the higher an operator appears, the
higher its precedence.
Operators with higher precedence are evaluated before operators with a relatively lower precedence.
Operators on the same line have equal precedence.
Operators
Examples
postfix
unary
creation or cast
New (type)expr
multiplicative
additive
shift
<<
>>
relational
<
equality
==
bitwise AND
&
bitwise exclusive OR
bitwise inclusive OR
logical AND
&&
logical OR
||
conditional
?:
assignment
>
<=
>=
instanceof
!=
Basic Java
Knowledge Check
Question
Evaluate the following expression: a + b c * d / e, wherein a = 2, b = 2,
c = 1, d = 3, and e = 10.
Basic Java
Knowledge Check
Question 2
Write a program to accept a number and display whether a number is odd
or even using the ternary operator.
Question 2
Find the largest of three numbers using ternary operator:
Develop a LargestFinder class with the following method:
public int getLargest (int num1, int num2, int num3)
Also, write the logic of finding the largest of three numbers using
the ternary operator.
Basic Java
Comments
Three kinds of comments:
Double slashes
// Single line comment
C-style
/* C-style comment
Is used to comment out multiple
lines */
Javadoc comments
Used to generate documentation
/** This class displays a text string at
* the console.
*/
Basic Java
Javadoc Comments
Sample Javadoc comments:
/** This program is to demonstrate the use of javadoc tool
@author Sindhu
*/
public class JavaDocDemo
{
/** This variable holds the value of the computed sum
*/
public static int sum = 0;
/** This is the main() method
This is the point at which execution starts */
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
sum = sum + i;
System.out.println(sum);
}
}
Basic Java
The generated
HTMLs follow a
standard format
defined by Sun
Microsystems.
All of Javas
built-in classes
are documented
similarly.
Basic Java
Conditional Statements
Basic Java
if-else Statement
if else statement
if (condition)
{
statements
}
else
{
statements
}
Basic Java
Knowledge Check
Question
Display a students result by:
developing a class TestResult with the following method
public String getResult( int marks, int marks2, int marks3).
Write the logic of returning the result as First Class, Second Class, Pass
Class, or Fails based on the average marks secured.
Basic Java
When a match is found, the statements associated with that value are
executed.
Note:
Variable can
only be of type
int, short, byte,
char or enum.
Syntax:
switch(variable)
{
case value-1 : statements
break;
case value-2 : statements
break;
default : statements
}
Copyright 2008 Pratian Technologies
www.pratian.com
Basic Java
Structured Loops
Basic Java
while Loop
The general form of the while statement is:
while(expression)
{
statement.
}
The loop is entered when the expression is true.
The loop is terminated when the expression is false.
This is a pre-tested loop.
This loop need not be compulsorily executed once.
int i =1;
while(i<=10)
{
System.out.print(i+\t);
i++;
}
Basic Java
Knowledge Check
Question
Display a number in words by:
developing a class NumToWordsConverter with the following method
public String numToWords(int number).
Write the logic of constructing a string that represents the number in words.
Basic Java
do while Loop
The general form of the dowhile statement is:
do
{
statement.
} while(expression);
This loop will be executed at least once.
The loop is re-entered when the expression is true.
The loop is terminated when the expression is false.
This is a post-tested loop.
int i =1;
do
{
System.out.println(i);
i++;
} while(i<=10);
Basic Java
Knowledge Check
Question
Accept users choice and perform mathematical computation.
Basic Java
for Loop
Basic Java
Knowledge Check
Question
Display the following pattern
*
*
*
*
*
*
*
*
* *
Basic Java
break Statement
The break statement, when executed in a switch structure, provides an immediate exit from the
switch structure.
When the break statement executes in a repetition structure, it immediately exits from these
structures.
Basic Java
Syntax:
while(condition)
{
statement;
if(condition)
break;
statement;
}
statement;
Knowledge Check
Question
Write a program to find the sum of all the prime numbers in the range n to m.
Display each prime number and also the final sum.
Basic Java
continue Statement
Basic Java
Knowledge Check
Question
Write a program to display the 1st, 2nd, and 4th multiple of 7, which gives the
remainder 1 when divided by 2, 3, 4, 5, and 6.
Basic Java
Arrays
Whenever an array is used, the subscript or the index is involved. The value to
be stored or retrieved from the array has to be specified by using both the name of
the array and the subscript.
arr =
10
15
20
25
30
35
40
45
50
arr[0] = 5;
System.out.println(arr[0]);
In an array of size n, the first subscript is always 0 and the last subscript is n 1.
Basic Java
Declaring an Array
//
memoryuse
notofallocated
Without
int arrayOfInts[ ];
Note: Without use of new keyword, the array is not allocated memory.
Arrays can contain any legal Java data type including reference types such as
objects or other arrays.
For example, the following declares an array that can contain ten Customer
objects:
Customer[ ] arrayOfCust = new Customer[10];
Basic Java
Initializing an Array
We can store values into an array by using the index to specify position:
int a[
a[0] =
a[1] =
a[2] =
a[3] =
a[4] =
] = new int[5];
10;
20;
30;
40;
50;
Basic Java
Basic Java
Knowledge Check
Question
Write a program to store N elements in an array of integer. Display the
elements. Accept a number to be searched. Display whether the number is
found or not in the array (LINEAR SEARCH).
Basic Java
Multi-Dimensional Arrays
An array where elements can be accessed by using more than one subscript is
known as multi-dimensional array.
[1]
[2]
a[0]
100
200
300
a[1]
400
500
600
700
800
900
a[2]
a[1][2]
Basic Java
Knowledge Check
Question
Check if a given square matrix is identical and / or symmetric by:
Developing a MatrixWizard class with the following methods:
public boolean isIdentity(int[ ][ ] matrix)
Basic Java
Recursion
Method call should terminate at some point, else the recursive method will be
called infinitely.
public void recurse(int n)
{
System.out.println(n);
recurse(n-1);
if(n == 0)
return;
}
Basic Java
Recursion
Consider finding the sum of elements in an array from a start index to the last
element in the array.
Basic Java
Knowledge Check
Question
Find the factorial of a number using recursion by:
Develop a class FactorialGenerator with the following method
public int getFactorial(int num)
Basic Java
Building Applications
All programs written in the Java language are built from
classes.
Every application needs one class with the main method.
The class is the entry point for the program and is passed
to the java interpreter command to run the application.
Signature of main() method
public static void main(String args[]) {}
Basic Java
Basic Java
Question time
Please try to limit the questions to the topics discussed during the session. Thank you.
Basic Java
Keywords
Keywords are standard words that constitute Java.
Have pre-defined meaning and cannot be redefined.
Are always in lowercase.
There are about 50 keywords in Java.
abstract
continue
for
new
switch
assert
default
goto
package
synchronized
boolean
do
if
private
this
break
double
implements
protected
throw
byte
else
import
public
throws
case
enum
instanceOf
return
transient
catch
extends
int
short
try
char
final
interface
static
void
class
finally
long
strictfp
volatile
const
float
native
super
while
Basic Java
Identifiers
Identifiers are user-defined names that are given to variables, functions,
arrays, classes, etc.
Naming Rules
Only numeric and alphabetic
characters are permitted
Special characters permitted are _
(underscore) and $ (dollar)
Should not start with a digit
Case-sensitive; uppercase and
lowercase letters are distinct
Keyword cannot be used as a
variable name
Knowledge Check
Basic Java
int age;
class Employee
{
//
}
void setName(Stringname)
int [ ] scores = new int [10];
Knowledge Check
Question
Identify legal and illegal identifiers from the following (state your
reasons):
first
Employee Salary
Conversion
Hello!
One+two
$test
2nd
_myName
Employee
Basic Java
Data Types
Data type determines the values that a variable can contain and the
operations that can be performed.
Two types:
Primitive Types
Reference Types
Classification
Examples
100
23.667
c
true
Basic Java
Data Types
Data type determines the values that a variable can contain and the
operations that can be performed.
Two types:
Primitive Types
Reference Types
Classification
Examples
classes
interfaces
arrays
Basic Java
customer
intArr[ ]
empArr[ ]
Primitive Types
boolean
Can take values true or false.
Cannot be used interchangeably
with 1 and 0
Basic Java
Primitive
type
Size
boolean
1-bit
char
16-bit
byte
8-bit
short
16-bit
int
32-bit
long
64-bit
float
32-bit
double
64-bit
Primitive Types
char
Unicode character set
Basic Java
Primitive
type
Size
boolean
1-bit
char
16-bit
byte
8-bit
short
16-bit
int
32-bit
long
64-bit
float
32-bit
double
64-bit
Primitive Types
byte
Takes values in the range -128
to 127
Basic Java
Primitive
type
Size
boolean
1-bit
char
16-bit
byte
8-bit
short
16-bit
int
32-bit
long
64-bit
float
32-bit
double
64-bit
Primitive Types
short
Takes values in the range
-32768 to 32767
Basic Java
Primitive
type
Size
boolean
1-bit
char
16-bit
byte
8-bit
short
16-bit
int
32-bit
long
64-bit
float
32-bit
double
64-bit
Primitive Types
int
All integer values are signed int
Takes values in the range
-2,147,483,648 to 2,147,483,647
Basic Java
Primitive
type
Size
boolean
1-bit
char
16-bit
byte
8-bit
short
16-bit
int
32-bit
long
64-bit
float
32-bit
double
64-bit
Primitive Types
long
Takes values in the range
-9223372036854775808 to
9223372036854775807
Basic Java
Primitive
type
Size
boolean
1-bit
char
16-bit
byte
8-bit
short
16-bit
int
32-bit
long
64-bit
float
32-bit
double
64-bit
Primitive Types
float
Takes floating point constant f
Fractional precision of --- digits
after decimal
Takes values in the range
1.40239846e-45 to
3.40282347e+38
Basic Java
Primitive
type
Size
boolean
1-bit
char
16-bit
byte
8-bit
short
16-bit
int
32-bit
long
64-bit
float
32-bit
double
64-bit
Primitive Types
double
Takes floating point constant d
Fractional precision of ---digits
after decimal
Takes values in the range
4.94065645841246544e-324 to
1.79769313486231570e+308
Basic Java
Primitive
type
Size
boolean
1-bit
char
16-bit
byte
8-bit
short
16-bit
int
32-bit
long
64-bit
float
32-bit
double
64-bit
Basic Java
Basic Java
Basic Java