Escolar Documentos
Profissional Documentos
Cultura Documentos
security
Java Milestones
Year
Milestones
1990
1991
1992
1994
1995
1996
Java Applications
Java is used to develop two types of application program:
Stand-alone applications
Java Environment
JDK
- Java Development Kit ( Program enable users to create java
applications)
10
11
Platform Independency
12
Introduction to JVM
JVM is the interpreter used to convert the byte code to machine
code on the fly and execute it.
Byte code is optimized instruction set which independent of
machine.
JVM Architecture
13
JVM
Advantages
Enable java program run in protected environment
Write once, run anywhere (one size fits all)
Browser can cache the downloaded code and reuse it later
14
15
16
Input Processing
import java.util
public class InputDemo
{
Scanner in;
public static void main(String[] args)
{
in=new Scanner(System.in);
System.out.println(Enter a value);
int i=in.nextInt();
System.out.println(User has Entered : + i );
}
}
nextLine, next, nextDouble, hasNext, hasNextInt,
hasNextDouble
17
Reading Input
Using Console class Java.io
import java.util
public class InputDemo
{
public static void main(String[] args)
{
Console con= System.Console();
String name=con.readLine();
String pass=con.readPassword();
System.out.println(User Name : +name + and Password :
+ pass);
}
}
18
19
20
21
22
23
25
Java Tokens
Smallest individual units in a program are known as tokens. The
compiler
recognizes
them
for
building
up
expressions
and
statements.
A Java program is a collection of tokens, comments and white spaces.
Java language includes five types of tokens. They are:
1. Identifiers
2. Comments
3. Keywords
3. Literals
4. Operators
5. Separators
26
Identifiers
Identifiers are programmer designed tokens. They are used for
naming classes, methods, variables, objects, labels, packages and
interfaces in a program. Java identifiers follow the following rules:
Identifiers must start with a letter, a currency character ($), or a
connecting character such as the underscore ( _ ).
Identifiers cannot start with a number!
After the first character, identifiers can contain any combination of
letters, currency characters, connecting characters, or numbers.
In practice, there is no limit to the number of characters an
identifier can contain.
You can't use a Java keyword as an identifier.
Identifiers in Java are case-sensitive; foo and FOO are two different
identifiers.
27
Illegal identifiers
28
Naming Conventions
Names of all public methods and instance variables start with a
leading lowercase letter. Example: average, sum
When more than one word are used in a name, the second and
subsequent words are marked with a leading uppercase letters.
Example: dayTemperature, firstDayofMonth, totalMarks.
All private and local variables use only lowercase letters combined
with underscores Example: length, batch_strength
All classes and interfaces start with a leading uppercase letter(and
each subsequent word with a leading uppercase letter). Example:
Student, HelloJava, Vehicle, MototCycle
Variables that represent constant values use all uppercase letters
and underscores between words. Example: TOTAL, F_MAX,
PRINCIPAL_AMOUNT
29
Comments
Comments help programmers to communicate and understand the
program. They are not programming statements and thus are ignored
by the compiler. In Java, comments are:
Line Comment Statement preceded by two slashes (//)
Block Comment Statement enclosed between /* and */
Java Document Comment Statement enclosed between /**
*/
using Javadoc the document section converted to help files.
30
Java Keywords
31
32
Eight Primitives:
Eight primitives of java are:
Four of them are integer types; two are floating-point number types; one is
the character type char; and one is a Boolean type for truth values.
33
Data Types:
Integer types :
Float types :
34
Character Type
In order to store character constants in memory. Java provides a
character data type called char. The char type assumes a size of 2 bytes but,
basically, it can hold only a single character.
Boolean Type
Boolean type is used when we want to test a particular condition during
the execution of the program. There are only two values that a boolean type
can take: true or false. Remember, both these words have been declared as
keywords. Boolean type is denoted by the keyword boolean and uses only
one bit of storage.
TYPE CONVERSION
Type
Conversion
Implicit
Conversion
Explicit
Conversion
Arithmetic
Operations
Casting
Operations
Implicit Conversions
The conversion can always be performed without any loss of data. For
numeric types, this implies that the destination type can fully represent the
range of the source type. For example, a short can be converted implicitly to
an int, because the short range is a subset of the int range. Therefore,
short b = 75;
int a = b;
Java does the conversion automatically. An implicit conversion is also known
as automatic type conversion.
The process of assigning a smaller type to a larger one is known as
widening or promotion.
Some Examples of implicit conversion are:
byte x1 = 75;
short x2 = x1;
int x3 = x2;
long x4 = x3;
float x5 = x4;
decimal x6 = x4;
37
37
16 bit types
32 bit types
64 bit types
byte
short
char
int
long
float
double
38
38
Explicit Conversions
The process of assigning a larger type to a smaller one is known as norrowing. The
norrowing may result in loss of information.
There are many conversions that cannot be implicitly made between types. If we
attempt such conversions, the compiler will give an error message.
For example, the following conversions cannot be made implicitly:
int to short
int to long
long to int
float to int
decimal to any numeric type
any numeric type to char
However, we can explicitly carry out such conversions using the cast operator. The
process is known as casting and is done as follows:
type variable1 = (type) variable2
39
39
Variables
Variables is an identifier that denotes the storage location used to store a
data value.
Variable declaration denotes three things:
Type of the value the variable going to store.
Based on the place of declaration the initial value assigned.
Name of the variable to refer the value.
Based on the type the size of memory allocation is determined.
Rules for variable declaration:
Variable name must contain numbers, alphabets, and underscore symbol.
They must not begin with a digit.
Uppercase and lowercase are distinct. This means that the variable Total is
not the same as total or TOTAL.
It should not be a keyword.
White space is not allowed.
Variable names can be of any length. A variable must be declared before it
40
Variable
When a variable is assigned a value that is too large (in size) to be
stored, it causes overflow. Java does not report warnings or errors on
overflow.
Example :
int value = 2147483647 + 1; // value will actually be -2147483648
( causes overflow)
41
Note: Java is strongly typed language i.e., variable on the left must be
compatible with the data type of the value on the right.
43
Constants
Named constants or constant represent permanent data that never
changes its value, once gets initialized.
Example:
final double pi= 3.14;
Final indicate that you can assign to the variable once.
44
Operators in Java
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment and Decrement operators
Conditional operators
Bitwise logical operators
Special operators
45
Arithmetic Operators
Relational Operators
Logical
Operators
46
Bitwise Operator
47
Assignment Operator
Assignment operators are used to assign the value of an expression to a
variable. C# has a set of shorthand assignment operators which are used in
the form
v op= exp
vexp
op
is the variable
is the expression
is the binary operator
For Example:
Case 1
m = 5;
y = ++m;
Case 2
m = 5;
y = m--;
The statement
a [ i ++ ] = 10; is equivalent to
49
a [ i ] = 10;49
i = i + 1;
Conditional Operator
It is also known as Ternary operator
Syntax:
exp_1? exp_2: exp_3
Special Operators
Instanceof Operator
The instanceof is an object reference operator and returns true if the
object on the left hand side is an instance of the class given on the right
hand side. This operator allows us to determine whether the object belongs
to a particular class or not.
Example:
person
instanceof student
Dot Operator
The dot operator (.) is used to access the instance variables and methods
of class objects.
Example:
person1.age
person1.salary( )
50
50
51
53
Nested if structure
Nested if structure come into play when there are too many alternate
conditions to be evaluated.
Syntax:
if (boolean-expression)
{
if (boolean-expression)
{
statement(s)-for-the-true-case;
}
}
else
{
statement(s)-for-the-false-case;
}
54
else if Ladder:
if (condition_1)
Statement_1;
else if (condition_2)
Statement_2;
else if (condition_3)
Statement_3;
.
.
.
else if (condition_n)
Statement_n;
else
Default-Statement-x;
57
58
Code to check whether the number entered by user is even or odd number.
Body Mass Index (BMI) is a measure of health on weight. It can be calculated by
taking your weight in kilograms and dividing by the square of your height in
meters. The interpretation of BMI for people 16 years or older is as follows:
3.
Computing taxes : The United States federal personal income tax is calculated
based on filing status and taxable income. There are four filing statuses: single
filers, married filing jointly, married filing separately, and head of household. The
tax rates vary every year. Table 3.2 shows the rates for 2009. If you are, say, single
with a taxable income of $10,000, the first $8,350 is taxed at 10% and the other
$1,650 is taxed at 15%. So, your tax is $1,082.5
59
Scenarios
Lottery : Suppose you want to develop a program to play lottery. The
program randomly generates a lottery of a two-digit number, prompts the
user to enter a two-digit number, and determines whether the user wins
according to the following rule:
1. If the user input matches the lottery in exact order, the award is $10,000.
2. If all the digits in the user input match all the digits in the lottery, the
award is $3,000.
3. If one digit in the user input matches a digit in the lottery, the award is
$1,000.
60
Switch case
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. If statement makes a problem difficult, when too
many choices are there to evaluate in such circumstances switch is the
alternative.
Syntax:
switch(expression)
{
case value :
//Statements
break;//optional
case value :
//Statements
break;//optional
default://Optional
//Statements
}
61
Scenario
Scissorrock-paper game: The program randomly generates a number 0, 1, or
2 representing scissor, rock, and paper. The program prompts the user to
enter a number 0, 1, or 2 and displays a message indicating whether the user
or the computer wins, loses, or draws.
64
Conditional Expression
When we want to assign a value to a variable based on certain condition to
be evaluated, the we can use conditional expression.
Syntax:
X= boolean-expression ? expression1 : expression2;
Example :
To find the biggest of two numbers:
class Big
{
public static void main(String[] ar)
{
int a=Integer.parseInt(ar[0]);
int b=Integer.parseInt(ar[1]);
if(a>b)
System.out.println ( a is big );
else
System.out.println ( b is big );
}
}
Replaced by:
//replaced entire if
statement
int res = ( a > b ) ? a : b ;
65
Exercises
1. Rewrite the following statement using a conditional expression:
if (temperature > 90)
pay = pay * 1.5;
else
pay = pay * 1.1;
2. Write a program that prompts the user to enter the month and
year and displays the number of days in the month. For example, if
the user entered month 2 and year 2000, the program should display
that February 2000 has 29 days. If the user entered month 3 and
year 2005, the program should display that March 2005 has 31 days.
3. Write a program that prompts the user to enter an integer and
checks whether the number is divisible by both 5 and 6, or neither of
them, or just one of them. Here are some sample runs for inputs 10,
30, and 23.
4. What is y after the following switch statement is executed?
x = 3; y = 3;
switch (x + 3) {
case 6: y = 1;
66
Loops
Loop is control structure that executes the sequence statement multiple
times based on condition. Java supports three different set of iteration
statements such as:
While loop
Do While loop
For loop
foreach loop
68
While loop
Based on conditional expression inside the loop, the set of statements get
executed multiple times
Syntax:
initialization;
while(test_condition)
{
Body of the Loop
}
Example:
Counting of numbers 1 to 100
//code
int sum, count=0;
while(count<100)
{
sum+=count;
count++;
}
S.O.P(count);
69
Do-While loop
do-while loop is a variation of the while loop. The do-while loop executes the
loop body first, then checks the loop continuation-condition to determine
whether to continue or terminate the loop.
Syntax :
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
Tip: Use the do-while loop if you have statements inside the loop
that must be executed at least once.
import java.util.Scanner;
public class TestDoWhile {
public static void main(String[] args) {
int data, sum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter an int value (the program exits if the input
is 0): ");
data = input.nextInt();
sum += data;
System.out.println("The sum is " + sum);
70
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.
Syntax:
for (initialization;test_condition;increment)
{
Body of the Loop
}
Example:
public class Test
{
public static void main(String args[])
{
for(int x =10; x <20; x = x+1)
{
System.out.print("value of x : "+ x );
System.out.print("\n");
}
}
}
71
72
Case 6:
for (j = 1000; j>0; j = j 1);
Case 7:
for (j = 1000;j>0; j= j-1);
73
73
Jumps in Loops
break;
continue;
goto;
public class BreakContinueWithLabel
{
public static void main(String args[])
{
int[] numbers= new int[]{100,18,21,30};
OUTER:
for(int i = 0; i<numbers.length; i++)
{
if(i % 2 == 0)
{
System.out.println("Odd number: " + i + ", continue from OUTER
label");
continue OUTER;
}
INNER:
for(int j = 0; j<numbers.length; j++)
{
System.out.println("Even number: " + i + ", break from
INNER label");
break INNER;
}
}
74
}
}
Scenario
1. Write a code to reverse the number using while loop.
2. Greatest Common divisor: Let the two input integers be n1 and
n2. You know that number 1 is a common divisor, but it may not be
the greatest common divisor. So, you can check whether k (fork 2, 3,
4, and so on) is a common divisor for n1 and n2, until k is greater
than n1 or n2. Store the common divisor in a variable named gcd.
Initially, gcd is 1. Whenever a new common divisor is found, it
becomes the new gcd.
3. Predicating the Future Tuition: Suppose that the tuition for a
university is $10,000 this year and tuition increases 7% every year.
In how many years will the tuition be doubled?
75
Review Questions
Analyze the following code. Is count < 100 always true, always false,
or sometimes true or sometimes false at Point A, Point B, and Point
C?
int count = 0;
while (count < 100) {
// Point A
System.out.println("Welcome to Java!\n");
count++;
// Point B
} // Point C
How many times is the following loop body repeated? What is the
printout of the loop?
76
What are the differences between a while loop and a do-while loop?
Convert the following while loop into a do-while loop.
int sum = 0;
int number = input.nextInt();
while (number != 0) {
sum += number;
number = input.nextInt();
}
Do the following two loops result in the same value in sum?
Can you always convert a while loop into a for loop? Convert the
following while loop into a for loop.
int i = 1, sum = 0;
while (sum < 10000) {
sum = sum + i;
i++;
}
77
What is the keyword break for? What is the keyword continue for?
Will the following program terminate? If so, give the output.
The for loop on the left is converted into the while loop on the right.
What is
wrong? Correct it.
79
80
81
Write a program that displays all the numbers from 100 to 1000,
ten per line, that are divisible by 5 and 6.
Use a while loop to find the smallest integer n such that n2 is
greater than 12,000.
Write a program that reads an integer and displays all its smallest
factors in increasing order. For example, if the input integer is 120,
the output should be as follows: 2, 2, 2, 3, 5.
82
Write a program that displays all the numbers from 100 to 1000,
ten per line, that are divisible by 5 and 6.
Use a while loop to find the smallest integer n such that n2 is
greater than 12,000.
83
Array
An array is a data structure which defines an ordered collection of a
fixed number of homogeneous data elements
The size of an array is fixed and cannot increase to accommodate
more elements
In Java, array are objects and can be of primitive data types or
reference types
All elements in the array must be of the same data type
Creating an Array
1. Declaring the array
2. Creating memory locations
3. Putting values into the memory locations.
1. Declaration of Arrays
Syntax:
type [ ] arrayname;
Example:
int [ ] counter;
float [ ] marks;
84
class NumberSorting
{
public static void main(String args[])
{
int number[] = {55,40,80,65,71};
int n = number.length;
System.out.println("Given List");
for(int i = 0;i<n;i++)
{
System.out.println(" " + number[i]);
}
System.out.print("\n");
for(int i = 0;i < n; i++)
{
for(j = 1;j < n; j++)
{
if (number[i] < number [j])
{
int temp = number[i];
number[i] = numbdf[j];
number[j] = temp;
}
}
}
System.out.println("Sorted list:");
for(int i = 0;i < n;i++)
{
System.out.println(" " + number[i]);
}
System.out.println(" ");
}
}
The for-each loop:
A powerful looping construct that allows repeating for each element in an
array without having to confirm with index values.
Syntax:
Ex:
for(variable : collection)
statement
Java.util.Arrays:
Thejava.util.Arraysclass contains a static factory that allows
arrays to be viewed as lists. Following are the important points
about Arrays:
This class contains various methods for manipulating arrays
(such as sorting and searching).
The methods in this class throw a NullPointerException if
the specified array reference is null.
Class declaration
public class Arrays extends Object
Case:
It is possible to assign an array object to another.
Ex:
int [ ] a = {1,2,3};
int [ ] b;
b = a;
class MultiTable
{
final static int ROWS = 5;
final static int COLUMNS = 5;
public static void main(String args[])
{
int product[][] = new int[ROWS][COLUMNS];
int row,column;
System.out.println("Multiplication Table");
System.out.println(" ");
int i,j;
for(i=1;i<ROWS;i++)
{
for(j=1;j<COLUMNS;j++)
{
product[i][j] = i * j;
System.out.print(" " + product[i][j]);
}
System.out.println(" ");
}
}
}
x[0]
x[0] [1]
x[1]
x[1] [3]
x[2]
x[2] [2]
92
92
93
94
class vArg
{
public static void printMax(int... numbers )
{
for (int i = 0; i < numbers.length; i++)
{
System.out.println( numbers[i] );
}
}
public static void main(String[] ar)
{
printMax(1,2,3,4,5);
printMax(1,2,4);
}
}
95
96
JAR
Steps to create jar File:
create a java code save the file
compile the java files to create .class files
create a manifest
manifest is the description contains the main class header
Example: Main-Class: classname
save it in .mft extension
create jar
jar cfm name.jar manifest.mft *.class
97