Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

JAVA

What is Java?

 Java is a high-level programming language


developed by James Gosling (Sun
Microsystems)

 The Java language is a C-language derivative,


so its syntax rules look much like C's
The Java compiler

 When you program for the Java platform, you


write source code in .java files and then
compile them. The compiler checks your code
against the language's syntax rules, then
writes out bytecodes in .class files. Bytecodes
are standard instructions targeted to run on a
Java virtual machine (JVM).
The JVM

 At run time, the JVM reads and interprets .class files


and executes the program's instructions on the
native hardware platform for which the JVM was
written. The JVM interprets the byte codes just as a
CPU would interpret assembly-language instructions.
The difference is that the JVM is a piece of software
written specifically for a particular platform.
 The JVM is the heart of the Java language's "write-once,
run-anywhere" principle.
 Your code can run on any chipset for which a suitable JVM
implementation is available. JVMs are available for major
platforms like
 Linux and Windows, and subsets of the Java language
have been implemented in JVMs for mobile phones and
hobbyist chips.
Why Java?
 “Most popular” language
 Runs on a “virtual machine” (JVM)
Features of Java
 Object-Oriented – uses classes to organize
code
 Portable and Platform Independent
 Multithreaded
 Garbage Collected
Applets and Applications

Java can be used to create two types of


program:
 Applet
 special applications designed to run within the
context of a web browser
 Application
 Stand-alone program that does not need a
browser to run
 A minimum Java program has the following
format:

public class <classname>{


public static void main(String[]
args){
<program statement>
}
}
Note that:
1. The items in angle brackets are place holders. These must be
replaced with whatever is appropriate for the program (without the
angle brackets).
a. The <classname> is an identifier for the program which should be
the same as the filename.
b. The <program statement> is a series of Java statements.
2. There is a minimum of 2 pairs of curly braces – one after <classname>
surrounding everything else, and another surrounding the <program
statements>.
3. args is a variable which may be renamed according to java rules on
variable names. At this point, just use it as is.
Java Coding Guidelines

Below are guidelines to be followed when coding in java.


 java program files must
o Have same name as public class.
o End with extension .java.

 Use comments for documentation and for readability.


 white spaces are ignored
 indent for readability.
 Java Statements

A statement is one or more lines of code terminated


by a semicolon. Example:

System.out.print(“Hello, World”);

Note: This is the default output statement.


 Java Sample Program

public class Hello{


public static void main(String[] args){
System.out.println(“Hello World!!”);
}
}
Java Comments

- A comment is an optional statements used to describe


what a program or a line of program is doing.

Ex:
//this is a comment - single-line comment
/*this is a comment*/ - multi-line
/** documentation */ - Javadoc
Java Variable
- A variable is a container that holds values that are used in a Java program. Every
variable must be declared to use a data type.
- a variable could be declared to use one of the eight primitive data types.
- every variable must be given an initial value before it can be used.
Ex:
<data type> <variable name> [=initial value];
int a= 9;
int x;

Note: values enclosed in <> are required values, while those values in [] are optional.
Rules

- variables can use alphabetic characters of either case


(a-z and A-Z), numbers (0-9), underscores(_), and
dollar signs($).
- Variables cannot start with a number.
- Keywords cannot be used as variable
names(keywords is sometimes called reserved
words).
Guidelines

- Name your variable close to its functionality.

- For multi-word variable, either use underscores to separate


the words, or capitalize the start to each word.

- Avoid starting the variables using the underscore.

- Variables are distinct or unique.


Examples

VALID INVALID
$sum 1sum
exer2exer Exer-1
StudInfo Exer,exer
Stud_Info Sum/
void
static
Data Type

 A data type is a classification identifying one of various


types of data, such as floating-point, integer, or
Boolean, stating the possible values for that type, the
operations that can be done on that type, and the way
the values of that type are stored.
 A variable's data type determines the values it may
contain, plus the operations that may be performed on
it.
Primitive Data Types

 Building blocks and are an essential part of a program.


Without these data types it would be impossible for a
programmer to store pertinent data necessary in the
completion of the program.
Java Primitive Data Type

Type Min value Max Value


byte -128 127
short -32768 32767
int -2,147,483,648 2,147,483,647
(Integer)
long -9,223,372,036,854,775,808 9,223,372,036,854,775,807
float -3.4*1018 3.4*1018
double -1.7*10308 1.7*10308
boolean true & false
char Single character enclose with single quote ‘’
String Set of characters enclosed with double quote “”
 boolean(true or false)-a boolean is not a number and cannot be
converted to a number or any other type.
 char(characters)-represents text characters or unicode characters.
 byte-represents short numbers from -128 – 127 only.
 short-ranges from -32768 - 32767
 int(integer)-numbers without fractional parts. Negative values are
allowed ranges from -2,147,483,648 - 2,147,483,647.
 long-enhance version of integer. Ranges from
9,223,372,036,854,775,808 - 9,223,372,036,854,775,807.

 float(floating point or fraction)- numbers with


decimal points.
 double-mostly used than the float data type,
since these numbers have twice the precision of
the float type.
Declaring and initializing variable

<data type> <variable name> [=initial value];

Example:

int myAge = 18;

Note: values enclosed in <> are required values, while those values in [] are
optional.
Guidelines in declaring and initializing
variables:

Below are the guidelines in initializing variables:


1. Always initialize your variables as you declare them.

2. Use descriptive names for your variables.

3. Declare one variable per line of code;


Displaying variable data

In java, we can output the value of a variable using the


following commands:

System.out.print();
System.out.println();
Example:
public class VarOutput{
public static void main(String args[]){
int value = 10;
char x;
x = „A‟

System.out.println(value);
System.out.println(“The value of x = ” + x);

}
}
Simple Assignment Operator

= Simple assignment operator


Arithmetic operators

 are used in mathematical expressions in the same way


that they are used in algebra.
 The following table lists the arithmetic operators:

Example:
Assume integer variable A holds 10 and variable B
holds 20 then:
Operato Description Example
r
+ Addition - Adds values on either side of the operator A + B will give
30

- Subtraction - Subtracts right hand operand from left hand A - B will give -
operand 10

* Multiplication - Multiplies values on either side of the A * B will give


operator 200

/ Division - Divides left hand operand by right hand operand B / A will give 2

% Modulus - Divides left hand operand by right hand operand B % A will give
and returns remainder 0

++ Increment - Increase the value of operand by 1 B++ gives 21

-- Decrement - Decrease the value of operand by 1 B-- gives 19


Normal Form Compressed Form
sum = sum + 1 sum+=2
p=p–1 p -=1
r = r /4 r /=4
j=j*b j*=b
n = n% 2 n%=2
n=n+1 n++
a=a–1 a--
Relational Operator
Operator Description Example
== Checks if the value of two operands are equal or (A == B) is
not, if yes then condition becomes true. not true.
!= Checks if the value of two operands are equal or (A != B) is
not, if values are not equal then condition becomes true.
true.
> Checks if the value of left operand is greater than (A > B) is not
the value of right operand, if yes then condition true.
becomes true.
< Checks if the value of left operand is less than the (A < B) is
value of right operand, if yes then condition true.
becomes true.
>= Checks if the value of left operand is greater than or (A >= B) is
equal to the value of right operand, if yes then not true.
condition becomes true.
<= Checks if the value of left operand is less than or (A <= B) is
equal to the value of right operand, if yes then true.
Logical Operators

Results to boolean value:


&& Conditional-AND true or false
|| Conditional-OR
! Not equal (<>)
Logical Operator
Operator Description Example
&& Called Logical AND operator. If both the (A && B) is
operands are non zero then then false.
condition becomes true.
|| Called Logical OR Operator. If any of the (A || B) is
two operands are non zero then then true.
condition becomes true.
! Called Logical NOT Operator. Use to !(A && B)
reverses the logical state of its operand. is true.
If a condition is true then Logical NOT
operator will make false.
Conditional Statements

 If statement
 If else
 If else if
 switch
If statement
 If the boolean expression evaluates to true then the block
of code inside the if statement will be executed. If not the
first set of code after the end of the if statement(after the
closing curly brace) will be executed.
Syntax:

if(Boolean_hexpression) {
//Statements will execute if the Boolean expression is true
}
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("This is if statement");
}
}
}
If. . .else
 An if statement can be followed by an
optional else statement, which executes when the Boolean
expression is false.
Syntax:

if(Boolean_expression){
//Executes when the Boolean expression is true
}
else{
//Executes when the Boolean expression is false
}
public class Test {
public static void main(String args[]){

int x = 30;
if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}
If else if

 an if statement can be followed by an


optional else if...else statement, which is very
useful to test various conditions using single
if...else if statement.
 When using if , else if , else statements there
are few points to keep in mind.
 An if can have zero or one else's and it must come
after any else if's.
 An if can have zero to many else if's and they must
Syntax:

if(Boolean_expression1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is
true.
}
public class Test {
public static void main(String args[]){
int x = 30;

if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}
Nested if...else Statement
 It is always legal to nest if-else statements, which means you
can use one if or else if statement inside another if or else if
statement.
Syntax:

if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
public class Test {
public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
}
The switch Statement:

 A switch statement allows a variable to be tested for


equality against a list of values. Each value is called a
case, and the variable being switched on is checked
for each case.
 Syntax:
Syntax:
switch(expression){
case value:
break; //optional
case value :
break; //optional
default:
}
The following rules apply to a switch
statement:
 The variable used in a switch statement can only be
a byte, short, int, or char.
 You can have any number of case statements
within a switch. Each case is followed by the value
to be compared to and a colon.
 The value for a case must be the same data type as
the variable in the switch, and it must be a constant
or a literal.
 When the variable being switched on is equal to a
case, the statements following that case will
execute until a break statement is reached.
 When a break statement is reached, the switch
terminates, and the flow of control jumps to the
next line following the switch statement.
 Not every case needs to contain a break. If no
break appears, the flow of control will fall
through to subsequent cases until a break is
reached.
 A switch statement can have an optional default
case, which must appear at the end of the
switch. The default case can be used for
performing a task when none of the cases is
true. No break is needed in the default case.
Looping Structure
LOOPING STRUCTURE

 Use to execute statements repeatedly


 Java has very flexible three looping mechanisms. You
can use one of the following three loops:
 while Loop
 do...while Loop
 for Loop
The for Loop:
 A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific number of
times.
 A for loop is useful when you know how many times a task is to be
repeated.
 Syntax:

for(initialization;Boolean_expression;update
){ //Statements
}
Example

 Write a program that displays “Hello Java” ten times.


 Write a program that displays number from 1 – 100
 Write a program that displays number from 100 – 1
 Write a program that displays the sum of all even
number from 1 – 100.
 Write a program that displays the factorial of a
number.
 Write a program that will get the product of two
numbers without using * operator.
 Write a program that will reverse a number.
 Write a program that converts decimal to binary.
Activity

 Write a program that converts decimal to binary,


octal and hexadecimal values.
 Write a program that identify if a number is
palindrome or not.
The while Loop:
 A while loop is a control structure that allows you to repeat
a task a certain number of times.
 Syntax:

while(Boolean_expression) {
//Statements
}
The do while loop:

Syntax:
do{
//statements

}while(expression);
Array
Array

 ordered collection of data items of the


same type referred to collectively by a
single name
 Index – each variable or cell in an array
 Elements – individual data / items in an array
indicated by the array name followed by its
dimensions appears in a square brackets
 Dimensions – an integer from 1 – n called
dimensioned variables
Array

 An array is a container object that holds a fixed


number of values of a single type.
 The length of an array is established when the array is
created.
 After creation, its length is fixed.
Declaring array
 Syntax:
<data type> [] arrayname;
<data type> [] arrayname = new <datatype>[length];
 Example:
 int[] anArray;
 double[] anArrayOfDoubles;
 boolean[] anArrayOfBooleans;
 char[] anArrayOfChars;
 String[] anArrayOfStrings;
Creating, Initializing, and Accessing
an Array
 anArray = new int[10];
Assigning value to array
 anArray[0] = 100; // initialize first element
 anArray[1] = 200; // initialize second element
 anArray[2] = 300; // and so forth
How to access array element:
 Each array element is accessed by its
numerical index:

 System.out.println("Element 1 at index 0: " + anArray[0]);

 System.out.println("Element 2 at index 1: " + anArray[1]);

 System.out.println("Element 3 at index 2: " + anArray[2]);


Alternatively, you can use the
shortcut syntax to create and
initialize an array:
int[] anArray = { 100, 200, 300, 400,
500, 600, 700, 800, 900, 1000 };
Dimensionality of an Array

 One-dimensional Array
 Array1[j]
 Two-dimensional Array
 Array1[ i ][ j ]
 One-Dimensional Array
 It is the basic array
 A vertical table with number of columns and
 only one row
 Index and Length
 Indices – used to access each location of arrays from 0
ranging up to the instantiated array
 Two-Dimensional Array
 It is an array of an array
 Also called as tables or matrices
 Row – first dimension
 Column – second dimension
Two-Dimensional Array

 It is an array of an array
 Also called as tables or matrices
 Row – first dimension
 Column – second dimension
Syntax:
type arrayName [ row ][ column ];
 A two-dimensional array can be think as a table, which will
have x number of rows and y number of columns. A 2-
dimensional array a, which contains three rows and four
columns can be shown as below:
a[3][4]
Initializing Two-Dimensional
Arrays:

Example:
int a[3][4] = { {0, 1, 2, 3} ,
{4, 5, 6, 7},
{8, 9, 10, 11}};

You might also like