chapter i(introduction to java)

96
Java Chapter I

Upload: chhom-karath

Post on 11-Apr-2017

483 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Chapter i(introduction to java)

Java

Chapter I

Page 2: Chapter i(introduction to java)

History of Java programming• A programming language originally developed by James Gosling at Sun

Microsystems .• Java is a cross-platform language that enables you to write programs for many

different operating systems• syntax : C and C++ but has a simplerobject model and fewer lowlevel facilities .• Oak=>Green=>Java• Java enables users to develop and deploy applications on the Internet for servers,

desktop computers, and small hand-held devices, applications on the server side, Web server to generate dynamic Web pages

Page 3: Chapter i(introduction to java)

SET UP AND USE

Page 4: Chapter i(introduction to java)
Page 5: Chapter i(introduction to java)

• javac SomeApplication.java

Page 6: Chapter i(introduction to java)
Page 7: Chapter i(introduction to java)

JCreator

Java Developing Tools: TextPad, NetBeans, or Eclipse integrated supportdevelopment environment (IDE)

Page 8: Chapter i(introduction to java)

Netbeans

Page 9: Chapter i(introduction to java)

eClipse

Page 10: Chapter i(introduction to java)

1. multiline comment: /* and end with */.2. single-line comment or end-of-line comment : // I hate java3. documentation comment: /** and ends with */

Comment

Page 11: Chapter i(introduction to java)

Test1public class Test1{public static void main(String[] args){/* For */System.out.println("Computer Bactouk Center");}

}Ex2:public class Welcome4{ // main method begins execution of Java application public static void main( String args[] ) { System.out.printf( "%s\n%s\n", "Welcome to", "Java Programming!" );

} // end method main } // end class Welcome4

Page 12: Chapter i(introduction to java)

public(access specifier) class Test1(identifier){

public static void main(String[] args){

System.out.println("Computer Bactouk Center");

}}Þ public means that it is accessible by any other classes Þ static means that it is unique. Þ void is the return value but void means nothing which means there will be no return value .Þ main is the name of the method Þ (String[] args) is used for command line parameters.Þ Curly brackets are used again to group the contents of main together . Þ static allows main( ) to be called without having to instantiate a particular instance of the

classÞ Methods are able to perform tasks and return informationÞ A string is sometimes called a character string, a message or a string literal.Þ System.out is known as the standard output object.Þ “Computer Backtouk Center” is argument.

Class blockMethod block

Page 13: Chapter i(introduction to java)

import java.util.*;public class TestJava { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int a; a=sc.nextInt(); System.out.println(a); }}Note: sc.nextDouble(), sc.next()• import declaration that helps the compiler locate a class that is used in this program.

Reading Input from the Console

Page 14: Chapter i(introduction to java)

Step1: Compiler

• The javac compiler creates a file called Example.class(C:\>javac Example.java)

• Program is run, the following output is displayed()(C:\>java Example)

Page 15: Chapter i(introduction to java)

Variables

• Variables are used to store values to be used later in a program. They are called variables because their values can be changed.

• Variables are for representing data of a certain type. To use a variable, you declare it by telling

• the compiler its name as well as what type of data it can store. The variable declaration tells

• the compiler to allocate appropriate memory space for the variable based on its data type.

• The variable is the basic unit of storage, combination of an identifier, a type, and an optional initializer.

• type identifier [ = value][, identifier [= value] ...] ;– int a, b, c; – int d = 3, e, f = 5; – byte z;– z = 22; – double d = 3.14159; – char x = 'x'; //’x’ is initialize constant

Page 16: Chapter i(introduction to java)

Named Constants• The value of a variable may change during the execution of a program, but a

named constant or simply constant represents permanent data that never changes.– final datatype CONSTANTNAME = VALUE;

public class ComputeArea {public static void main(String[] args)

{final double PI; // Declare a constantPI=100;// Assign a radiusdouble radius = 20;// Compute areadouble area = radius * radius * PI;// Display resultsSystem.out.println("The area for the circle of radius " + radius + " is " + area);}

}

Page 17: Chapter i(introduction to java)

Data type

Page 18: Chapter i(introduction to java)

Data type

• The Primitive TypesPrimitive type Data Type

Integer byte

short

int

long

Characters char

Boolean boolean

Page 19: Chapter i(introduction to java)

Integer

Page 20: Chapter i(introduction to java)

Integerpublic class DayTime { public static void main(String[] args)

{ int point1;

int point2; point1=10; point2=200;

int day=30;

System.out.println("From " + point1 + "km to " + point2 + "km is " + (point2-point1) + "km"); System.out.println("From " + point1 + " to " + point2 + "km, we take " + day + " days"); }}

Page 21: Chapter i(introduction to java)

Char

• Char in java is 0 to 65,536• Char in C is 0 to 127(Not IBM computer)• Char in C is 0 to 255(IBM computer)

public class TestA { public static void main(String[] args) { char ch1='A'; char ch2=97; System.out.println("ch1=" + ch1 + "\nch2=" + ch2); }}

Page 22: Chapter i(introduction to java)

Character Escape- Suppose you want to print a message with quotation marks in the output. Can you write a statement like this?

Page 23: Chapter i(introduction to java)

Floating-point numbers

public class Area { public static void main(String[] args) {

double pi, r, a;r = 21.2;pi = 3.1416;a = pi * r * r; System.out.println("Area of circle is " + a);

}}

Page 24: Chapter i(introduction to java)

Floating-point numberspublic class Calc

{

public static void main(String[] args) {

float v1=6;float v2=4.3f;System.out.println(v1 + "+" + v2 + "=" + (v1+v2));System.out.println(v1 + "-" + v2 + "=" + (v1-v2));System.out.println(v1 + "*" + v2 + "=" + (v1*v2));System.out.println(v1 + "/" + v2 + "=" + (v1/v2));

System.out.println(v1 + "%" + v2 + "=" + (v1%v2));

} }• Floating-point literals are written with a decimal point. By default, a floating-point literal is

treated as a double type value. For example, 5.0 is considered a double value, not a float value. You can make a number a float by appending the letter f or F, and you can make a number a double by appending the letter d or D. For example, you can use 100.2f or 100.2F for a float number, and 100.2d or 100.2D for a double number

Page 25: Chapter i(introduction to java)

boolean• True/falsepublic class Area { public static void main(String[] args) {

boolean sleep=true; sleep=false;System.out.printf("I am so tired so feel seep(" +

sleep + ")"); }}

Page 26: Chapter i(introduction to java)

boolean

public class TestA { public static void main(String[] args) { int a=10,b=100; System.out.println(a>b); }}

Page 27: Chapter i(introduction to java)

Note: Java Strings• To represent a string of characters, use the data type called String.• objects designed to represent a sequence of characters.• In Java, ordinary strings are objects of the class String.• A string literal is a sequence of characters between double quotes.

– String s=new String();• S=“sdfsdf”

– String s=new String(“Texto”);– String s=“texto”;

• String s=“texto”• s=s + “libre”

• If one of the operands is a nonstring (e.g., a number), the nonstring value is converted into a string and concatenated with the other string.

• EX:– String message = "Welcome " + "to " + "Java";– String s = "Chapter" + 2; // s becomes Chapter2– String s1 = "Supplement" + 'B'; // s1 becomes SupplementB

• Method: next() and nextLine()?• == check to see if the two string are exactly the same object• .equals() // . equalsIgnoreCase() method check if the two strings have the same

value;

Page 28: Chapter i(introduction to java)

Default value

Page 29: Chapter i(introduction to java)

Mathematic Arithmetic

Page 30: Chapter i(introduction to java)

Equality and relational operators

• Tertiary OperatorResult=(condition)?TrueReturn:FalseReturn;

Page 31: Chapter i(introduction to java)
Page 32: Chapter i(introduction to java)

Dynamic Initialization

public class TestA { public static void main(String[] args) { double x=100.0; double result=Math.sqrt(x); System.out.println("result sqrt(x)=" + result); }}

Page 33: Chapter i(introduction to java)

The Scope and Lifetime of Variablespublic class TestA { public static void main(String args[]) {

int x; // known to all code within mainx = 10;if(x == 10) { // start new scopein y = 20; // known only to this block// and y both known here.System.out.println("x and y: " + x + " " + y);x = y * 2;}// y = 100; // Error! y not known here// x is still known here.int y=30;System.out.println("x is " + x);System.out.println("y is " + y);}

}

Page 34: Chapter i(introduction to java)

The Scope and Lifetime of Variables

public class TestA { public static void main(String args[]) {

int x;for(x = 0; x < 3; x++) {int y = -1; // y is initialized each time block is enteredSystem.out.println("y is: " + y); // this always prints -1y = 100;System.out.println("y is now: " + y);}}

}

Page 35: Chapter i(introduction to java)

Type Conversion and Casting• narrowing conversion

– if you want to assign an int value to a byte variable? This conversion will not be performed automatically, because a byte is smaller than an int.

– Explicit cast statement: v1=(type)v2;• Automatic Conversions

– int type is always large enough to hold all valid byte values, so no explicit cast statement .

byte a = 40; byte b = 50; byte c = 100;

int d = a * b / c;

Page 36: Chapter i(introduction to java)

narrowing conversion• int a; byte b; b = (byte) a;• Casting Incompatible Typespublic class JavaTest {public static void main(String[] args) { int a; byte b; a=10; b = (byte)a; System.out.println(b); a=10; b=(byte)a; System.out.println(b); }}

Page 37: Chapter i(introduction to java)

narrowing conversionpublic class JavaTest {public static void main(String[] args) { byte b; int i = 257; double d = 323.142; System.out.println("\nConversion of int to byte."); b = (byte) i; System.out.println("i and b " + i + " " + b); System.out.println("\nConversion of double to int."); i = (int) d; System.out.println("d and i " + d + " " + i); System.out.println("\nConversion of double to byte."); b = (byte) d; System.out.println("d and b " + d + " " + b); }}

Page 38: Chapter i(introduction to java)

Automatic Conversionspublic class JavaTest { public static void main(String[] args) { double b; int i = 257; double d = 323.142; System.out.println("\nConversion of int to byte."); b = i; System.out.println("i and b " + i + " " + b); System.out.println("\nConversion of double to int."); i = (int) d; System.out.println("d and i " + d + " " + i); System.out.println("\nConversion of double to byte."); b = d; System.out.println("d and b " + d + " " + b); }}

Page 39: Chapter i(introduction to java)

Formatting Console Output

• to format the output using the printf method.– System.out.printf(format, item1, item2, ..., itemk)

* (int)(Math.random() *10) returns a random single-digit integer (i.e., a number between 0 and 9)

Page 40: Chapter i(introduction to java)

import java.util.Scanner;

public class SubtractionQuiz { public static void main(String[] args) { int number1 = (int)(Math.random() * 10); int number2 = (int)(Math.random() * 10); { int temp = number1; number1 = number2; number2 = temp; } System.out.print ("What is " + number1 + " - " + number2 + "? "); Scanner input = new Scanner(System.in); System.out.println("You are correct!"); else System.out.println("Your answer is wrong\n" + number1 + " - “ + number2 + " should be " + (number1 - number2)); }}

Page 41: Chapter i(introduction to java)

Reference data type

• array type• class type• interface type

Page 42: Chapter i(introduction to java)

Array• An array is a special kind of object that contains values called

elements. The java array enables the user to store the values of the same type in contiguous memory allocations.

• One-Dimensional Arrays– a list of like-typed variables– Step:

• Declaration : type array-var[ ];• Allocate : array-var = new type[size];• Assign value: array_var[n]=value;

– Or step• Declaration and Allocate: type arr-var[]=new type[size];• Assign value: array-var[n]=values;

– Or step• Declaration + Allocate + Assign: type arr-var[]={v1,v2,v3…vn};

• Note: array_var.length

Page 43: Chapter i(introduction to java)

One-Dimensional Arrayspublic class JavaTest { public static void main(String[] args) { String arr_Day[]; arr_Day=new String[7];//or Sring arr_Day=new String[7]; arr_Day[0]="Monday"; arr_Day[1]="Tuesday"; arr_Day[2]="Wednesday"; arr_Day[3]="Thursday"; arr_Day[4]="Friday"; arr_Day[5]="Saturday"; arr_Day[6]="Sunday";

System.out.println("Today is " + arr_Day[5]); }}

Page 44: Chapter i(introduction to java)

One-Dimensional Arrayspublic class TestJava{public static void main(String args[]) { int month_days[]; month_days = new int[12]; month_days[0] = 31; month_days[1] = 28; month_days[2] = 31; month_days[3] = 30; month_days[4] = 31; month_days[5] = 30; month_days[6] = 31; month_days[7] = 31; month_days[8] = 30; month_days[9] = 31; month_days[10] = 30; month_days[11] = 31; System.out.println("April has " + month_days[3] + " days.");}}

Copy Array:int[] sourceArray = {2, 3, 1, 5, 10};int[] targetArray = new int[sourceArray.length];for (int i = 0; i < sourceArray.length; i++) {targetArray[i] = sourceArray[i];}

Page 45: Chapter i(introduction to java)

Passing array to Method

public static void printArray(int[] array){for (int i = 0; i < array.length; i++) {

System.out.print(array[i] + " ");}}

printArray(new int[]{3, 1, 2, 6, 4, 2});//===============public static void main(String[] args) {

int x = 1; // x represents an int valueint[] y = new int[10]; // y represents an array of int values//y[0]=100;m(x, y); // Invoke m with arguments x and ySystem.out.println("x is " + x);System.out.println("y[0] is " + y[0]);}

public static void m(int number, int[] numbers) {number = 1001; // Assign a new value to numbernumbers[0] = 5555; // Assign a new value to numbers[0]}

Page 46: Chapter i(introduction to java)
Page 47: Chapter i(introduction to java)

Return array From Method

public static int[] reverse(int[] list) {int[] result = new int[list.length];for (int i = 0, j = result.length - 1;i < list.length; i++, j--) {

result[j] = list[i];} return result;

}

int[] list1 = {1, 2, 3, 4, 5, 6};int[] list2 = reverse(list1);

Page 48: Chapter i(introduction to java)

Multidimensional Arrays(Two Diemensional)• are actually arrays of arrays• two-dimensional array to store a matrix

– elementType arrayRefVar[][] = new elementType[nR][nC];– elementType[][] arrayRefVar;

• arrayRefVar = new elementType[nR][nC];– elementType arrayRefVar[][];

• arrayRefVar = new elementType[nR][nC];– elementType[][] arrayRefVar = {{….},{….},….,{…}}

– arrayRefVar.length => Length of row– arrayRefVar[index].length => Length of column

EX:• for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) {

int i1 = (int)(Math.random() * matrix.length);int j1 = (int)(Math.random() * matrix[i].length);// Swap matrix[i][j] with matrix[i1][j1]int temp = matrix[i][j];matrix[i][j] = matrix[i1][j1];matrix[i1][j1] = temp;

}}

Page 49: Chapter i(introduction to java)

public class JavaMe { public static void main(String[] args) { int marr[][]=new int[2][4]; marr[0][0]=0; marr[0][1]=1; marr[0][2]=2; marr[0][3]=3; marr[1][0]=0; marr[1][1]=1; marr[1][2]=2; marr[1][3]=3; System.out.println(marr[0][0] + "\t" + marr[0][1] + "\t" + marr[0][2] + "\t" + marr[0][3] +"\n\r" + marr[1][0] +"\t" + marr[1][1] + "\t" + marr[1][2] + "\t" + marr[1]

[3]); }}

Multidimensional Arrays(Two Diemensional)

Page 50: Chapter i(introduction to java)

EX:public class JavaMe { public static void main(String[] args) { int twoD[][] ={{0,1},{2,3},{4,5},{6,7},{8,9}};

System.out.println(twoD[0][0]+ "\t" + twoD[0][1] + "\n\r" + twoD[1][0]+ "\t" + twoD[1][1]+ "\n\r" + twoD[2][0]+ "\t" + twoD[2][1] + "\n\r" + twoD[3][0]+ "\t" + twoD[3][1]+ "\n\r" + twoD[4][0]+ "\t" + twoD[4][1] );

}}EX:public class JavaMe { public static void main(String[] args) { int twoD[][] = new int[4][];

twoD[0] = new int[1];twoD[1] = new int[2];twoD[2] = new int[3];twoD[3] = new int[4];twoD[0][0]=0;twoD[1][0]=1;twoD[1][1]=2;twoD[2][0]=3;twoD[2][1]=4;twoD[2][2]=5;twoD[3][0]=6; twoD[3][1]=7;twoD[3][2]=8;twoD[3][3]=9;System.out.println(twoD[0][0] + "\n\r" + twoD[1][0] + twoD[1][1] + "\n\r" + twoD[2][0] + + twoD[2][0] + + twoD[2][2] + "\n\r” + twoD[3][0] + twoD[3][1] + twoD[3][2] + twoD[3][3]);

}}

Page 51: Chapter i(introduction to java)

Ragged Arrays

Page 52: Chapter i(introduction to java)

Passing Two-Dimensional Arrays to Methods• System.out.println("\nSum of all elements is " + sum(m));• public static int sum(int[][] m) {

int total = 0; for (int row = 0; row < m.length; row++) {for (int column = 0; column < m[row].length; column++) {total += m[row][column];}}return total;}

Page 53: Chapter i(introduction to java)

Control Statements

• To cause the flow of execution to advance and branch based on changes to the state of a program.– selection: allow your program to choose different

paths of execution based upon the outcome of an expression or the state of a variable.

– Iteration: enable program execution to repeat one or more statements

– jump: allow your program to execute in a nonlinear fashion

Page 54: Chapter i(introduction to java)

Conditional Operator

• Ternary operator because it has three terms.– test ? trueresult : falseresult– Int smaller;– smaller = x < y ? x : y;

Page 55: Chapter i(introduction to java)

import java.util.*;public class TestJava{

public static void main(String[] args){Scanner sc=new Scanner(System.in);int money,count;String sheet;System.out.print("Enter money:");money=sc.nextInt();count=money/100;money=money%100;sheet=count>1?"sheets":"sheet";System.out.println("100$:" + count + " " + sheet);count=money/50;money=money%50;sheet=count>1?"sheets":"sheet";System.out.println("100$:" + count + " " + sheet);sheet=count>1?"sheets":"sheet";count=money/20;money=money%20;System.out.println("20$:" + count + " " + sheet);count=money/10;money=money%10;System.out.println("10$:" + count + " " + sheet);count=money/5;money=money%5;System.out.println("5$:" + count + " " + sheet);count=money/2;money=money%2;System.out.println("2$:" + count + " " + sheet);count=money/1;money=money%1;System.out.println("1$:" + count + " " + sheet);}

}

Page 56: Chapter i(introduction to java)

Select statement• If: be used to route program execution through two different

paths. if (condition) statement1;

else statement2;Ex:int a=7, b=8;if(a < b) a = 0;else b = 0;

Page 57: Chapter i(introduction to java)

boolean dataAvailable;if (dataAvailable)

ProcessData();else

waitForMoreData();--------------------------------int bytesAvailable;if (bytesAvailable > 0) {

ProcessData();bytesAvailable -= n;}

elsewaitForMoreData();

Page 58: Chapter i(introduction to java)

Nested ifif(i == 10) {

if(j < 20) a = b;If(k > 100) c = d; // this if iselse a = c; // associated with this else

}else a = d; // this else refers to if(i == 10)

Page 59: Chapter i(introduction to java)

The if-else-if Ladderif(condition)

statement;else if(condition)

statement;else if(condition)

statement;...elsestatement;

Page 60: Chapter i(introduction to java)

class IfElse {public static void main(String args[]) {int month = 4; // AprilString season;if(month == 12 || month == 1 || month == 2)season = "Winter";else if(month == 3 || month == 4 || month == 5)season = "Spring";else if(month == 6 || month == 7 || month == 8)season = "Summer";else if(month == 9 || month == 10 || month == 11)season = "Autumn";elseseason = "Bogus Month";System.out.println("April is in the " + season + ".");}}

Page 61: Chapter i(introduction to java)

Converting Strings to Numbers

Convert Number to String

Page 62: Chapter i(introduction to java)

switch

• Provides easy way to dispatch execution to different parts of code based on the value of an expression.

switch (expression) {case value1:// statement sequencebreak;case value2:// statement sequencebreak;...case valueN:// statement sequencebreak;default:// default statement sequence}

• 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.

• char ch=(char)st.charAt(0);

Page 63: Chapter i(introduction to java)

class SampleSwitch {public static void main(String args[])

{for(int i=0; i<6; i++)

switch(i) {case 0:

System.out.println("i is zero.");Break;case 1:System.out.println("i is one.");break;case 2:System.out.println("i is two.");Break;case 3:System.out.println("i is three.");break;default:System.out.println("i is greater than 3.");

}}}

}}

Page 64: Chapter i(introduction to java)

class MissingBreak {public static void main(String args[]) {for(int i=0; i<12; i++)switch(i) {case 0:case 1:case 2:case 3:case 4:System.out.println("i is less than 5");break;case 5:case 6:case 7:case 8:case 9:System.out.println("i is less than 10");break;default:System.out.println("i is 10 or more");}}}

Page 65: Chapter i(introduction to java)

Nested switch Statements

switch(count) {case 1:

switch(target) { case 0:System.out.println("target is zero");break;case 1: System.out.println("target is one");break;

}break;case 2: // ...

Page 66: Chapter i(introduction to java)

Switch or if?

• The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean expression. That is, the switch looks only for amatch between the value of the expression and one of its case constants.

• No two case constants in the same switch can have identical values. Of course, aswitch statement and an enclosing outer switch can have case constants in common.

• Aswitch statement is usually more efficient than a set of nested ifs.

Page 67: Chapter i(introduction to java)

Iteration Statements• for, while, and do-while called loop• loop that controls how many times an operation or a

sequence of operations is performed in succession.• A loop repeatedly executes the same set ofinstructions until a termination condition is met.

Page 68: Chapter i(introduction to java)

Whilewhile(condition) {// body of loop}Ex:class While {

public static void main(String args[]) {int n = 10;while(n >= 0) {System.out.println("tick " + n);n--;//n=n-1}}

}

Page 69: Chapter i(introduction to java)

int a = 10, b = 20;while(a > b)System.out.println("This will not be displayed");final int NUMBER_OF_QUESTIONS = 5;long startTime = System.currentTimeMillis();int number1 = (int)(Math.random() * 10);

Page 70: Chapter i(introduction to java)

import java.util.*;public class TestJava{

public static void main(String[] args){Scanner sc=new Scanner(System.in);double min,n;System.out.print("Please Enter value:");min=sc.nextDouble();while(sc.hasNextDouble()){n=sc.nextDouble();if(min>n)min=n;System.out.println("Min=" + min);}

}

}

Page 71: Chapter i(introduction to java)

do-whiledo {

body of loop} while (condition);

Ex:class DoWhile {public static void main(String args[]) {int n = 10;do {System.out.println("tick " + n);n=n-2;} while(n > 0);}}

- import java.io.*;- String.substring(BeginIndex,

EndIndex)- String.charAt(pos)

Page 72: Chapter i(introduction to java)

class Menu {public static void main(String args[])throws java.io.IOException {char choice;do {System.out.println("Help on:");System.out.println(" 1. if");System.out.println(" 2. switch");System.out.println(" 3. while");System.out.println(" 4. do-while");System.out.println(" 5. for\n");System.out.println("Choose one:");choice = (char) System.in.read();} while( choice < '1' || choice > '5');System.out.println("\n");switch(choice) {case '1':System.out.println("The if:\n");System.out.println("if(condition) statement;");System.out.println("else statement;");break;

Page 73: Chapter i(introduction to java)

case '2':System.out.println("The switch:\n");System.out.println("switch(expression) {");System.out.println(" case constant:");System.out.println(" statement sequence");System.out.println(" break;");System.out.println(" // ...");System.out.println("}");break;case '3':System.out.println("The while:\n");System.out.println("while(condition) statement;");break;case '4':System.out.println("The do-while:\n");System.out.println("do {");System.out.println(" statement;");System.out.println("} while (condition);");break;case '5':System.out.println("The for:\n");System.out.print("for(init; condition; iteration)");System.out.println(" statement;");break;}}}

Page 74: Chapter i(introduction to java)

forfor(initialization; condition; iteration) {// body}

class ForTick {public static void main(String args[]) {int n;for(n=10; n>0; n--)System.out.println("tick " + n);}}

Page 75: Chapter i(introduction to java)

class ForTick {public static void main(String args[]) {for(int n=10; n>0; n--)System.out.println("tick " + n);}}

Page 76: Chapter i(introduction to java)

class Comma {public static void main(String args[]) {int a, b;for(a=1, b=4; a<b && a<c; a++, b--) {System.out.println("a = " + a);System.out.println("b = " + b);}}}Ex:class ForVar {public static void main(String args[]) {int i;boolean done = false;i = 0;for( ; !done; ) {System.out.println("i is " + i);if(i == 10) done = true;i++;}}}

Page 77: Chapter i(introduction to java)

The For-Each Version of the for Loop

• for(type itr-var : collection) statement-blockclass ForEach {public static void main(String args[]) {int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };int sum = 0;// use for-each style for to display and sum the valuesfor(int x : nums) {System.out.println("Value is: " + x);sum += x;}System.out.println("Summation: " + sum);}}

Page 78: Chapter i(introduction to java)

class ForEach2 {public static void main(String args[]) {int sum = 0;int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };// use for to display and sum the valuesfor(int x : nums) {

System.out.println("Value is: " + x);sum += x;if(x == 5) break; // stop the loop when 5 is obtained

}System.out.println("Summation of first 5 elements: " + sum);}}

Page 79: Chapter i(introduction to java)

class ForEach3 {public static void main(String args[]) {int sum = 0;int nums[][] = new int[3][5];// give nums some valuesfor(int i = 0; i < 3; i++) for(int j=0; j < 5; j++)nums[i][j] = (i+1)*(j+1);// use for-each for to display and sum the valuesfor(int x[] : nums) {for(int y : x) {System.out.println("Value is: " + y);sum += y;}}System.out.println("Summation: " + sum);}}

Page 80: Chapter i(introduction to java)

class Search {public static void main(String args[]) {int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };int val = 5;boolean found = false;// use for-each style for to search nums for valfor(int x : nums) {if(x == val) {found = true;break;}}if(found)System.out.println("Value found!");}}

Page 81: Chapter i(introduction to java)

Using break

class BreakLoop {public static void main(String args[]) {for(int i=0; i<100; i++) {if(i == 10) break; // terminate loop if i is 10System.out.println("i: " + i);}System.out.println("Loop complete.");}}

Page 82: Chapter i(introduction to java)

class BreakLoop3 {public static void main(String args[]) {for(int i=0; i<3; i++) {System.out.print("Pass " + i + ": ");for(int j=0; j<100; j++) {if(j == 10) break; // terminate loop if j is 10System.out.print(j + " ");}System.out.println();}System.out.println("Loops complete.");}}

Page 83: Chapter i(introduction to java)

Using break as a civilized form of goto.

class Break {public static void main(String args[]) {boolean t = true;first: {aaaa: {third: {System.out.println("Before the break.");if(t) break first; // break out of second blockSystem.out.println("This won't execute");}System.out.println("This won't execute");}System.out.println("This is after second block.");}}}

Page 84: Chapter i(introduction to java)

Using continue

class Continue {public static void main(String args[]) {for(int i=0; i<10; i++) {System.out.print(i + " ");if (i%2 == 0) continue;System.out.println("");}}}

Page 85: Chapter i(introduction to java)

return

class Return {public static void main(String args[]) {boolean t = true;System.out.println("Before the return.");if(t) return; // return to callerSystem.out.println("This won't execute.");}}

Page 86: Chapter i(introduction to java)

Insert

Search

Delete

Update

Page 87: Chapter i(introduction to java)

int num;Scanner sc=new Scanner(System.in);System.out.print("Enter number of product:");

num=sc.nextInt();

String product[][]=new String[num][5];for(int i=0;i<num;i++)

for(int j=0;j<4;j++){

if(j==0) System.out.print("Enter ProdID=");if(j==1) System.out.print("Enter ProName=");if(j==2) System.out.print("Enter Qty=");if(j==3) System.out.print("Enter UnitPrice=");product[i][j]=sc.next();

}

System.out.println(" ProductID ProName Qty UnitPrice Total");

for(int i=0;i<num;i++){

float price=Float.parseFloat(product[i][3]);int qty=Integer.parseInt(product[i][2]);float total=price*qty;

System.out.println(product[i][0] + " " + product[i][1] + " " + product[i][2] + " " + product[i][3] + " " + total );

}

Insert

Page 88: Chapter i(introduction to java)

System.out.print("Enter PID to search=");String pID=sc.next();boolean b=false;int help=0;for(int i=0;i<num;i++){

if(product[i][0].equals(pID)){System.out.println("FOund");b=true;help=I;break;

System.out.println(“%.0f”,var);}}

if(b==true){System.out.println(product[help][0] + " " + product[help][1] + " " + product[help][2] + " " + product[help][3] + " " + product[help][4]);}if(b==false){System.out.println("Not Found");}

Search

Page 89: Chapter i(introduction to java)

The Math class contains the methods• Math.pow(3.5, 2.5) returns 22.91765• Math.sqrt(4) returns 2.0• Math.ceil(-2.1) returns -2.0• Math.floor(2.1) returns 2.0• Math.max(2.5, 3) returns 3.0• Math.min(2.5, 3.6) returns 2.5• Math.abs(-2) returns 2

Page 90: Chapter i(introduction to java)

Function/Method in java

• We can do so by defining a method. The method is for creating reusable code.• Methods are referred to as procedures and functions. A value-returning

method is called a function; a void method is called a procedure.• Public class TestJava{

function1bodypublic static void main(String[] args)

{function1caller;function2caller;

} function2body

}• The syntax :

modifier returnValueType methodName(list of parameters) {// Method body;}

Page 91: Chapter i(introduction to java)

A value-returning method• public static float functionName([parameter..])

{statementblock;return value;}

A void method• public static void functionName([parameter..])

{statementblock;}

Page 92: Chapter i(introduction to java)
Page 93: Chapter i(introduction to java)

import java.util.*;public class TestJava{

public static void getResult(byte result){if(result==1){System.out.println("Result point 1:");System.out.println("|-------|");System.out.println("| * |");System.out.println("|-------|");}else if(result==2){System.out.println("Result point 2:");System.out.println("|---------|");System.out.println("| * * |");System.out.println("|---------|");}else if(result==3){System.out.println("Result Point 3:");System.out.println("|--------|");System.out.println("| * * * |");System.out.println("|--------|");}else if(result==4){System.out.println("Result point 4:");System.out.println("|---------|");System.out.println("| * * * |");System.out.println("| * |");System.out.println("|---------|");}else if(result==5){System.out.println("Result point 5::");System.out.println("|---------|");System.out.println("| * * * |");System.out.println("| * * |");System.out.println("|---------|");}else if(result==6){System.out.println("Result point 6:");System.out.println("|---------|");System.out.println("| * * * |");System.out.println("| * * * |");System.out.println("|---------|");}

}public static void getCalc(){byte point, result;Scanner sc=new Scanner(System.in);System.out.print("Enter your point:");point=sc.nextByte();result=(byte)(Math.random()*6+1);switch(point){case 1:System.out.println("You point 1:");System.out.println("|-------|");System.out.println("| * |");System.out.println("|-------|");break;case 2:System.out.println("You point 2:");System.out.println("|---------|");System.out.println("| * * |");System.out.println("|---------|");break;case 3:System.out.println("You point 3:");System.out.println("|--------|");System.out.println("| * * * |");System.out.println("|--------|");break;case 4:System.out.println("You point 4:");System.out.println("|---------|");System.out.println("| * * * |");System.out.println("| * |");System.out.println("|---------|");break;case 5:System.out.println("You point 5:");System.out.println("|---------|");System.out.println("| * * * |");System.out.println("| * * |");System.out.println("|---------|");break;case 6:System.out.println("You point 6:");System.out.println("|---------|");System.out.println("| * * * |");System.out.println("| * * * |");System.out.println("|---------|");break;default:System.out.println("out of point:");System.out.println("|---------|");System.out.println("| |");System.out.println("| Error |");System.out.println("|---------|");}getResult(result);}public static void main(String[] args){getInterface();getCalc();}public static void getInterface(){System.out.println("==========Play Point============");System.out.println("|------------------------------|");System.out.println("| * | * * | * * * |");System.out.println("--------------------------------"); System.out.println("| * * * | * * * | * * * |");System.out.println("| * | * * | * * * |");System.out.println("--------------------------------");}

}

Page 94: Chapter i(introduction to java)

import java.util.*;public class TestJava{

public static void sum(float x, float y){ System.out.println(x+ "" + y + "=" + result);}public static void main(String[] args){

Scanner sc=new Scanner(System.in);float x,y,result;System.out.print("Enter x=");x=sc.nextFloat();System.out.print("Enter y=");y=sc.nextFloat();sum(x,y);}

}

Page 95: Chapter i(introduction to java)

Passing Primitive data type Method Argument by Value:• The arguments must match the parameters in order, number, and compatible type, as

defined in the method signature. • Compatible type means that you can pass an argument to a parameter without explicit

casting, such as passing an int value argument to a double value parameter.• public static void nPrintln(String message, int n) {

for (int i = 0; i < n; i++)System.out.println(message);

}Passing Primitive data type Method Argument by Reference: NONE• To generalize the foregoing discussion, a random character between any two characters

ch1 and ch2 with ch1 < ch2 can be generated as follows:• (char)(ch1 + Math.random() * (ch2 – ch1 + 1))’d’ – ’k’(char)(’d’ + Math.random()*(’k’-’d’+1));

Overloading Methods• another method with the same name but different parameters.

Page 96: Chapter i(introduction to java)