Hello java

58
HELLO JAVA! Raaid Alubady L E V E L Celebrate IEEE Day with Coding Java

Transcript of Hello java

Page 1: Hello java

HELLO JAVA!

Raaid Alubady LEVEL

Celebrate IEEE Day with Coding Java

Page 2: Hello java

OUTLINE Beginning in Java

oBeginning in JavaoComponents of Java Programming oJava Variable and Data Type

Components and Control Toolso2.1. Data input o2.2. Data output o2.3. Condition statements o2.4. Loop statements

Array and Methods

Hello Java

Hello Java

Hello Java

Page 3: Hello java

Beginning in Java

• Sun Microsystem (by James Gosling) began developing Java behind closed door in 1991. It wasn't reveal to the public until 1995.

• The original name of Java was intended to be "OAK", Other names floating around were "Silk" and "DNA".

• Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look and feel" of the C++ language, but it is simpler to use than C++ and enforces an object-oriented. Java can be used to create complete applications that may run on a single computer or be distributed among servers and clients in a network. It can also be used to build a small application module or applet for use as part of a Web page.

Hello Java !

Page 4: Hello java

Beginning in Java Characteristics of Java• Easy to learn• Platform independent (not access directly system resources)• Object-orientated programming language• Interpreted and compiled language (source code… byte-code) • Automatic memory management

Hello Java !

Java IDE Tools• Inprise JBuilder• Microsoft Visual J++• Symantec Café • Forte by Sun MicroSystems• IBM Visual Age for Java• Eclipse • NetBeans 6.0 (free, open-source IDE, runs

on Windows, Linux, Solaris, and the MacOS)• JCreator LE 4.0 (free) by Xinox Software

Page 5: Hello java

Beginning in Java

Why Program in Java?

Hello Java !

Page 6: Hello java

Beginning in Java

Why Program in Java?

Hello Java !

Page 7: Hello java

Beginning in Java

Ready to learn JAVA.

If so, switch on your laptop.

Next , open Eclipse...

Hello Java !

JAVA

Page 8: Hello java

Beginning in Java

Three editions of Java API Java SE: A Standard Edition targeted at developing console,

desktop client, and server applications. Java EE: An Enterprise Edition targeted at developing large-

scale industry enterprise applications. Java ME: A Micro Edition targeted at developing mobile,

hand-held device applications.

Hello Java !

Java API, JDK and IDE

Contains predefined classes and interfaces for developing Java programs.

API(Application Programming Interface)

Page 9: Hello java

Beginning in Java Hello Java !

Java API, JDK and IDE

JDK(Java Development Kit)A set of programs for developing and testing Java program, each of which is invoked from a command line.

(Integrated Development Environment)Software that provides integrated development environment (editing, compiling, building, debugging and online help) for rapidly developing Java program

IDE

Page 10: Hello java

Beginning in Java Create the first project1

2

3

4

Hello Java !

Page 11: Hello java

Beginning in Java Create the first project

5

6

Hello Java !

Page 12: Hello java

Beginning in Java Create the first project

7

8

9

Hello Java !

Page 13: Hello java

Beginning in Java Create the first project

10

Hello Java !

Page 14: Hello java

Beginning in Java

First Example: Hello class with Java

Hello Java !

Page 15: Hello java

Beginning in Java

Components of Java Programming Comments.(to illustrate the programs steps and comments) Project. (it using to include one or more package in one project) Package. (it using to include one or more class in one package) Class.(at least one in one project) Main Method.(at least one in one project and its use for project

execution) Other methods. (the main class might be included many

methods) Blocks.(codes must be organize) Reserved Keyword. (such as private, String, extends, class,

and so on) Instructions.(language format) Access specify. (like public, private, protected)

Hello Java !

Page 16: Hello java

Beginning in Java Java Variable and Data Type

• Local variable. declared within a method in a class.

• Instance variable. declared within a class but outside any method.

• Static variable. declared within a class as static.

Declaring variable: <<datatype>> <<variableName>>;Example: int count; double radius; double total;Or double radius, total;

Hello Java !

Page 17: Hello java

Beginning in Java

Note2: In Java, the equal sign (=) is used as the assignment operator.

Note1: The Java syntax is similar to C++. Java is case sensitive, e.g. the variables myValue and myvalue will be treated as different variables.

Note3: The name of a variable can be made of one letter (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z,A ,B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, or Z) .

Note4: The name of a variable can start with a letter, an underscore "_", or the dollar sign $.

Note5: After the first character, the name of the variable can include letters, digits (0, 1, 2, 3, 4, 5, 6, 7, 8, or 9), or underscores in any combination

Hello Java !

Page 18: Hello java

Beginning in Java Note6: The name of a variable cannot be one of the words that the Java languages has reserved for its own use.

abstract assert boolean break byte

case catch char class const

continue default do double else

enum extends final finally float

for goto if implements Import

intanceof int interface long native

new package private protected public

return short static strictfp super

switch synchronized this throw throws

transient try void volatile while

Hello Java !

Page 19: Hello java

Beginning in Java

Visibility Default(friendly) public protected Private

From the same class Yes Yes Yes Yes

From any class in the same package

Yes Yes No No

From any class outside the package

No Yes No No

From a subclass in the same package

Yes Yes Yes No

From a subclass outside the same package

No Yes Yes No

Instance variables access specification

Note7: this table is same when instance methods and inner class access specify.

Hello Java !

Hel

lo

Java

!

Page 20: Hello java

Components and Control ToolsJava Data Input and out put

Input by Console Scanner

import java.util.Scanner;

public class Read_Scanner {

public static void main( String [ ] args )

{

Scanner in = new Scanner( System.in );

System.out.print( in.nextLine() );

} // end of main method

} // end of main class

Output by System.out• In Java we can use Scanner class.• First step, declare a Scanner object.

Scanner scan = new Scanner (System.in)

• System.in is a object represents the standard input stream, which by default is the keyboard.

• The object scan reads the input in many ways: scan.nextInt()scan.nextDouble()

scan.nextFloat()scan.next()scan.nextLine()

• java.util.Scanner class library should be imported in order to used this object.

import java.util.Scanner

public static void main( String [ ] args )

{int x=9, y=8, z; z=x+y; System.out.print (x); System.out.print (y); System.out.print (z); System.out.println (); System.out.println(x); System.out.println(y); System.out.println(z); System.out.println("the result= "+ z); // end of main method } // end of main class

System.out.print( ); without new line

Or System.out.println( ); with new line

98179817The result = 17

Hel

lo

Java

!

Output

Page 21: Hello java

Java Data Input and out putimport java.util.Scanner;

public class test {/* * This program is basic calculator */

public static void main(String[] args) {// double elmFirst, elmSecond, elmSum; System.out.print("Enter the First element "); Scanner in = new Scanner( System.in ); elmFirst = in.nextDouble(); System.out.print("Enter the Second element "); elmSecond = in.nextDouble(); elmSum = elmFirst + elmSecond; System.out.println("The answer is " + elmSum);

}}

Enter the First element 3.6Enter the Second element 9.23The answer is 12.83

Components and Control Tools

Hel

lo

Java

!

Output

Page 22: Hello java

Components and Control Tools

Condition Stracture The if selection structure (single or multiple selection structure) Conditional operator ?: (ternary conditional) The switch selection structure (multiple-selection structure)

if, if/else, instance if StatementSyntax: if (condition(s)) { statement or block of statements } Or : if (condition(s)) { statement or block of statements } else { statement or block of statements }

The condition is a Boolean comparison that can use one of the binary operators:

== , != , > , < , >= , <=In addition to the Boolean operators && (AND), || (OR), and ! (NOT). Of course combinations can occur using brackets ( )

Hel

lo

Java

!

Page 23: Hello java

Components and Control Tools

if, if/else, nistens if StatementExample: if (x !== y); System.out.println (“Not Equal”);

Example:if (studentGrade >= 60) System.out.println (“Passed”);else System.out.println (“Failed”);

Example:if (totalSum<50) { // no discount System.out.println (“No discount”); System.out.println (“Payment is ”+totalSum); }else { //10% discount totalSum=totalSum-(totalSum*0.1); System.out.println (“Payment with discount is ”+totalSum); }

Example:if (x>5) { if (y>5) System.out.println(“x and y are > 5”);}else System.out.println(“x is <=5”);}

Hel

lo

Java

!

Page 24: Hello java

Components and Control Tools

Conditional operator

Syntax: (condition (s) ? statement1 : statement2

Example: System.out.println (studentGrade >= 60 ? “Passed” : “Failed”);

import java.util.Scanner;public class test {public static void main(String[ ] args) {// test Conditional operator

int mark; System.out.print("Enter the mark "); Scanner in = new Scanner( System.in ); mark = in.nextInt();mark= mark >= 50 ? mark+10 : mark-5;

System.out.println("The answer is " + mark);}}

Example

Hel

lo

Java

!

Page 25: Hello java

Components and Control Tools

Switch selection structure Syntax: switch (variable) { case value_1 : { statement or block of statements; break; } case value_2 : { statement or block of statements; break; } case value_3 : { statement or block of statements; break; } ............................................................................................ ............................................................................................ case value_n : { statement or block of statements; break; } default : { statement or block of statements; } }

Example System.out.print("Enter the mark "); Scanner in = new Scanner( System.in ); i = in.nextInt();

switch (i)}

case 1: { System.out.println (“Read”); break;}

case 2: {System.out.println (“Blue”); break; }

case 3: { System.out.println(“Black”); }

System.out.println(“Unknown”); default:

//end of switch{

Hel

lo

Java

!

Page 26: Hello java

Components and Control Tools

Exercise4: Write a program called PrintNumberInWord which prints "ONE", "TWO",... , "NINE", "OTHER" if the int variable "number" is 1, 2,... , 9, or other, respectively. Use (a) a "nested-if" statement; (b) a "switch-case" statement.

Exercise1: Write a program in Java to find out if a number is prime in Java? (input 7: output true , input 9 : output false). A number is called prime if it is divisible by either itself or 1. 

Exercise2: Write Java program to check if a number is palindrome in Java? ( 121 is palindrome, 321 is not). A number is called a palindrome if number is equal to reverse of number e.g. 121 is palindrome because reverse of 121 is 121 itself.

Exercise3: Write a program in Java to check if a number is even or odd in Java? (input 2 output true, input 3 : output false). A number is called even if it is completely divisible by two and odd if it’s not completely divisible by two. For example number 4 is even number because when you do 4/2 , remainder is 0 which means 4 is completely divisible by 2. On the other hand 5 is odd number because 5/2 will result in remainder as 1H

ello

Ja

va !

Page 27: Hello java

Components and Control Tools

Loop Statements for loops while loops do/while loops

for loopsSyntax: for ( initializations; condition(s); increment/ decrement ) { statement or block of statements ; } 

Example for (int i=0 ; i<10 ; i++)}

System.out.println ("the value I is" + i); }

Hel

lo

Java

!

Page 28: Hello java

Components and Control Tools

public class test {/*

* This program is test for statement */

public static void main(String[] args) {for(int i=1;i<=10;i++){ if ((i%2)==0) System.out.println("The i " + i + " is event"); else System.out.println("The i " + i + " is odd");} //end for

} //end main} //end class

public static void main(String[] args) {int i; for(i=1;i<=10;i++); System.out.println("the result : "+ i); } //end main

What does the result

Hel

lo

Java

!

Page 29: Hello java

Components and Control Tools

public class test {/* * This program is test for statement */public static void main(String[] args) { int i; int ii; int sum; for(i=0;i<10;i++){ sum=0; for(ii=i;ii<10;ii++){ sum+=ii; } // end second for System.out.println("the result : "+ sum); } // end first for } //end main} //end class

Exercise5: Write a program called SumAndAverage to produce the sum of 1, 2, 3, ..., to 100. Also compute and display the average. The output shall look like:

The sum is 5050 The average is 50.5

The sum is 5050 The average is 50.5 H

ello

Ja

va !

Page 30: Hello java

Components and Control Tools

while structureSyntax: while ( condition(s) )}

statement or block of statements; {

Example: int numberCount = 1; // this step very important while (numberCount<=10) { System.out.println (numberCount); numberCount++; }

import java.util.Scanner;public class test {//This program is test whilepublic static void main(String[] args) { int numberCount; System.out.print("Enter the mark "); Scanner in = new Scanner( System.in ); numberCount = in.nextInt(); while (numberCount==10) { System.out.println (numberCount); numberCount++; }// end while System.out.println("The answer is " + numberCount);} }

Hel

lo

Java

!

Page 31: Hello java

Components and Control Tools

do / while structure

Syntax: do {

statement or block of statements ;

} while ( condition(s) ) ;Example: int numberCount = 10; do { System.out.println (numberCount); numberCount--; } while (numberCount>0);

Exercise6: Modify the program to use a "while-do" loop instead of "for" loop.Exercise7: Modify the program to use a "do-while" loop.Exercise8: What is the difference between "for" and "while-do" loops? What is the difference between "while-do" and "do-while" loops?

Exercise9: Write a program called Fibonacci to display the first 20 Fibonacci numbers F(n), where F(n)=F(n–1)+F(n–2) and F(1)=F(2)=1. Also compute their average. The output shall look like: The first 20 Fibonacci numbers are: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 The average is 338

Hel

lo

Java

!

Page 32: Hello java

Array and Methods

Java Arrays Array is the most important thing in any programming language. By definition, array is the static memory allocation. It allocates the memory for the same data type in sequence.

Example int [ ] num; num = new int [6]; or we can also :  int [ ]num = new int [6]; or like this int num[ ] = new int [6];

Declaration of an array  Syntax: DataType[ ] ArrayRefVar=new DataType[array size];

Should be the same

There are two type of arrayi. Single-dimensionalii. Two-dimensional

Single-dimensional

Hello Java !

Page 33: Hello java

Array and Methods

Some times user declares an array and it's size simultaneously. You may or may not be define the size in the declaration time. such as:

int arraytest[] = {50,20,45,82,25,63}; 

int arraytest[] = {50,20,45,82,25,63}; 

After that when implement this, arraytest = new int [6]; that’s mean

arraytest[o] arraytest[1] arraytest[2] arraytest[3] arraytest[4] arraytest[5]

arraytest.length = 6

arraytest

null

arraytest

When we declare the definition of array like that int [ ] arraytest; this will be in memory like below :-

Hello Java !

Page 34: Hello java

Array and Methods Hello Java !

import java.util.Scanner;public class test {/* * This program using to find the repeated max integer */public static void main(String[] args) { int numberCount; final int num=6; // final means const in another language int[ ] numbers=new int [num]; // Input data section for(int i=0;i<numbers.length;i++) { System.out.print("Enter the elment "); Scanner in = new Scanner( System.in ); numbers[i] = in.nextInt(); } //end for //Processing 1 section int max=numbers[0]; for (int i=0;i<numbers.length;i++) { if (max<numbers[i]) max=numbers[i]; } //end for //Processing 2 section int count=0; for (int i=0;i<numbers.length;i++) { if (numbers[i]==max) count++; } // end for //Output data sectionSystem.out.print("the array data are :" );for(int i=0;i<numbers.length;i++)System.out.print(numbers[i] + " "); //output all array dataSystem.out.println("\n the largest number is " +max); // output the maxSystem.out.println("the occurrence count of the largest number is " +count); // output the freguncy of max }}

Enter the elment 4Enter the elment 8Enter the elment 0Enter the elment 9Enter the elment 3Enter the elment 9the array data are :4 8 0 9 3 9 the largest number is 9the occurrence count of the largest number is 2

Output

Page 35: Hello java

Array and Methods Hello Java !

Exampleint [ ][ ] num; num = new int [6][6]; or we can also :  int [ ][ ]num = new int [6][6]; and also we can write int num[ ][ ] = new int [6][6];

Two Dimensional Array

Declaration :Syntax: DataType[ ][ ] ArrayRefVar=new DataType[sizeofrow][sizeofcolumn]

Exercise10: Write program to sort an integer array? arrayElm[5].

Exercise11: Write program to sort an integer two dimensional array? arrayElm[5][5].

Page 36: Hello java

Array and Methods Hello Java !

Java MethodsIn programming, experience has shown that the best way to develop and

maintain a large program is to construct it from small, simple pieces or modules. This technique is called divide and conquer. Modules in Java are called methods and classes. Many methods and classes are already available “prepackaged” in the Java API (Java Class Library).

One of the important classes in Java is the Math class that has many methods allowing the programmer to perform certain common mathematical calculations. The Math class is part of the java.lang.Math package, which is automatically imported by the compiler.

Example:System.out.println (Math.sqrt(900.0));System.out.println (Math.sin (0.0));

For more details and methods visit the website:https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html

Page 37: Hello java

Array and Methods Hello Java !

Java Methods

Main method Users-defined methodsJava library methods

• Any method in java contain two part: method header and method body

[< method_specify>] <return_type> <method_name> ([< formal parameters >]) { // method body (declarations and statements) }

Note : the bracket [ ], means inside it optional.Important notes:• If the return type is void then the return statements inside the method

should return nothing.• Don’t put a semicolon after the first line of the method definition.• Each variable in the parameter list should have a type.• A method cannot be defined inside another method.

Constructor methods

Page 38: Hello java

Array and Methods Hello Java !

public double maximum (double x, double) { if (x>y) return x; return y; }

Main method Declaration: public static void main(String[ ] args) { // method body (declarations and statements) }

Users-defined method

Java library method

Math.max ( x, Math.max ( y, z));

Constructors methodpublic class A{public A( ) { }public A(int m){……..}

Page 39: Hello java

Array and Methods Hello Java !

Methods in the same class

public class A{public static void main(String[ ] arg){……}public static int max(int a, int y){…….}

public static boolean check(boolean a){……}……..…….…….…….} end class A

Methods in the different class

public class A{public static void main(String[ ] arg){……}public static int max(int a, int y){…….}} // end class A

public class B{public boolean check(boolean a){……}

public double sum(double[ ] arr){…….}} //end class B

Very Important note

Page 40: Hello java

Array and Methods Hello Java !

• Value-returning methods: have return typeo Return a value of a specific data type using return statement;o The returned value can be used in one of the following scenarios:

Save the value for further calculation Example : int out; out=max(a , b);

Using the value in some calculation Example : out=max(a , b)/2;

Print the value Example : System.out.print(max(a , b));

Users-defined method

Value-returning methods Void methods

• Void methods: do not have return type (i.e. return 0;)o Do not use a return statement to return a value

Page 41: Hello java

Array and Methods Hello Java !

Invoking method: method_name([Actual parameters without data type]);

Example: int data[ ] = (55,72,35,19,74}; sum(data);

public class Methods{

  public static void DisplayMyInfo ( ) {

      System.out.print("My name is Mhamad Harmush \n");      System.out.print("I made harmash.com when i was 20 years old \n");      System.out.print("I love programming \n");   }  public static void main (String[] args) {        DisplayMyInfo();     }}

Page 42: Hello java

Array and Methods Hello Java !

import java.util.Scanner;

public class test {

// This program using to find the factorial to any number

public static void main(String[] args) {

int elm;System.out.print("Enter the number ");Scanner in = new Scanner( System.in ); elm = in.nextInt(); System.out.print(fact(elm)); // call method } // end main method

public static int fact(int dat){

int result=1;for(int i=dat; i>0; i--)result*=i;return result;} // end fact method }

Enter the number 5120

Output

Page 43: Hello java

Array and Methods Hello Java !

import java.util.Scanner;

public class test {

// This program using to find the factorial to any number

public static void main(String[] args) {

int elm; System.out.print("Enter the number ");Scanner in = new Scanner( System.in ); elm = in.nextInt();fact(elm); // call method } // end main method

public static void fact(int dat){

int result=1;for(int i=dat; i>0; i--) result*=i; System.out.print(result); } // end fact method }

Enter the number 5120

Output

Page 44: Hello java

Array and Methods Hello Java !

import java.util.Scanner;

public class test {

// This program using to find the factorial to any number

public static void main(String[] args) {

int elm;System.out.print("Enter the number ");Scanner in = new Scanner( System.in ); elm = in.nextInt(); System.out.print(fact(elm)); // call method } // end main method

public static int fact(int dat){

int result=1;for(int i=dat; i>0; i--)result*=i;return result;} // end fact method }

Enter the number 5120

Output

Page 45: Hello java

Array and Methods Hello Java !

import java.util.Scanner;import java.lang.Math;public class test {/* * to demonstrate the all concept above */public static void main(String[] args) { String circleArray[]={"Red", "Yellow", "Black", "White"}; double radius1, radius2; for(int i = 0; i< circleArray.length; i++) { radius1=0; radius2=0; System.out.print("Enter the radius1 for Circle "+ circleArray[i] +": "); Scanner in = new Scanner( System.in ); radius1 = in.nextDouble(); System.out.print("Enter the radius2 for Circle "+ circleArray[i] +": "); Scanner inn = new Scanner( System.in ); radius2 = inn.nextDouble();

if ((radius1 <= 0.0)|| (radius2 <= 0.0)) ExceptionError(); // Invoking void method

Page 46: Hello java

Array and Methods Hello Java !

else { double radius=Math.max(radius1, radius2); // Invoking Java library method System.out.println("The area for Circle "+ circleArray[i] +" is: " + radius); // Invoking Users-defined methods System.out.println("The area for Circle "+ circleArray[i] +" is: " + getArea(radius)); System.out.println("The area for Circle "+ circleArray[i] +" is: " + getDiameter(radius)); System.out.println("The area for Circle "+ circleArray[i] +" is: " + getCircumference(radius)); } // end else

} // end for

} // end main method

// Declaration users - Value return methodspublic static double getArea(double radius){return Math.PI * radius * radius;} // end method

Page 47: Hello java

Array and Methods Hello Java !

public static double getDiameter(double radius){return radius * 2;} // end method public static double getCircumference(double radius){return Math.PI * radius * 2; } // end method

// Declaration users - Void methodspublic static void ExceptionError(){System.out.println("The radius is not except"); } // end method } //end class

Enter the radius1 for Circle Red: 3.7Enter the radius2 for Circle Red: 6.2The area for Circle Red is: 6.2The area for Circle Red is: 120.76282160399165The area for Circle Red is: 12.4The area for Circle Red is: 38.955748904513435Enter the radius1 for Circle Yellow: 5Enter the radius2 for Circle Yellow: 4.1The area for Circle Yellow is: 5.0The area for Circle Yellow is: 78.53981633974483The area for Circle Yellow is: 10.0The area for Circle Yellow is: 31.41592653589793Enter the radius1 for Circle Black: 5.8

Output

Page 48: Hello java

Array and Methods Hello Java !

Enter the radius2 for Circle Black: 4.3The area for Circle Black is: 5.8The area for Circle Black is: 105.68317686676063The area for Circle Black is: 11.6The area for Circle Black is: 36.4424747816416Enter the radius1 for Circle White: 1.9Enter the radius2 for Circle White: 1.8The area for Circle White is: 1.9The area for Circle White is: 11.341149479459153The area for Circle White is: 3.8The area for Circle White is: 11.938052083641214

import java.util.Scanner;

public class test {/* * to demonstrate the all concept above */public static void main(String[] args) {

int val=0;int data[][]={{4, 16, 2, 8, 3}, {9, 5, 11, 2, 25}, {2, 3, 14, 7, 0}, {21, 15, 3, 6, 23}, {19, 8, 23, 7, 21}};

Page 49: Hello java

Array and Methods Hello Java !

do{System.out.println("Array Operations");System.out.println("---------------------------------");System.out.println("1- Print Main Diagonal");System.out.println("2- Print Secondary Diagonal");System.out.println("3- Print Upper Triangle");System.out.println("4- Print Lower Triangle");System.out.println("5- Return the Avarage ");System.out.println("6- Return the First Odd Data ");System.out.println("7- Return the Least Even Data ");System.out.println("8- Print the Array ");System.out.println("0- Exit ");System.out.println("----------------------------------");

System.out.print("Enter your choice ");Scanner in = new Scanner( System.in ); val=in.nextInt();

switch (val){case 1: { mainDiagonal(data); break;}case 2: { secondaryDiagonal(data); break; }case 3: { upperTriangle(data); break;}case 4: { lowerTriangle(data); break; }case 5: { float result=arrayAvarge(data); System.out.println(result); break; }

Page 50: Hello java

Array and Methods Hello Java !

case 6: { int result=firstOddData(data); System.out.println(result); break;}case 7: { int result=leastEvenData(data); System.out.println(result); break;}case 8: { print(data); break; }default: System.out.println(" Exit");}

}while (val != 0);

}// end main method

public static void mainDiagonal(int data[][]){

for(int i=0; i<5; i++)for(int j=0; j<5; j++)if (i == j) System.out.print(" " + data[i][j]); System.out.println(); }

public static void secondaryDiagonal(int data[][]){

for(int i=0; i<5; i++)

Page 51: Hello java

Array and Methods Hello Java !

for(int j=0; j<5; j++)if (i+j == 4) System.out.print(" " + data[i][j]); System.out.println(); }

public static void upperTriangle(int data[][]){

for(int i=0; i<5; i++)for(int j=0; j<5; j++)if (i<j) System.out.print(" " + data[i][j]); System.out.println(); } public static void lowerTriangle(int data[][]){

for(int i=0; i<5; i++)for(int j=0; j<5; j++)if (i>j) System.out.print(" " + data[i][j]); System.out.println(); }

Page 52: Hello java

Array and Methods Hello Java !

public static void print(int data[][]){

for(int i=0; i<5; i++)for(int j=0; j<5; j++) System.out.print(" " + data[i][j]); System.out.println(); }

public static float arrayAvarge(int data[][]){ float avg; int sum=0; for(int i=0; i<5; i++) for(int j=0; j<5; j++) sum+=data[i][j]; return avg=sum/25; }

public static int firstOddData(int data[][]){ int res=0; for(int i=0; i<5; i++){ for(int j=0; j<5; j++) if (data[i][j]%2 != 0) res=data[i][j]; break;}return res; }

Page 53: Hello java

Array and Methods Hello Java !

public static int leastEvenData(int data[][]){

int res=0; for(int i=0; i<5; i++) for(int j=0; j<5; j++) if (data[i][j]%2 == 0) res=data[i][j]; return res; }

} //end class

Array Operations---------------------------------1- Print Main Diagonal2- Print Secondary Diagonal3- Print Upper Triangle4- Print Lower Triangle5- Return the Avarage 6- Return the First Odd Data 7- Return the Least Even Data 8- Print the Array 0- Exit ----------------------------------Enter your choice 0 Exit

Output

Page 54: Hello java

Array and Methods Hello Java !

Exercise12: Write a boolean method called hasEight(), which takes an integer as input and returns true if the number contains the digit 8 (e.g., 18, 808). The signature of the method is as follows:

public static boolean hasEight(int number)

Exercise13: Write a boolean method called contains(), which takes an array of int and an int; and returns true if the array contains the given int. The method's signature is as follows:

public static boolean contains(int[] array, int key)

Exercise14: Write a boolean method called equals(), which takes two arrays of int and returns true if the two arrays are exactly the same (i.e., same length and same contents). The method's signature is as follows:

public static boolean equals(int[] array1, int[] array2)

Page 55: Hello java

Array and Methods Hello Java !

Exercise15: Write a program called GradesStatistics, which reads in n grades (of int between 0 and 100, inclusive) and displays the average, minimum, maximum, median and standard deviation. Display the floating-point values upto 2 decimal places. Your output shall look like:

Enter the number of students: 4Enter the grade for student 1: 50Enter the grade for student 2: 51Enter the grade for student 3: 56Enter the grade for student 4: 53{50,51,56,53}The average is: 52.50The median is: 52.00The minimum is: 50The maximum is: 56The standard deviation is: 2.29

The formula for calculating standard deviation is:

Page 56: Hello java

Array and Methods Hello Java !

Exercise16: Write a method to compute e and exp(x) using the following series expansion, in a class called TrigonometricSeries. The signatures of the methods are:

public static double exp(int numTerms) // x in radianspublic static double exp(double x, int numTerms)

End The Hello Java! – Level 1

Page 57: Hello java

Level 1

Level 2

Level 3

Level 4

Level 5

Java Levels

Page 58: Hello java

Are you Interested to continue with us – Hello Java! – Level 2

Hello Java! – Level 2OOP with Java

Class, Object, InterfaceArrayList, Stack, QueueOverloading, Overriding

NEW