SlideShare a Scribd company logo
1 of 58
HELLO JAVA!
Raaid Alubady L
E
V
E
L
Celebrate IEEE Day with Coding Java
Beginning in Java
o Beginning in Java
o Components of Java Programming
o Java Variable and Data Type
Components and Control Tools
o 2.1. Data input
o 2.2. Data output
o 2.3. Condition statements
o 2.4. Loop statements
Array and Methods
Hello
Java
Hello
Java
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 !
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
Beginning in Java
Why Program in Java?
Hello
Java !
Beginning in Java
Why Program in Java?
Hello
Java !
Beginning in Java
Ready to learn JAVA.
If so, switch on your laptop.
Next , open Eclipse...
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)
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
Beginning in Java
Create the first project1
2
3
4
Hello
Java !
Beginning in Java
Create the first project
5
6
Hello
Java !
Beginning in Java
Create the first project
7
8
9
Hello
Java !
Beginning in Java
Create the first project
10
Hello
Java !
Beginning in Java
First Example: Hello class with Java
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 !
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 !
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 !
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 !
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 !
Hello
Java!
Components and Control Tools
Java 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
9817
9
8
17
The result = 17
Hello
Java!
Output
Java Data Input and out put
import 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.6
Enter the Second element 9.23
The answer is 12.83
Components and Control Tools
Hello
Java!
Output
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 Statement
Syntax: 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 ( )
Hello
Java!
Components and Control Tools
if, if/else, nistens if Statement
Example:
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”);
}
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
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}
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 1
Hello
Java!
Components and Control Tools
Loop Statements
 for loops
 while loops
 do/while loops
for loops
Syntax: 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);
}
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
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.5Hello
Java!
Components and Control Tools
while structure
Syntax: 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 while
public 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);
} }
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
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 array
i. Single-dimensional
ii. Two-dimensional
Single-dimensional
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 !
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 section
System.out.print("the array data are :" );
for(int i=0;i<numbers.length;i++)
System.out.print(numbers[i] + " "); //output all array data
System.out.println("n the largest number is " +max); // output the max
System.out.println("the occurrence count of the largest number is " +count); // output the
freguncy of max
}
}
Enter the elment 4
Enter the elment 8
Enter the elment 0
Enter the elment 9
Enter the elment 3
Enter the elment 9
the array data are :4 8 0 9 3 9
the largest number is 9
the occurrence count of the largest number is 2
Output
Array and Methods
Hello
Java !
Example
int [ ][ ] 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].
Array and Methods
Hello
Java !
Java Methods
In 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
Array and Methods
Hello
Java !
Java Methods
Main method Users-defined methods
Java 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
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 method
public class A{
public A( ) { }
public A(int m){
……..
}
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
Array and Methods
Hello
Java !
• Value-returning methods: have return type
o 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
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();
}
}
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 5
120
Output
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 5
120
Output
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 5
120
Output
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
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 methods
public static double getArea(double radius){
return Math.PI * radius * radius;
} // end method
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 methods
public static void ExceptionError(){
System.out.println("The radius is not except");
} // end method
} //end class
Enter the radius1 for Circle Red: 3.7
Enter the radius2 for Circle Red: 6.2
The area for Circle Red is: 6.2
The area for Circle Red is: 120.76282160399165
The area for Circle Red is: 12.4
The area for Circle Red is: 38.955748904513435
Enter the radius1 for Circle Yellow: 5
Enter the radius2 for Circle Yellow: 4.1
The area for Circle Yellow is: 5.0
The area for Circle Yellow is: 78.53981633974483
The area for Circle Yellow is: 10.0
The area for Circle Yellow is: 31.41592653589793
Enter the radius1 for Circle Black: 5.8
Output
Array and Methods
Hello
Java !
Enter the radius2 for Circle Black: 4.3
The area for Circle Black is: 5.8
The area for Circle Black is: 105.68317686676063
The area for Circle Black is: 11.6
The area for Circle Black is: 36.4424747816416
Enter the radius1 for Circle White: 1.9
Enter the radius2 for Circle White: 1.8
The area for Circle White is: 1.9
The area for Circle White is: 11.341149479459153
The area for Circle White is: 3.8
The 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}};
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; }
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++)
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();
}
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;
}
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 Diagonal
2- Print Secondary Diagonal
3- Print Upper Triangle
4- Print Lower Triangle
5- 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
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)
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: 4
Enter the grade for student 1: 50
Enter the grade for student 2: 51
Enter the grade for student 3: 56
Enter the grade for student 4: 53
{50,51,56,53}
The average is: 52.50
The median is: 52.00
The minimum is: 50
The maximum is: 56
The standard deviation is: 2.29
The formula for calculating standard deviation is:
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 radians
public static double exp(double x, int numTerms)
End The Hello Java! – Level 1
Level 1
Level 2
Level 3
Level 4
Level 5
Java Levels
Are you Interested to continue
with us – Hello Java! – Level 2
Hello Java! – Level 2
OOP with Java
Class, Object, Interface
ArrayList, Stack, Queue
Overloading, Overriding

More Related Content

What's hot

What's hot (18)

Core java Basics
Core java BasicsCore java Basics
Core java Basics
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Introduction to java Programming
Introduction to java ProgrammingIntroduction to java Programming
Introduction to java Programming
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Learn Java Part 2
Learn Java Part 2Learn Java Part 2
Learn Java Part 2
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic Concepts
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Core java
Core javaCore java
Core java
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Javatut1
Javatut1 Javatut1
Javatut1
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
 

Similar to Hello Java-First Level

Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introductionchnrketan
 
Introduction
IntroductionIntroduction
Introductionrichsoden
 
Unit of competency
Unit of competencyUnit of competency
Unit of competencyloidasacueza
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for DesignersR. Sosa
 
Java Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming BasicsJava Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming BasicsAkshaj Vadakkath Joshy
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for MainframersRich Helton
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1sotlsoc
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECSreedhar Chowdam
 
CSL101_Ch1.pptx
CSL101_Ch1.pptxCSL101_Ch1.pptx
CSL101_Ch1.pptxshivanka2
 
Fundamentals of oop lecture 2
Fundamentals of oop lecture 2Fundamentals of oop lecture 2
Fundamentals of oop lecture 2miiro30
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 

Similar to Hello Java-First Level (20)

Javalecture 1
Javalecture 1Javalecture 1
Javalecture 1
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introduction
 
Introduction
IntroductionIntroduction
Introduction
 
Unit of competency
Unit of competencyUnit of competency
Unit of competency
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
Java Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming BasicsJava Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming Basics
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
Java Notes
Java Notes Java Notes
Java Notes
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Core Java
Core JavaCore Java
Core Java
 
CSL101_Ch1.pptx
CSL101_Ch1.pptxCSL101_Ch1.pptx
CSL101_Ch1.pptx
 
CSL101_Ch1.pptx
CSL101_Ch1.pptxCSL101_Ch1.pptx
CSL101_Ch1.pptx
 
CSL101_Ch1.ppt
CSL101_Ch1.pptCSL101_Ch1.ppt
CSL101_Ch1.ppt
 
CSL101_Ch1.ppt
CSL101_Ch1.pptCSL101_Ch1.ppt
CSL101_Ch1.ppt
 
Java platform
Java platformJava platform
Java platform
 
Fundamentals of oop lecture 2
Fundamentals of oop lecture 2Fundamentals of oop lecture 2
Fundamentals of oop lecture 2
 
01slide
01slide01slide
01slide
 
01slide
01slide01slide
01slide
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 

Recently uploaded

Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 

Recently uploaded (20)

Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 

Hello Java-First Level

  • 1. HELLO JAVA! Raaid Alubady L E V E L Celebrate IEEE Day with Coding Java
  • 2. Beginning in Java o Beginning in Java o Components of Java Programming o Java Variable and Data Type Components and Control Tools o 2.1. Data input o 2.2. Data output o 2.3. Condition statements o 2.4. Loop statements Array and Methods Hello Java Hello Java Hello Java
  • 3. 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 !
  • 4. 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
  • 5. Beginning in Java Why Program in Java? Hello Java !
  • 6. Beginning in Java Why Program in Java? Hello Java !
  • 7. Beginning in Java Ready to learn JAVA. If so, switch on your laptop. Next , open Eclipse... Hello Java !
  • 8. 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)
  • 9. 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
  • 10. Beginning in Java Create the first project1 2 3 4 Hello Java !
  • 11. Beginning in Java Create the first project 5 6 Hello Java !
  • 12. Beginning in Java Create the first project 7 8 9 Hello Java !
  • 13. Beginning in Java Create the first project 10 Hello Java !
  • 14. Beginning in Java First Example: Hello class with Java Hello Java !
  • 15. 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 !
  • 16. 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 !
  • 17. 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 !
  • 18. 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 !
  • 19. 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 ! Hello Java!
  • 20. Components and Control Tools Java 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 9817 9 8 17 The result = 17 Hello Java! Output
  • 21. Java Data Input and out put import 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.6 Enter the Second element 9.23 The answer is 12.83 Components and Control Tools Hello Java! Output
  • 22. 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 Statement Syntax: 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 ( ) Hello Java!
  • 23. Components and Control Tools if, if/else, nistens if Statement Example: 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”); } Hello Java!
  • 24. 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 Hello Java!
  • 25. 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} Hello Java!
  • 26. 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 1 Hello Java!
  • 27. Components and Control Tools Loop Statements  for loops  while loops  do/while loops for loops Syntax: 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); } Hello Java!
  • 28. 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 Hello Java!
  • 29. 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.5Hello Java!
  • 30. Components and Control Tools while structure Syntax: 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 while public 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); } } Hello Java!
  • 31. 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 Hello Java!
  • 32. 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 array i. Single-dimensional ii. Two-dimensional Single-dimensional Hello Java !
  • 33. 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 !
  • 34. 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 section System.out.print("the array data are :" ); for(int i=0;i<numbers.length;i++) System.out.print(numbers[i] + " "); //output all array data System.out.println("n the largest number is " +max); // output the max System.out.println("the occurrence count of the largest number is " +count); // output the freguncy of max } } Enter the elment 4 Enter the elment 8 Enter the elment 0 Enter the elment 9 Enter the elment 3 Enter the elment 9 the array data are :4 8 0 9 3 9 the largest number is 9 the occurrence count of the largest number is 2 Output
  • 35. Array and Methods Hello Java ! Example int [ ][ ] 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].
  • 36. Array and Methods Hello Java ! Java Methods In 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
  • 37. Array and Methods Hello Java ! Java Methods Main method Users-defined methods Java 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
  • 38. 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 method public class A{ public A( ) { } public A(int m){ …….. }
  • 39. 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
  • 40. Array and Methods Hello Java ! • Value-returning methods: have return type o 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
  • 41. 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(); } }
  • 42. 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 5 120 Output
  • 43. 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 5 120 Output
  • 44. 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 5 120 Output
  • 45. 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
  • 46. 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 methods public static double getArea(double radius){ return Math.PI * radius * radius; } // end method
  • 47. 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 methods public static void ExceptionError(){ System.out.println("The radius is not except"); } // end method } //end class Enter the radius1 for Circle Red: 3.7 Enter the radius2 for Circle Red: 6.2 The area for Circle Red is: 6.2 The area for Circle Red is: 120.76282160399165 The area for Circle Red is: 12.4 The area for Circle Red is: 38.955748904513435 Enter the radius1 for Circle Yellow: 5 Enter the radius2 for Circle Yellow: 4.1 The area for Circle Yellow is: 5.0 The area for Circle Yellow is: 78.53981633974483 The area for Circle Yellow is: 10.0 The area for Circle Yellow is: 31.41592653589793 Enter the radius1 for Circle Black: 5.8 Output
  • 48. Array and Methods Hello Java ! Enter the radius2 for Circle Black: 4.3 The area for Circle Black is: 5.8 The area for Circle Black is: 105.68317686676063 The area for Circle Black is: 11.6 The area for Circle Black is: 36.4424747816416 Enter the radius1 for Circle White: 1.9 Enter the radius2 for Circle White: 1.8 The area for Circle White is: 1.9 The area for Circle White is: 11.341149479459153 The area for Circle White is: 3.8 The 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}};
  • 49. 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; }
  • 50. 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++)
  • 51. 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(); }
  • 52. 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; }
  • 53. 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 Diagonal 2- Print Secondary Diagonal 3- Print Upper Triangle 4- Print Lower Triangle 5- 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
  • 54. 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)
  • 55. 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: 4 Enter the grade for student 1: 50 Enter the grade for student 2: 51 Enter the grade for student 3: 56 Enter the grade for student 4: 53 {50,51,56,53} The average is: 52.50 The median is: 52.00 The minimum is: 50 The maximum is: 56 The standard deviation is: 2.29 The formula for calculating standard deviation is:
  • 56. 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 radians public static double exp(double x, int numTerms) End The Hello Java! – Level 1
  • 57. Level 1 Level 2 Level 3 Level 4 Level 5 Java Levels
  • 58. Are you Interested to continue with us – Hello Java! – Level 2 Hello Java! – Level 2 OOP with Java Class, Object, Interface ArrayList, Stack, Queue Overloading, Overriding