SlideShare ist ein Scribd-Unternehmen logo
1 von 96
Java
Chapter I
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
SET UP AND USE
• javac SomeApplication.java
JCreator
Java Developing Tools: TextPad, NetBeans, or Eclipse integrated support
development environment (IDE)
Netbeans
eClipse
1. multiline comment: /* and end with */.
2. single-line comment or end-of-line comment : // I hate java
3. documentation comment: /** and ends with */
Comment
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( "%sn%sn", "Welcome to", "Java Programming!" );
} // end method main
} // end class Welcome4
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 block
Method
block
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
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)
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
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 constant
PI=100;
// Assign a radius
double radius = 20;
// Compute area
double area = radius * radius * PI;
// Display results
System.out.println("The area for the circle of radius " + radius + " is " + area);
}
}
Data type
Data type
• The Primitive Types
Primitive type Data Type
Integer byte
short
int
long
Characters char
Boolean boolean
Integer
Integer
public 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");
}
}
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);
}
}
Character Escape
- Suppose you want to print a message with quotation marks in the output. Can you
write a statement like this?
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);
}
}
Floating-point numbers
public 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
boolean
• True/false
public class Area
{
public static void main(String[] args)
{
boolean sleep=true; sleep=false;
System.out.printf("I am so tired so feel seep("
+ sleep + ")");
}
}
boolean
public class TestA
{
public static void main(String[] args)
{
int a=10,b=100;
System.out.println(a>b);
}
}
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;
Default value
Mathematic Arithmetic
Equality and relational operators
• Tertiary Operator
Result=(condition)?TrueReturn:FalseReturn;
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);
}
}
The Scope and Lifetime of Variables
public class TestA
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
in 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);
}
}
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 entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
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;
narrowing conversion
• int a; byte b; b = (byte) a;
• Casting Incompatible Types
public 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);
}
}
narrowing conversion
public 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);
}
}
Automatic Conversions
public 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);
}
}
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)
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 wrongn" + number1 + " - “ +
number2 + " should be " + (number1 - number2));
}}
Reference data type
• array type
• class type
• interface type
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
One-Dimensional Arrays
public 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]);
}
}
One-Dimensional Arrays
public 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];
}
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 value
int[] y = new int[10]; // y represents an array of int values
//y[0]=100;
m(x, y); // Invoke m with arguments x and y
System.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 number
numbers[0] = 5555; // Assign a new value to numbers[0]
}
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);
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;
}}
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] +"nr" + marr[1][0] +"t" + marr[1][1] + "t" + marr[1][2] +
"t" + marr[1][3]);
}
}
Multidimensional Arrays(Two Diemensional)
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] + "nr" + twoD[1][0]+ "t" + twoD[1][1]+
"nr" + twoD[2][0]+ "t" + twoD[2][1]
+ "nr" + twoD[3][0]+ "t" + twoD[3][1]+ "nr" + 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] + "nr" + twoD[1][0] + twoD[1][1] + "nr" +
twoD[2][0] + + twoD[2][0] + + twoD[2][2] + "nr” + twoD[3][0] + twoD[3][1] + twoD[3][2]
+ twoD[3][3]);
}
}
Ragged Arrays
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;}
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
Conditional Operator
• Ternary operator because it has three terms.
– test ? trueresult : falseresult
– Int smaller;
– smaller = x < y ? x : y;
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);
}
}
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;
boolean dataAvailable;
if (dataAvailable)
ProcessData();
else
waitForMoreData();
--------------------------------
int bytesAvailable;
if (bytesAvailable > 0) {
ProcessData();
bytesAvailable -= n;}
else
waitForMoreData();
Nested if
if(i == 10)
{
if(j < 20) a = b;
If(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
The if-else-if Ladder
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String 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";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Converting Strings to Numbers
Convert Number to String
switch
• Provides easy way to dispatch execution to different parts of code
based on the value of an expression.
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN:
// statement sequence
break;
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);
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.");
}
}}
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");
}
}
}
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: // ...
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 a
match 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.
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 of
instructions until a termination condition is met.
While
while(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
}
}
}
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);
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);
}
}
}
do-while
do
{
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)
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. forn");
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;
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;
}}}
for
for(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);
}
}
class ForTick
{
public static void main(String args[]) {
for(int n=10; n>0; n--)
System.out.println("tick " + n);
}
}
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++;
}}}
The For-Each Version of the for Loop
• for(type itr-var : collection) statement-block
class 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 values
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}
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 values
for(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);
}
}
class ForEach3 {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][5];
// give nums some values
for(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 values
for(int x[] : nums) {
for(int y : x) {
System.out.println("Value is: " + y);
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}
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 val
for(int x : nums) {
if(x == val) {
found = true;
break;
}
}
if(found)
System.out.println("Value found!");
}
}
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 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
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 10
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Loops complete.");
}
}
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 block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
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("");
}
}
}
return
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
Insert
Search
Delete
Update
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
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
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
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{
function1body
public static void main(String[] args)
{
function1caller;
function2caller;
}
function2body
}
• The syntax :
modifier returnValueType methodName(list of parameters) {
// Method body;}
A value-returning method
• public static float functionName([parameter..])
{
statementblock;
return value;
}
A void method
• public static void functionName([parameter..])
{
statementblock;
}
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;
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);
}
}
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.
Chapter i(introduction to java)

Weitere ähnliche Inhalte

Was ist angesagt?

FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
What's new in Scala 2.13?
What's new in Scala 2.13?What's new in Scala 2.13?
What's new in Scala 2.13?Hermann Hueck
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments rajni kaushal
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Hermann Hueck
 
Java simple programs
Java simple programsJava simple programs
Java simple programsVEERA RAGAVAN
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories Intro C# Book
 
Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 

Was ist angesagt? (20)

Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
What's new in Scala 2.13?
What's new in Scala 2.13?What's new in Scala 2.13?
What's new in Scala 2.13?
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Java and j2ee_lab-manual
Java and j2ee_lab-manualJava and j2ee_lab-manual
Java and j2ee_lab-manual
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
 
10. Recursion
10. Recursion10. Recursion
10. Recursion
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 

Ähnlich wie Chapter i(introduction to java)

Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfnisarmca
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contdraksharao
 
Wap to implement bitwise operators
Wap to implement bitwise operatorsWap to implement bitwise operators
Wap to implement bitwise operatorsHarleen Sodhi
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operatorsraksharao
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfmayorothenguyenhob69
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfShashikantSathe3
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloadingkinan keshkeh
 

Ähnlich wie Chapter i(introduction to java) (20)

Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
C#2
C#2C#2
C#2
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdf
 
Basics of objective c
Basics of objective cBasics of objective c
Basics of objective c
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contd
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Wap to implement bitwise operators
Wap to implement bitwise operatorsWap to implement bitwise operators
Wap to implement bitwise operators
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdf
 
Introduction to Java Programming Part 2
Introduction to Java Programming Part 2Introduction to Java Programming Part 2
Introduction to Java Programming Part 2
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 

Mehr von Chhom Karath

Mehr von Chhom Karath (20)

set1.pdf
set1.pdfset1.pdf
set1.pdf
 
Set1.pptx
Set1.pptxSet1.pptx
Set1.pptx
 
orthodontic patient education.pdf
orthodontic patient education.pdforthodontic patient education.pdf
orthodontic patient education.pdf
 
New ton 3.pdf
New ton 3.pdfNew ton 3.pdf
New ton 3.pdf
 
ច្បាប់ញូតុនទី៣.pptx
ច្បាប់ញូតុនទី៣.pptxច្បាប់ញូតុនទី៣.pptx
ច្បាប់ញូតុនទី៣.pptx
 
Control tipping.pptx
Control tipping.pptxControl tipping.pptx
Control tipping.pptx
 
Bulbous loop.pptx
Bulbous loop.pptxBulbous loop.pptx
Bulbous loop.pptx
 
brush teeth.pptx
brush teeth.pptxbrush teeth.pptx
brush teeth.pptx
 
bracket size.pptx
bracket size.pptxbracket size.pptx
bracket size.pptx
 
arch form KORI copy.pptx
arch form KORI copy.pptxarch form KORI copy.pptx
arch form KORI copy.pptx
 
Bracket size
Bracket sizeBracket size
Bracket size
 
Couple
CoupleCouple
Couple
 
ច្បាប់ញូតុនទី៣
ច្បាប់ញូតុនទី៣ច្បាប់ញូតុនទី៣
ច្បាប់ញូតុនទី៣
 
Game1
Game1Game1
Game1
 
Shoe horn loop
Shoe horn loopShoe horn loop
Shoe horn loop
 
Opus loop
Opus loopOpus loop
Opus loop
 
V bend
V bendV bend
V bend
 
Closing loop
Closing loopClosing loop
Closing loop
 
Maxillary arch form
Maxillary arch formMaxillary arch form
Maxillary arch form
 
Front face analysis
Front face analysisFront face analysis
Front face analysis
 

Kürzlich hochgeladen

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 

Kürzlich hochgeladen (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 

Chapter i(introduction to java)

  • 2. 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
  • 4.
  • 6.
  • 7. JCreator Java Developing Tools: TextPad, NetBeans, or Eclipse integrated support development environment (IDE)
  • 10. 1. multiline comment: /* and end with */. 2. single-line comment or end-of-line comment : // I hate java 3. documentation comment: /** and ends with */ Comment
  • 11. 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( "%sn%sn", "Welcome to", "Java Programming!" ); } // end method main } // end class Welcome4
  • 12. 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 block Method block
  • 13. 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
  • 14. 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)
  • 15. 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
  • 16. 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 constant PI=100; // Assign a radius double radius = 20; // Compute area double area = radius * radius * PI; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } }
  • 18. Data type • The Primitive Types Primitive type Data Type Integer byte short int long Characters char Boolean boolean
  • 20. Integer public 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"); } }
  • 21. 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); } }
  • 22. Character Escape - Suppose you want to print a message with quotation marks in the output. Can you write a statement like this?
  • 23. 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); } }
  • 24. Floating-point numbers public 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
  • 25. boolean • True/false public class Area { public static void main(String[] args) { boolean sleep=true; sleep=false; System.out.printf("I am so tired so feel seep(" + sleep + ")"); } }
  • 26. boolean public class TestA { public static void main(String[] args) { int a=10,b=100; System.out.println(a>b); } }
  • 27. 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;
  • 30. Equality and relational operators • Tertiary Operator Result=(condition)?TrueReturn:FalseReturn;
  • 31.
  • 32. 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); } }
  • 33. The Scope and Lifetime of Variables public class TestA { public static void main(String args[]) { int x; // known to all code within main x = 10; if(x == 10) { // start new scope in 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); } }
  • 34. 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 entered System.out.println("y is: " + y); // this always prints -1 y = 100; System.out.println("y is now: " + y); } } }
  • 35. 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;
  • 36. narrowing conversion • int a; byte b; b = (byte) a; • Casting Incompatible Types public 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); } }
  • 37. narrowing conversion public 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); } }
  • 38. Automatic Conversions public 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); } }
  • 39. 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)
  • 40. 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 wrongn" + number1 + " - “ + number2 + " should be " + (number1 - number2)); }}
  • 41. Reference data type • array type • class type • interface type
  • 42. 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
  • 43. One-Dimensional Arrays public 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]); } }
  • 44. One-Dimensional Arrays public 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]; }
  • 45. 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 value int[] y = new int[10]; // y represents an array of int values //y[0]=100; m(x, y); // Invoke m with arguments x and y System.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 number numbers[0] = 5555; // Assign a new value to numbers[0] }
  • 46.
  • 47. 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);
  • 48. 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; }}
  • 49. 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] +"nr" + marr[1][0] +"t" + marr[1][1] + "t" + marr[1][2] + "t" + marr[1][3]); } } Multidimensional Arrays(Two Diemensional)
  • 50. 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] + "nr" + twoD[1][0]+ "t" + twoD[1][1]+ "nr" + twoD[2][0]+ "t" + twoD[2][1] + "nr" + twoD[3][0]+ "t" + twoD[3][1]+ "nr" + 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] + "nr" + twoD[1][0] + twoD[1][1] + "nr" + twoD[2][0] + + twoD[2][0] + + twoD[2][2] + "nr” + twoD[3][0] + twoD[3][1] + twoD[3][2] + twoD[3][3]); } }
  • 52. 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;}
  • 53. 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
  • 54. Conditional Operator • Ternary operator because it has three terms. – test ? trueresult : falseresult – Int smaller; – smaller = x < y ? x : y;
  • 55. 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); } }
  • 56. 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;
  • 57. boolean dataAvailable; if (dataAvailable) ProcessData(); else waitForMoreData(); -------------------------------- int bytesAvailable; if (bytesAvailable > 0) { ProcessData(); bytesAvailable -= n;} else waitForMoreData();
  • 58. Nested if if(i == 10) { if(j < 20) a = b; If(k > 100) c = d; // this if is else a = c; // associated with this else } else a = d; // this else refers to if(i == 10)
  • 59. The if-else-if Ladder if(condition) statement; else if(condition) statement; else if(condition) statement; . . . else statement;
  • 60. class IfElse { public static void main(String args[]) { int month = 4; // April String 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"; else season = "Bogus Month"; System.out.println("April is in the " + season + "."); } }
  • 61. Converting Strings to Numbers Convert Number to String
  • 62. switch • Provides easy way to dispatch execution to different parts of code based on the value of an expression. switch (expression) { case value1: // statement sequence break; case value2: // statement sequence break; . . . case valueN: // statement sequence break; 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);
  • 63. 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."); } }}
  • 64. 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"); } } }
  • 65. 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: // ...
  • 66. 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 a match 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.
  • 67. 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 of instructions until a termination condition is met.
  • 68. While while(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 } } }
  • 69. 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);
  • 70. 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); } } }
  • 71. do-while do { 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)
  • 72. 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. forn"); 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;
  • 73. 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; }}}
  • 74. for for(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); } }
  • 75. class ForTick { public static void main(String args[]) { for(int n=10; n>0; n--) System.out.println("tick " + n); } }
  • 76. 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++; }}}
  • 77. The For-Each Version of the for Loop • for(type itr-var : collection) statement-block class 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 values for(int x : nums) { System.out.println("Value is: " + x); sum += x; } System.out.println("Summation: " + sum); } }
  • 78. 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 values for(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); } }
  • 79. class ForEach3 { public static void main(String args[]) { int sum = 0; int nums[][] = new int[3][5]; // give nums some values for(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 values for(int x[] : nums) { for(int y : x) { System.out.println("Value is: " + y); sum += y; } } System.out.println("Summation: " + sum); } }
  • 80. 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 val for(int x : nums) { if(x == val) { found = true; break; } } if(found) System.out.println("Value found!"); } }
  • 81. 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 10 System.out.println("i: " + i); } System.out.println("Loop complete."); } }
  • 82. 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 10 System.out.print(j + " "); } System.out.println(); } System.out.println("Loops complete."); } }
  • 83. 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 block System.out.println("This won't execute"); } System.out.println("This won't execute"); } System.out.println("This is after second block."); } } }
  • 84. 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(""); } } }
  • 85. return class Return { public static void main(String args[]) { boolean t = true; System.out.println("Before the return."); if(t) return; // return to caller System.out.println("This won't execute."); } }
  • 87. 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
  • 88. 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
  • 89. 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
  • 90. 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{ function1body public static void main(String[] args) { function1caller; function2caller; } function2body } • The syntax : modifier returnValueType methodName(list of parameters) { // Method body;}
  • 91. A value-returning method • public static float functionName([parameter..]) { statementblock; return value; } A void method • public static void functionName([parameter..]) { statementblock; }
  • 92.
  • 93. 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;
  • 94. 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); } }
  • 95. 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.

Hinweis der Redaktion

  1. EX1: 10.5 + 2 * 3 ______________ 45 - 3.5 v1=10.5; v2=2; V3=3; V4=45; V5=3.5 Result=(v1+(v2*v3))/(v4-v5); EX2:
  2. Reading Input from the Console - Java uses System.out to refer to the standard output device - System.in to the standard input device. EX: import java.util.Scanner; // Scanner is in the java.util package public class ComputeAreaWithConsoleInput { public static void main(String[] args) { // Create a Scanner object Scanner input = new Scanner(System.in);// // Prompt the user to enter a radius System.out.print("Enter a number for radius: "); double radius = ; // Compute area double area = radius * radius * 3.14159; // Display result System.out.println("The area for the circle of radius " + radius + " is " + area); } }
  3. Identifiers Names of things that appear in the program. Such names are called identifiers. All identifiers must obey the following rules: ■ An identifier is a sequence of characters that consists of letters, digits, underscores (_), and dollar signs ($). ■ An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. ■ An identifier cannot be a reserved word. (See Appendix A, “Java Keywords,” for a list of reserved words.) ■ An identifier cannot be true, false, or null. ■ An identifier can be of any length.
  4. There are three benefits of using constants: (1) you don’t have to repeatedly type the same value; (2) if you have to change the constant value (e.g., from 3.14 to 3.14159 for PI), you need to change it only in a single location in the source code; (3) a descriptive name for a constant makes the program easy to read.
  5. public class ShowCurrentTime { public static void main(String[] args) { // Obtain the total milliseconds since midnight, Jan 1, 1970 long totalMilliseconds = System.currentTimeMillis(); // Obtain the total seconds since midnight, Jan 1, 1970 long totalSeconds = totalMilliseconds / 1000; // Compute the current second in the minute in the hour long currentSecond = (int)(totalSeconds % 60); // Obtain the total minutes long totalMinutes = totalSeconds / 60; // Compute the current minute in the hour long currentMinute = totalMinutes % 60; // Obtain the total hours long totalHours = totalMinutes / 60; // Compute the current hour long currentHour = totalHours % 24; // Display results System.out.println("Current time is " + currentHour + ":" + currentMinute + ":" + currentSecond + " GMT"); } }
  6. * int i = 10; Same effect as int newNum = 10 * i++; int newNum = 10 * i;i = i + 1; * int i = 10; Same effect as int newNum = 10 * (++i); i = i + 1;int newNum = 10 * i;
  7. import java.util.Scanner; public class Test4{ public static void main(String[] args) { System.out.print("Enter you play:"); Scanner sc=new Scanner(System.in); int answer=sc.nextInt(); if(answer>=1 && answer<=4) { int number=(int)(Math.random()*3+1); if(answer==number) { System.out.println("Your answer = result"); } else { System.out.printf("The result is %d but you put %d\n",number,answer); System.out.println("Your answer # result"); } } else { System.out.println("Out of range 1-4"); } } }
  8. import java.util.Random; public class j1 { public static void main(String[] args) { int[] myList=new int[10]; Random rand=new Random(); for(int i=0;i<10;i++) { myList[i]= rand.nextInt(10); } for(int i=0;i<10;i++) { System.out.println(myList[i]); } //sum int sum=0; for(int i=0;i<10;i++) { sum=sum+myList[i]; } //max int max=myList[0]; for(int i=0;i<10;i++) { if(myList[i]>max) max=myList[i]; } //min int min=myList[0]; for(int i=0;i<10;i++) { if(myList[i]<min) min=myList[i]; } System.out.println("sum=" + sum); System.out.println("max=" + max); System.out.println("min=" + min); } }
  9. public class Test5 { public static void main(String[] args) { int n=3; java.util.Scanner sc1=new java.util.Scanner(System.in); System.out.print("Enter number of names:"); n=sc1.nextInt(); java.util.Scanner sc=new java.util.Scanner(System.in); String[] name=new String[n]; //insert for(int i=0;i<n;i++) { System.out.print("Enter name:"); name[i]=sc.nextLine(); } //search java.util.Scanner sc2=new java.util.Scanner(System.in); System.out.print("Enter text to search:"); String search=new String(); search=sc2.nextLine(); boolean b=false; int j=0; for(int i=0;i<name.length;i++) { if(search.equalsIgnoreCase(name[i])) { b=true; j++; } } if(b==false) { System.out.println("Not Found!"); } else { System.out.println("Found:" + j + " time"); } //update java.util.Scanner sc3=new java.util.Scanner(System.in); System.out.print("Enter text to to Update:"); String update=new String(); update=sc3.nextLine(); boolean b1=false; int j1=0; for(int i=0;i<name.length;i++) { if(search.equalsIgnoreCase(name[i])) { b1=true; name[i]=update; j1++; } } if(b1==false) { System.out.println("Not Found!"); } else { System.out.println("Update :" + j1 + " time"); } //delete java.util.Scanner sc4=new java.util.Scanner(System.in); System.out.print("Enter text to to DELETE:"); String delete=new String(); delete=sc4.nextLine(); boolean b2=false; int j2=0; for(int i=0;i<name.length;i++) { if(delete.equalsIgnoreCase(name[i])) { b2=true; name[i]=""; j2++; } } if(b2==false) { System.out.println("Not Found!"); } else { System.out.println("Update :" + j2 + " time"); } //output for(int i=0;i<n;i++) { System.out.println("Enter name:" + name[i]); } } }
  10. import java.util.Scanner; public class Test4 { public static void main(String[] args) { String set1 = " 1 3 5 7\n" + " 9 11 13 15\n" + "17 19 21 23\n" + "25 27 29 31"; String set2 = " 2 3 6 7\n" + "10 11 14 15\n" + "18 19 22 23\n" + "26 27 30 31"; String set3 = " 4 5 6 7\n" + "12 13 14 15\n" + "20 21 22 23\n" + "28 29 30 31"; String set4 = " 8 9 10 11\n" + "12 13 14 15\n" + "24 25 26 27\n" + "28 29 30 31"; String set5 = "16 17 18 19\n" + "20 21 22 23\n" + "24 25 26 27\n" + "28 29 30 31"; // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to answer questions System.out.print("Is your birthday in Set1?\n"); System.out.print(set1); System.out.print("\nEnter 0 for No and 1 for Yes: "); int answer = input.nextInt(); int day=0; if (answer == 1) day += 1; System.out.print("\nIs your birthday in Set2?\n" ); System.out.print(set2); System.out.print("\nEnter 0 for No and 1 for Yes: "); answer = input.nextInt(); if (answer == 1) day += 2; System.out.print("Is your birthday in Set3?\n"); System.out.print(set3); System.out.print("\nEnter 0 for No and 1 for Yes: "); answer = input.nextInt(); if (answer == 1) day += 4; System.out.print("\nIs your birthday in Set4?\n"); System.out.print(set4); System.out.print("\nEnter 0 for No and 1 for Yes: "); answer = input.nextInt(); if (answer == 1) day += 8; System.out.print("\nIs your birthday in Set5?\n"); System.out.print(set5); System.out.print("\nEnter 0 for No and 1 for Yes: "); answer = input.nextInt(); if (answer == 1) day += 16; System.out.println("\nYour birthday is " + day + "!"); } }
  11. /** * @(#)Test2.java * * Test2 application * * @author * @version 1.00 2013/9/14 */ import java.util.Date; import java.util.Scanner; public class Test2 { public static void main(String[] args) { System.out.println("Answer the question here:"); String answer=""; char ch='n'; int v1=0,v2=0; Scanner sc=new Scanner(System.in); int i=0; while(ch!='y' && ch!='Y') { Date d=new Date(); System.out.println("You start at :" + d.getHours()+ ":" + d.getMinutes() + ":" + d.getSeconds() ); while(i<5) { v1=(int)(Math.random()*10); v2=(int)(Math.random()*10); if(v1<v2) { int v; v=v1; v1=v2; v2=v; } System.out.print(v1 + "-" + v2 + "="); int ans=sc.nextInt(); if(v1-v2!=ans) { answer+=(i+1) + ", False "; } else { answer+=(i+1) + ",True "; } i++; } System.out.println(answer); Date d1=new Date(); System.out.println("You finished at :" + d1.getHours()+ ":" + d1.getMinutes() + ":" + d1.getSeconds() ); System.out.print("Do you wnat to close(y/n)?"); ch=sc.next().charAt(0); i=0; answer=""; } } }
  12. import java.util.Scanner; import java.io.*; public class Test1 { public static void main(String[] args) { char ch='n'; Scanner sc=new Scanner(System.in); String fullName=new String(""); String firstName=""; String lastName=""; do { int i=0; System.out.printf("Enter full Name:"); fullName=sc.nextLine(); do{ if(fullName.charAt(i)==' ') { firstName=fullName.substring(0,i); lastName=fullName.substring(i+1); break; } i++; }while(i<fullName.length()-1); System.out.printf("First Name is %s\n",firstName); System.out.printf("Last Name is %s\n",lastName); System.out.print("Do you want to close(y/n)?:"); ch=(char)(sc.next().charAt(0)); }while(ch!='y' && ch!='Y'); } }
  13. import java.util.Scanner; class Test11 { public static void main(String args[]){ // Print random characters between 'a' and 'z', 25 chars per line for (int i = 0; i < 'z'-'a'; i++) { char ch =(char)('a' + Math.random() * ('z' - 'a' + 1)); if(i%5==0 && i!=0) { System.out.println(); System.out.print(ch); } else { System.out.print(ch); } } } }