java programming

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

Upload: tass

Post on 23-Feb-2016

44 views

Category:

Documents


2 download

DESCRIPTION

Java Programming. By: A.Abbasi Omid Reza Nejati [email protected] Marvdasht Islamic Azad University. Java Environment. Getting Started. Install the necessary Java components and files: - PowerPoint PPT Presentation

TRANSCRIPT

Java ProgrammingBy: A.AbbasiOmid Reza [email protected] Islamic Azad University

1Java Environment2Getting StartedInstall 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.

3How Things Work in Java (contd)

4Starting a New Project in NetBeansTo start a new project, click on File > New Project and do as the following:

5Main FunctionThe 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.

6Write and Save Your CodeAdd 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.

7Running Java Programs in NetBeansThere 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.

8Sharing Java ProgramsYou 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.

9Java BasicsCommentsVariablesOperatorsExpressions, Statements and BlocksControl Flow StatementsArraysBasic Input/Output

10CommentsComments 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*/

11VariablesPrograms 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;12Primitive Data Typesbyte: 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 pointdouble: a double-precision 64-bit IEEE 754 floating pointboolean: true or false valuechar: a single 16-bit Unicode character (0 .. 65535)String: Java supports character strings via java.lang.String

13Variable NamesVariable 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 pointdouble: a double-precision 64-bit IEEE 754 floating pointboolean: true or false valuechar: a single 16-bit Unicode character (0 .. 65535)String: Java supports character strings via java.lang.String

14LiteralsA 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

15Literals (contd)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. 16Java 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 Java keywordsThe following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.

Java keywordsabstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto implements ifimport instanceof interface intlong native package newprivate protected public return short static strictfp super switch this synchronized throw throws transient void tryvolatile while Java Basic Operators

Java Relational Operators

Java Relational Operators

Java Bitwise Operators

Java Logical Operators

24Java 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 Java Loop ControlJava has very flexible three looping mechanisms. You can use one of the following three loops:

while Loop do...while Loop for Loop 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.The do...while LoopDo{ //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. Example for do...while Loop

This would produce the following result: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 } Java Decision MakingThere are two types of decision making statements in Java. They are: if statements switch statements The if Statementif(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.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

Example for if Loop

This would produce the following result:The switch StatementA 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 } 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];

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);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,Program example1.Write a program that receives two numbers and prints their sum doesimport 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); 2.Write a program that receives two numbers and determine the maximum and minimumimport 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);3.Write a program to print even numbers between two numbersint 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