by: a.abbasi omid reza nejati [email protected] marvdasht islamic azad university

44
Java Programming By: A.Abbasi Omid Reza Nejati [email protected] Marvdasht Islamic Azad University

Upload: eleanor-morton

Post on 11-Jan-2016

233 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java Programmi

ng

By: A.AbbasiOmid Reza Nejati

[email protected] Islamic Azad University

Page 2: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java Environment

Page 3: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Getting Started

Install the necessary Java components and files: • Java Virtual Machine which is also known as

Java Runtime Environment (JRE) is necessary to run any Java code.

• Java Software Development Kit is required to write your code and test it out.

• NetBeans as one of the most popular IDEs (Interface Development Environments). NetBeans handles all the editing, creating, compiling and running for you.

Page 4: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

How Things Work in Java (cont’d)

Page 5: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Starting a New Project in NetBeans

To start a new project, click on File > New Project and do as the following:

Page 6: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Main Function

The word "main" is the main entry point for executing your programs. Whenever a Java program starts, it looks for this name to execute any code within its curly brackets.

Page 7: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Write and Save Your Code

Add the following line to your main method as your first simple program:

Now click File > Save, or File > Save All. Or click the Save icon on the NetBeans toolbar.

Page 8: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Running Java Programs in NetBeans

There are various ways to run your program in NetBeans: • Press F6 on your Keyboard. • Select Run Main Project from the Run menu.• click the green arrow on the NetBeans toolbar.

Page 9: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Sharing Java Programs

You can send your programs to other people so that they can run them. To do that, you need to create a JAR file (Java ARchive). From the Run menu of NetBeans, select Clean and Build Main Project.When you do, NetBeans saves your work and then creates all the necessary files. It will create a folder called dist and place all the files in there.

Page 10: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java Basics• Comments• Variables• Operators• Expressions, Statements and Blocks• Control Flow Statements• Arrays• Basic Input/Output

Page 11: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Comments

• Comments are used to explain a special part of code, give some information about the program goal, the programmer, the code version, and etc.

• When a program is compiled, all the comments are ignored. • Java supports single-line comments:

//This is a single line comment as well as comments in multiple lines. The syntax is as the following:

/*This is a comment spreadingover two lines or more*/

Page 12: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Variables

• Programs work by manipulating data placed in memory. The data can be numbers, text, characters, and more besides. The data is given a name, so that it can be re-called whenever it is need. The name, and its value, is known as a Variable.

• Java is statically-typed, which means that all variables must first be declared before they can be used. Java has the following syntax for declaring a variable:

Data-type Variable-name;

Page 13: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Primitive Data Types

• byte: an 8-bit signed two's complement integer (-128 .. +127)

• short: a 16-bit signed two's complement integer (-32768 .. +32767)

• int: a 32-bit signed two's complement integer (-231 .. 231-1)• long: a 64-bit two's complement integer (-263 .. 263-1)• float: a single-precision 32-bit IEEE 754 floating point• double: a double-precision 64-bit IEEE 754 floating point• boolean: true or false value• char: a single 16-bit Unicode character (0 .. 65535)• String: Java supports character strings via java.lang.String

Page 14: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Variable Names

• Variable names are case-sensitive.• A variable's name can be any legal identifier: an unlimited-

length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_".

• int: a 32-bit signed two's complement integer (-231 .. 231-1)• long: a 64-bit two's complement integer (-263 .. 263-1)• float: a single-precision 32-bit IEEE 754 floating point• double: a double-precision 64-bit IEEE 754 floating point• boolean: true or false value• char: a single 16-bit Unicode character (0 .. 65535)• String: Java supports character strings via java.lang.String

Page 15: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Literals

A literal is the source code representation of a fixed value.

• Integer literals: An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int. Integer literals can be expressed by these number systems:

- Decimal (Base 10): e.g. 26 - Hexadecimal (Base 16): e.g. 0x1a - Binary (Base 2; available in Java SE 7 and later): e.g. 0b11010

Page 16: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Literals (cont’d)

Floating-Point Literals: A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.The floating point types can also be expressed using E or e for scientific notation.

Page 17: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java IdentifiersAll Java components require names. Names used for classes, variables and methods are called identifiers. In Java, there are several points to remember about identifiers. They are as follows: All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_). After the first character, identifiers can have any combination of characters. A keyword cannot be used as an identifier. Most importantly identifiers are case sensitive. Examples of legal identifiers : age, $salary, _value, __1_value Examples of illegal identifiers: 123abc, -salary

Page 18: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java keywords

The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.

Page 19: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java keywords

abstract assert boolean break

byte case catch char

class const continue default

do double else enum

extends final finally float

for goto implements if

import instanceof interface int

long native package new

private protected public return

short static strictfp super

switch this synchronized throw

throws transient void try

volatile while

Page 20: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java Basic Operators

Page 21: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java Relational Operators

Page 22: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java Relational Operators

Page 23: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java Bitwise Operators

Page 24: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java Logical Operators

Page 25: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java Conditional Operator (?:)

Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as: variable x =(expression)? value iftrue: value iffalse Following is the example:

This would produce the following result:

public static void main(String args[]){ Int a,b; a =10; b =(a ==1) ? 20 : 30; System.out.println("Value of b is : "+ b ); b =(a ==10) ? 20 : 30; System.out.println("Value of b is : "+ b ); } }

Value of b is:30 Value of b is:20

Page 26: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java Loop Control

Java has very flexible three looping mechanisms. You can use one of the following three loops:

while Loop do...while Loop for Loop

Page 27: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

The while LoopA while loop is a control structure that allows you to repeat a task a certain number of times.The syntax of a while loop is:

while(Boolean_expression) { //Statements }

When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true. Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Page 28: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

The do...while Loop

Do{ //Statements }while(Boolean_expression);

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

Page 29: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Example for do...while Loop

This would produce the following result:

Page 30: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

The for loopA for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. A for loop is useful when you know how many times a task is to be repeated. The syntax of a for loop is:for(initialization ; Boolean_expression ; update) { //Statements }

Page 31: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java Decision Making

There are two types of decision making statements in Java. They are: if statements switch statements

Page 32: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

The if Statement

if(Boolean_expression) { //Statements will execute if the Boolean expression is true }

An if statement consists of a Boolean expression followed by one or more statements.

The syntax of an if statement is:

If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If not, the first set of code after the end of the if statement(after the closing curly brace) will be executed.

Page 33: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

The if...else StatementAn if statement can be followed by an optional else statement, which executes when the Boolean expression is falseThe syntax of an if...else is:

if (Boolean_expression){ //Executes when the Boolean expression is true }else{ //Executes when the Boolean expression is false }

if(Boolean_expression1){ //Executes when the Boolean expression 1 is true }else if(Boolean_expression2){ //Executes when the Boolean expression 2 is true }else{ //Executes when the none of the above condition is true. }

An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. The syntax of an if...else if...else Statement

Page 34: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Example for if Loop

This would produce the following result:

Page 35: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

The switch Statement

A switch statement allows a variable to be tested for equality against a list ofvalues. Each value is called a case, and the variable being switched on is checked for each caseThe syntax of enhanced for loop is: switch(expression){ case value : //Statements break;//optional case value : //Statements break;//optional //You can have any number of case statements. default://Optional //Statements }

Page 36: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java ArraysCreating Arrays: You can create an array by using the new operator with the following syntax: dataType [] arrayRefVar = new dataType [arraySize];dataType [] arrayRefVar = {value0, value1,..., value n};For example:double[] myList =new double[10];Int [] my List= {5,6,4,8,9,3,12,45,10,20};Or Data type [][][]…[] arrayRefVar= new dataType [arraySize] [arraySize]… [arraySize];For example:Int [] [] x;X= new int [10][100];

Page 37: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java input and output (I/O)To import data You must import the java.util.Scanner class to declare and create instances of the Scanner class.

import java.util.Scanner; public class test {public static void main ( String [] args ) {scanner s= new Scanner( System.in );

For example:

import java.util.Scanner; public class test {public static void main ( String [] args ) {Int n;scanner s= new Scanner( System.in );n=s.nextint();n=*2;System.out.println(“n*2=“+n);

Page 38: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Java output We have used System.out.print(...) and System.out.println(...) statements for displaying simple text messages to the user.

int x = 3;double rate = 5.5;boolean playing = true;String phrase = "The winner is ";

System.out.print( "x = " + x);System.out.println( rate ); System.out.println( "playing = " + playing );System.out.println( phrase + "Deb" );

they can all be printed using print or println as follows:

For example, if the following variables are defined,

Page 39: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

Program example

1.Write a program that receives two numbers and prints their sum does

import java.util.Scanner;public class test{public static void main(String[] args) {int first; int second; int sum;Scanner s= new Scanner( System.in );System.out.print("Enter first number: "); first = s.nextInt(); System.out.print("Enter second number: "); second = s.nextInt();sum=first+second;System.out.print(“sum= “+sum);

Page 40: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

2.Write a program that receives two numbers and determine the maximum and minimum

import java.util.Scanner;public class test{public static void main(String[] args) {int m; int n; Scanner s= new Scanner( System.in );System.out.print("Enter first number: "); m= s.nextInt(); System.out.print("Enter second number: "); n= s.nextInt();If(m>n) System.out.print(“max=“+m,”min=“+n); else System.out.print(“max=“+n,”min=“+m);

Page 41: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

3.Write a program to print even numbers between two numbers

int x; int y; Scanner s= new Scanner( System.in );System.out.print("Enter first number: "); x= s.nextInt(); System.out.print("Enter second number: "); y= s.nextInt();int max,min;if(x>y){ max=x; min=y;}else{ max=y; min=x;}If(min%2==0){ for(int i=min;min<=max;i+=2){ System.out.println(i);}}else{ for(int i=min+1;min<=max;i+=2){ System.out.println(i);}

Page 42: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

4.Write a program to calculate the perimeter and area of a circle

int x; int y; Scanner s= new Scanner( System.in );System.out.print("Enter radius of the circle: "); n= s.nextInt(); Final double p = 3.14;System.out.println(“area of circle=“+p*(n*n);System.out.println(“perimeter of circle=“+p*(n*n);

Note: If you use the word final The variable remains constant and does not change during program

Page 43: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

5. Write a program that will get a ten numbered and write the sum of number.

int sum=0;int [] array;array = new int [10];Scanner s= new Scanner( System.in );for (i=1; i<=10 ; i++){System.out.print(“enter number:”);array=s.nextInt();sum=sum+array;}System.out.println(“sum=”+sum);

Note: to input a list of number you must use loop

Page 44: By: A.Abbasi Omid Reza Nejati Omid.nejati.73@live.com Marvdasht Islamic Azad University

The End