Você está na página 1de 97

Java An Introduction

Programming language developed by Sun Microsystems in 1991.


Originally called Oak by James Gosling
Originally created for consumer electronics ( TV, VCR, Mobile
Phone, etc.)
Internet and Web was just emerging, so Sun turned it into a
language of Internet Programming.
Pure Object oriented language
Java is a whole platform, with a huge library, containing lots of
reusable code, and an execution environment that provides
services such as

security

portability across operating systems

automatic garbage collection.


1

Need for Java


Many different types of controllers with different set of CPU are
used in electronic devices.
The problem with C and C++ is that designed to be compiled for a
specific target.
An attempt to solve these problems, Gosling and others began
work on a portable, platform-independent language that on a
variety of CPUs under differing environments.
Second force was the introduction of World wide web demand a
language that could useful in creating portable application.

Java White Paper Buzzwords


Simple
Object Oriented - technique for programming that focuses on the
data (= objects) and on the interfaces to that object.
Portable
Architecture Neutral - By generating bytecode instructions, make it
executable on many processors, given the presence of the Java
runtime system.
Interpreted - Java interpreter can execute Java bytecodes directly
on any machine.
Network-Savvy - Java has an extensive library of routines for coping
with TCP/IP protocols like HTTP and FTP.
High Performance JIT Compiler monitor the code and optimize the
code for speed.
Robust - Emphasis on early checking for possible problems, later
dynamic (runtime) checking, and eliminating situations that are
error-prone.
Multithreaded
Secure - intended to be used in networked/distributed
environments.
3

Java Milestones
Year

Milestones

1990

Sun decided to develop a software that could be used for


consumer electronics. A project called Green Project
created and head by James Gosling.

1991

Explored Possibility of using C++, with some updates


announced a new language named Oak

1992

Demonstrate a new language to control a list of home


appliances

1994

Team developed a new Web browser called Hot Java to


locate and run applets.

1995

Oak was renamed to Java. Companies such as Netscape,


Microsoft announced their support for Java

1996

Java became the language for Internet Programming and


General purpose OO language.
4

Java Applications
Java is used to develop two types of application program:

Stand-alone applications

Web applications (applets)

Java Environment
JDK
- Java Development Kit ( Program enable users to create java
applications)

JRE - Java Runtime Environment ( Software to run java programs)


IDE - Eclipse, Jcreator, NetBeans
Setting Path
MyComputer -> Environment Variables ->Advanced -> Path ->
C:\Jdk1.7\bin
6

Sample Helloworld application


/* Simple Helloworld Java application */
class test
{
public static void main(String[] args)
{
System.out.println(Helloworld Java);
}
}
// save it as test.java
Compile : javac test.java
Execute : java test
Helloworld Java

Process of Building and Running Java Applications

Sample Java Execution

Java is Compiled and Interpreted

10

How different from compiled languages?

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

Spot the errors


1. Fix the errors
Class Demo
public static void Main(String[] args)
{
System.out.println("afternoon");
system.out.println("morning");
}
}
If a NoClassDefFoundError occurs when you run a program, what is
the cause of the error?
If a NoSuchMethodError occurs when you run a program, what is
the cause of
the error?

15

Spot the errors


2. Identify and fix the errors in the following code:
public class Welcome
{
public void main(string args[])
{
System.out.println('Welcome to Java!);
}
)

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

Declaration rules for a Java file


A source code file can have only one public class.
If the source file contains a public class, the filename must match
the public class name.
A file can have only one package statement, but multiple imports.
The package statement (if any) must be the first (non-comment)
line in a source file.
The import statements (if any) must come after the package and
before the class declaration.
If there is no package statement, import statements must be the
first (non-comment) statements in the source file.
package and import statements apply to all classes in the file.
A file can have more than one nonpublic class.
Files with no public classes have no naming restrictions.
24

Class Access modifiers


There are three access modifiers: public, protected, and private.
There are four access levels: public, protected, default, and private.
Classes can have only public or default access.
A class with default access can be seen only by classes within the
same package.
A class with public access can be seen by all classes from all
packages.
Class visibility revolves around whether code in one class can
Create an instance of another class
Extend (or subclass), another class
Access methods and variables of another class

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

Legal and Illegal identifiers


Legal Identifiers

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

Java Default Access Modifier


Default Access Modifier
Variable or method without access modifier is available to any
class within the same package. Variables inside interface are
implicitly public and final and methods in interface are public.

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

Convert a data of one type to another before it is used in arithmetic


operations or to store a value of one type into a variable of another type.
Example:
byte b1 = 50;
byte b2 = 60;
byte b3 = b1 + b2;
Error:
cannot implicitly covert type int to type byte
int b3 = b1 + b2; // No Error
In C#, type conversions take place in two ways
1. Implicit conversions
36
36
2. Explicit conversions

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

Java Conversion hierarchy chart


8 bit types

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

Java variable types


Three types of variable used in java:
Local variables ( declared inside function or construct)
Instance variable ( Non static variable declared inside the class and
accessed using object)
Static variable (declared with static modifier and accessed using
class name).
Example:
class VariableDemo
{
int a=10;
static int b=20;
public static void main(String[] ar)
{
String c=Hello;
VariableDemo ob=new VariableDemo();
System.out.println(c + b + ob.a);
}
}
42

Assignment Statements & Expression


variable can get the value using assignment statement or assignment
expression.
Value is assigned using assignment operator
Example :
int a = 10;
An expression represents a computation involving values, variables,
and operators that, taking them together, evaluates to a value.
Example:
int x = 5 * (3 / 2) + 3 * 2;

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

v op= exp is equivalent to v = v op(exp);


Ex:
x + = y + 1; is equivalent to x = x + (y +1)
Advantages:
. What appears on the left hand side need not be repeated and
therefore it becomes easier to write.
. The statement is more concise and easier to read.
48
48 efficient code.
. The use of shorthand operators results in a more

Increment and Decrement Operator


The operators are ++ and - ++ means Increment Operator
- - means Decrement Operator
The operator ++ adds 1 to the operand while subtracts 1. Both are unary
operators and are used in the following form:
++m;
or m++
--m or m
++m; is equivalent to m = m + 1 (or m + = 1;)
--m; is equivalent t o m = m 1 (or m - = 1;)
We use the increment and decrement operators extensively in for and while
loops

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( )

//Reference to the variable age

50

//Reference to the method salary( )

50

Decision Making Statements


Two types of Decision making statements in java:
If else
Switch

51

If Statement ( one way if statement)


Consists of a Boolean condition followed by one or statement.
Syntax:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
Example: Problem statement
Calculate the area of the circle in case of radius is positive integer
class Area
{
public static void main(String[] ar)
{
Scanner s=new Scanner(System.in);
int rad=s.nextInt();
if(rad>0)
{
System.out.println( the area is + (3.14 * rad * rad));
}
}
}
52

Two way if statement


When there are multiple conditions need to be evaluated then we can use ifelse construct. If the condition is true one set of statement executes
otherwise alternate set get executed.
Syntax:
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}

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

Nesting ifelse statement


if (Boolean-expression)
{
True-block statement(S)
if (Boolean-expression)
{
True-block Statement(s)
}
else
{
False-block Statement(s)
}
}
else
{
False-block statement(s)
}

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;

Common errors in Selection statement


1.Forgetting Necessary Braces

2. Wrong Semicolon at the if Line

57

Common errors in Selection statement


3. Redundant Testing of Boolean Values

4. Dangling else Ambiguity

58

Scenario to write if else:


1.
2.

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

THE SWITCH STATEMENT


switch (expression)
{
case value_1:
block_1;
break;
case value_2:
block_2;
break;
case value_3:
block_3;
break;
------------------------------------------default:
default_block
break;
}
Statement_x;

Rules for switch


The switch-expression must yield a value of char, byte, short, or int type
and must always be enclosed in parentheses.
The value1, and valueN must have the same data type as the value of the
switch-expression. Note that value1, and valueN are constant expressions,
meaning that they cannot contain variables, such as 1 + x.
When the value in a case statement matches the value of the switchexpression, the statements starting from this case are executed until either
a break statement or the end of the switch statement is reached.
The keyword break is optional. The break statement immediately ends the
switch statement.
The default case, which is optional, can be used to perform actions when
none of the specified cases matches the switch-expression.
The case statements are checked in sequential order, but the order of the
cases (including the default case) does not matter. However, it is good
programming style to follow the logical sequence of the cases and place
63

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.

In a main method, generate a random integer between 1 and 13 to


represent the possible values in a suit of playing cards.
Use a switch statement that applies cases to your random integer.
If the random number is 1, print out Ace to the console.
If the random number is 11, print out Jack to the console.
If the random number is 12, print out Queen to the console.
If the random number is 13, print out King to the console.
The default case should simply print the random integer to the console.

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

5. Use a switch statement to rewrite the following if statement and


draw the flow chart for the switch statement:
if (a == 1)
x += 5;
else if (a == 2)
x += 10;
else if (a == 3)
x += 16;
else if (a == 4)
x += 34;
6. Write a switch statement that assigns a String variable dayName
with Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday, if day is 0, 1, 2, 3, 4,5, 6, accordingly.
7. Rewrite the following if statement using the conditional operator:
if (count % 10 == 0)
System.out.print(count + "\n");
else
System.out.print(count + " ");
67

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

Enhanced for loop


Syntax:
for(declaration : expression)
{ //Statements }
Declaration:
The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within
the for block and its value would be the same as the current array element.
Expression:
This evaluates to the array you need to loop through. The expression can be
an array variable or method call that returns an array.
Example:
public class Test
{ public static void main(String args[])
{
for( String s : args)
{
System.out.println(s);
}
}
}

72

Additional Features of the for Loop


Case 1:
p = 1;
for (n = 0; n<17;++n)
can be rewritten as
for (p=1,n=0;n<17;++n)
Case 2:
for (n=1,m=50;n<=m; n=n+1,m=m-1)
{
------------------}
Case 3:
sum = 0;
for ( i =1, i<20 && sum <100; i++)
{
--------------------}
Case 4:
for (x = (m+n)/2; x>0;x = x/2)
Case 5:
----------------m = 5;
for (;m != 100;)
{
System.out.println(m);
m = m + 5;
}
---------------

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

Suppose the input is 2 3 4 5 0. What is the output of the following


code?
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number, max;
number = input.nextInt();
max = number;
while (number != 0) {
number = input.nextInt();
if (number > max)
max = number;
}
System.out.println("max is " + max);
System.out.println("number " + number);
}}
78

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

After the break statement is executed in the following loop, which


statement is executed? Show the output.
for (int i = 1; i < 4; i++) {
for (int j = 1; j < 4; j++) {
if (i * j > 2)
break;
System.out.println(i * j);
}
System.out.println(i);
}
After the continue statement is executed in the following loop,
which statement is executed? Show the output.
for (int i = 1; i < 4; i++) {
for (int j = 1; j < 4; j++) {
if (i * j > 2)
continue;
System.out.println(i * j);
}
System.out.println(i);
}

80

Identify and fix the errors in the following code:


public class Test {
public void main(String[] args)
{
for (int i = 0; i < 10; i++);
sum += i;
if (i < j);
System.out.println(i)
else
System.out.println(j);
while (j < 10);
{
j++;
};
{
j++;
} while (j < 10)
}
}

81

What is wrong with the following code?

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

2. Creating memory locations


Syntax:
arrayname = new type [size];
Examples:
number = new int [5];
average = new float [10];
3. Declaration and Creation in one step
Syntax:
type [ ] arrayname = new type [size];
Examples:
int [ ] number = new int [5];
4. Initialization of Arrays
Syntax:
type [ ] arrayname = {list of values};
Example:
int [ ] number = {32,45,34,56,34};
int [ ] number = new int [3] {10,20,30};
85

One Dimensional Array:


A list of like-typed elements.
First create an array variable of the desired type.
new is a special operator that allocates memory.
Assigning values are based on the array variable index ranges from 0 to
n-1;
To display the values in output is also based on index.
class Arrays
{
public static void main(String args[])
{
int month_days[];
month_days = new int[12];
month_days[0] = 31; month_days[6] = 31;
month_days[1] = 28; month_days[7] = 31;
month_days[2] = 31; month_days[8] = 30;
month_days[3] = 30; month_days[9] = 31;
month_days[4] = 31; month_days[10] = 30;
month_days[5] = 30; month_days[11] = 31;
System.out.println(April has + month_days[3] + days);
}
}
O/P: April has 30 days

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

int a[] = {10,20,30,40,50};


for (int b : a)
System.out.println(b);

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;

Two Dimensional Array


Declaration for the Two Dimensional Array
int [ ][ ] myArray;
myArray = new int[3,3];
OR
int [ ][ ] myArray = new int[3,3];
OR
int[ ][ ] table = {{0,0,0},{1,1,1}};

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(" ");
}
}
}

Variable Size Arrays


Variable Size array is called Array of Array or Nested Array or
Jagged Array
Ex:
int [ ] [ ] x = new int [3] [ ]; //Three rows array
x [0] = new int [2]
x [1] = new int [4]
x [2] = new int [3]

//First Rows has two elements


//Second Rows has four elements
//Third Rows has three elements

x[0]

x[0] [1]

x[1]

x[1] [3]

x[2]

x[2] [2]

92

92

public class MyArrayc2


{
public static void main(String args[ ])
{
Scanner s=new Scanner(System.in);
int[][] jag=new int[3][];
jag[0]=new int[4];
jag[1]=new int[3];
jag[2]=new int[5];
System.out.println("Enter the array elements");
for(int i=0;i<jag.length;i++)
{
for(int j=0;j<jag[i].length;j++)
jag[i][j]=s.nextInt();
}
for(int i=0;i<jag.length;i++)
{
for(int j=0;j<jag[i].length;j++)
{
System.out.print(jag[i][j] + "\t ");
}
System.out.println();
}
}
}

93

Variable length arguments


Java allows us to pass a variable number of arguments of the same
type to a method. The parameter in the method is declared as
follows:
typeName... parameterNames
Rules:
A function should contain only one variable length parameter
The variable length parameter must be last in the list
Preceded by any number usual parameters.

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

Path & ClassPath


PATH and CLASSPATH are operating system level environment
variables.
PATH is used to define where the system can find the executables
(.exe) files
Example path= c:\program files\java\jdk.7.0_05\bin

CLASSPATH is used to specify the location of .class files

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

Executing the jar


java jar name.jar

97

Você também pode gostar