Você está na página 1de 92

http://www.tutorialspoint.com/java/index.htm http://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.

html

The Basic Java Application

A Program is a sequence of instructions that a

computer can execute to perform some task. Java is an object-oriented programming language developed by Sun Microsystems, a company best known for its high-end Unix workstations. What is Object-Oriented Programming Object-Oriented Programming (OOP) is different from procedural programming languages (C, Pascal, etc.) in several ways. Everything in OOP is grouped as "objects"

The Java virtual machine (JVM) is a software

implementation of a computer that executes programs like a real machine. The Java virtual machine is written specifically for a specific operating system, e.g. for Linux a special implementation is required as well as for Windows. Java programs are compiled by the Java compiler into so-called bytecode. The Java virtual machine interprets this bytecode and executes the Java program. Bytecodes are a set of instructions that looks a lot like some machine codes, but that is not specific to any one processor.

Java comes in two flavors, the Java Runtime

Environment (JRE) and the Java Development Kit (JDK). The Java runtime environment (JRE) consists of the JVM and the Java class libraries and contains the necessary functionality to start Java programs. The JDK contains in addition the development tools necessary to create Java programs. The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java class libraries.

Java has the following properties: Platform independent: Java programs use the Java virtual machine as abstraction and do not access the operating system directly. This makes Java programs highly portable. A Java program which is standard complaint and follows certain rules can run unmodified on all supported platforms, e.g. Windows or Linux. Object-orientated programming language: Except the primitive data types, all elements in Java are objects. Strongly-typed programming language: Java is strongly-typed, e.g. the types of the used variables must be pre-defined and conversion to other objects is relatively strict, e.g. must be done in most cases by the programmer.

Interpreted and compiled language: Java source code is

transferred into the bytecode format which does not depend on the target platform. These bytecode instructions will be interpreted by the Java Virtual machine (JVM). The JVM contains a so called HotspotCompiler which translates performance critical bytecode instructions into native code instructions. Automatic memory management(Robust): Java manages the memory allocation and de-allocation for creating new objects. The program does not have direct access to the memory. The so-called garbage collector deletes automatically objects to which no active pointer exists. The Java syntax is similar to C++. Java is case sensitive, e.g. the variables myValue and myvalue will be treated as different variables.

Java is distributed

Commonly used Internet protocols such as HTTP and FTP as well as calls for network access are built into Java. Internet programmers can call on the functions through the supplied libraries and be able to access files on the Internet as easily as writing to a local file system. Java is secure The Java language has built-in capabilities to ensure that violations of security do not occur. Even though the Java compiler produces only correct Java code, there is still the possibility of the code being tampered with between compilation and runtime. Java guards against this by using the bytecode verifier to check the bytecode for language compliance when the code first enters the interpreter, before it ever even gets the chance to run.

Java is portable

By porting an interpreter for the Java Virtual Machine to any computer hardware/operating system, one is assured that all code compiled for it will run on that system. This forms the basis for Java's portability. Another feature which Java employs in order to guarantee portability is by creating a single standard for data sizes irrespective of processor or operating system platforms. Java is high-performance The Java language supports many high-performance features such as multithreading, just-in-time compiling, and native code usage.

The programmer writes Java source code in a text

editor which supports plain text. Normally the programmer uses an Integrated Development Environment (IDE) for programming. An IDE supports the programmer in the task of writing code, e.g. it provides auto-formating of the source code, highlighting of the important keywords, etc. At some point the programmer (or the IDE) calls the Java compiler (javac). The Java compiler creates the bytecode instructions. . These instructions are stored in .class files and can be executed by the Java Virtual Machine.

Java Class Libraries


The collection of preexisting Java code that

provides solutions to common programming problems. The Java program files that you create must use the extension .java. When you compile a Java program, the resulting Java bytecodes are stored in a file with the same name and the extension .class.

Java programming OOP

Class

A unit of code that is the basic building block of Java programs. Or

A class is a blueprint or prototype from which objects are created.


The basic form of a Java class is as follows: public class <name> { <method> <method> ... <method> }

Method(Behavior)

A program unit that represents a particular action or computation. Or A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Or Methods are functions defined inside classes that operate on instances of those classes. Example: public class Hello2 { public static void main(String[] args) { System.out.println("Hello, world!"); System.out.println(); System.out.println("This program produces four"); System.out.println("lines of output."); }}

Object

An object is an instance of a class. Objects have states and behaviors. An object's state is created by the values assigned to these instant variables.

About Java programs, it is very important to keep in mind the following points. Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have different meaning in Java.

Class Names - For all class names the first letter should be in Upper Case. If several words are used to form a name of the class each inner words first letter should be in Upper Case. Example class MyFirstJavaClass Method Names - All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example public void myMethodName() Program File Name - Name of the program file should exactly match the class name. When saving the file you should save it using the class name (Remember java is case sensitive) and append '.java' to the end of the name. (if the file name and the class name do not match your program will not compile). Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java public static void main(String args[]) - java program processing starts from the main() method which is a mandatory part of every java program..

A name given to an entity in a program, such as a class or method. Or Names used for classes, variables and methods are called identifiers. In java there are several points to remember about identifiers. o All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an underscore (-). o After the first character identifiers can have any combination of characters. o A key word cannot be used as an identifier. o Most importantly identifiers are case sensitive. o Examples of legal identifiers: age, $salary, _value, __1_value o Examples of illegal identifiers : 123abc, -salary

A sample of a class is given below:

public class Dog{ String breed; int age; String color;


void barking(){ } void hungry(){ } void sleeping(){ } }

class Motorcycle { String make; String color; boolean engineState; void startEngine() { if (engineState == true) System.out.println(The engine is already on.); else { engineState = true; System.out.println(The engine is now on.); }}} public static void main (String args[]) { Motorcycle m = new Motorcycle(); m.make = Yamaha RZ350; m.color = yellow; }

The first line of the class is known as the class

header. The word public in the header indicates that this class is available to anyone to use. Class is enclosed in curly brace characters ({ }). These characters are used in Java to group together related bits of code. In this case, the curly braces are indicating that everything defined within them is part of this public class.

The Main method is the method in which execution to any java program begins. A main method declaration looks as follows: public static void main(String args[]){ } The method is public because it be accessible to the JVM to begin execution of the program.

It is Static because it be available for execution without an object instance. you may know that you need an object instance to invoke any method. So you cannot begin execution of a class without its object if the main method was not static.
It returns only a void because, once the main method execution is over, the program terminates. So there can be no data that can be returned by the Main method The last parameter is String args[]. This is used to signify that the user may opt to enter parameters to the java program at command line. We can use both String[] args or String args[]. The Java compiler would accept both forms.

One of the simplest and most common statements is

System.out.println, which is used to produce a line of output. System.out.println("This line uses the println method."); The above statement commands the computer to produce the following line of output: This line uses the println method.

Modifiers are keywords that you add to those definitions

to change their meanings. The Java language has a wide variety of modifiers, including the following The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes.
Package?

A package is a namespace that organizes a set of related classes interface? Methods form the object's interface with the outside world;

Modifier protected public

Used on member class interface member

Meaning Accessible only within its package and its subclasses Accessible anywhere Accessible anywhere Accessible anywhere its class is.

none(package)

class
member

Accessible only in its package


Accessible only in its package

private
final

member
class method variable

Accessible only in its class(which defines it).


Cannot be subclassed Cannot be overridden and dynamically looked up Cannot change its value

Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are: Visible to the package. the default. No modifiers are needed. Visible to the class only (private). Visible to the world (public). Visible to the package and all subclasses (protected). The final modifier for finalizing the implementations of classes, methods, and variables. The abstract modifier for creating abstract classes and methods.

A class can contain any of the following variable types. Local variables . variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. Instance variables . Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. Class variables . Class variables are variables declared with in a class, outside any method, with the static keyword.

Instance Variables (Non-Static Fields) Technically

speaking, objects store their individual states in "nonstatic fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. When a number of objects are created from the same class, each instance has its own copy of class variables.

public class NonStaticVariable { int noOfInstances; NonStaticVariable(){ noOfInstances++; } public static void main(String[] args){ NonStaticVariable st1 = new NonStaticVariable(); System.out.println("No. of instances for st1 : " + st1.noOfInstances); NonStaticVariable st2 = new NonStaticVariable(); System.out.println("No. of instances for st1 : " + st1.noOfInstances); System.out.println("No. of instances for st2 : " + st2.noOfInstances); NonStaticVariable st3 = new NonStaticVariable(); System.out.println("No. of instances for st1 : " + st1.noOfInstances); System.out.println("No. of instances for st2 : " + st2.noOfInstances); System.out.println("No. of instances for st3 : " + st3.noOfInstances); }}

public class StaticVariable { static int noOfInstances; StaticVariable(){ noOfInstances++; } public static void main(String[] args){ StaticVariable sv1 = new StaticVariable(); System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);

StaticVariable sv2 = new StaticVariable(); System.out.println("No. of instances for sv1 : " + sv1.noOfInstances); System.out.println("No. of instances for st2 : " + sv2.noOfInstances);
StaticVariable sv3 = new StaticVariable(); System.out.println("No. of instances for sv1 : " + sv1.noOfInstances); System.out.println("No. of instances for sv2 : " + sv2.noOfInstances); System.out.println("No. of instances for sv3 : " + sv3.noOfInstances); } }

Variables are nothing but reserved memory

locations to store values. This means that when you create a variable you reserve some space in memory. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. There are two data types available in Java:
Primitive Data Types b. Reference/Object Data Types
a.

Primitive Data Types: There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a key word. Let us now look into detail about the eight primitive data types.

byte: Byte data type is a 8-bit signed two's complement integer. Minimum value is -128 (-2^7) Maximum value is 127 (inclusive)(2^7 -1) Default value is 0 Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int. Example : byte a = 100 , byte b = -50

short: Short data type is a 16-bit signed two's complement integer. Minimum value is -32,768 (-2^15) Maximum value is 32,767(inclusive) (2^15 -1) Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int Default value is 0. Example : short s= 10000 , short r = -20000 int: Int data type is a 32-bit signed two's complement integer. Minimum value is - 2,147,483,648.(-2^31) Maximum value is 2,147,483,647(inclusive).(2^31 -1) Int is generally used as the default data type for integral values unless there is a concern about memory. The default value is 0. Example : int a = 100000, int b = -200000

long: o Long data type is a 64-bit signed two's complement integer. o Minimum value is -9,223,372,036,854,775,808.(-2^63) o Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1) o This type is used when a wider range than int is needed. o Default value is 0L. o Example : int a = 100000L, int b = -200000L float: o Float data type is a single-precision 32-bit IEEE 754 floating point. o Float is mainly used to save memory in large arrays of floating point numbers. o Default value is 0.0f. o Float data type is never used for precise values such as currency. o Example : float f1 = 234.5f

double: o double data type is a double-precision 64-bit IEEE 754 floating point. o This data type is generally used as the default data type for decimal values. generally the default choice. o Double data type should never be used for precise values such as currency. o Default value is 0.0d. o Example : double d1 = 123.4 boolean: o boolean data type represents one bit of information. o There are only two possible values : true and false. o This data type is used for simple flags that track true/false conditions. o Default value is false. o Example : boolean one = true

char: o char data type is a single 16-bit Unicode character. o Minimum value is '\u0000' (or 0). o Maximum value is '\uffff' (or 65,535 inclusive). o Char data type is used to store any character. o Example . char letterA ='A

Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy etc. o Class objects, and various type of array variables come under reference data type. o Default value of any reference variable is null. o A reference variable can be used to refer to any object of the declared type or any compatible type. o Example : Animal animal = new Animal("giraffe")

Reference Data Types:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:
Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Assignment Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators:
Operator + * / % ++ -Description Addition - Adds values on either side of the operator Subtraction - Subtracts right hand operand from left hand operand Multiplication - Multiplies values on either side of the operator Division - Divides left hand operand by right hand operand Modulus - Divides left hand operand by right hand operand and returns remainder Increment - Increase the value of operand by 1 Decrement - Decrease the value of operand by 1 Example A + B will give 30 A - B will give -10 A * B will give 200 B / A will give 2 B % A will give 0 B++ gives 21 B-- gives 19

There are following relational operators supported by Java language


Operat or == != > <

Description
Checks if the value of two operands are equal or not, if yes then condition becomes true. Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.

Example
(A == B) is not true. (A != B) is true. (A > B) is not true. (A < B) is true.

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

>=

Checks if the value of left operand is greater than or (A >= B) is not equal to the value of right operand, if yes then condition true. becomes true.

<=

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition

(A <= B) is true.

Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte.
Bitwise operator works on bits and perform bit by bit operation. Assume

if a = 60; and b = 13; Now in binary format they will be as follows: a = 0011 1100 b = 0000 1101 ----------------a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011
The following table lists the bitwise operators: Assume integer variable A holds 60 and variable B holds 13 then:

Operator Description

Example (A & B) will give 12 which is 0000 1100 (A | B) will give 61 which is 0011 1101 (A ^ B) will give 49 which is 0011 0001 (~A ) will give -60 which is 1100 0011

&
| ^ ~ <<

Binary AND Operator copies a bit to the result if it exists in both operands. Binary OR Operator copies a bit if it exists in eather operand. Binary XOR Operator copies the bit if it is set in one operand but not both. Binary Ones Complement Operator is unary and has the efect of 'flipping' bits.

Binary Left Shift Operator. The left A << 2 will give 240 which operands value is moved left by the number is 1111 0000 of bits specified by the right operand. Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. A >> 2 will give 15 which is 1111

>>

>>>

A >>>2 will give 15 which is 0000 1111

The following table lists the logical operators: Assume boolean variables A holds true and variable B

holds false then:


Description

Operator &&

Example (A && B) is false.

Called Logical AND operator. If both the operands are non zero then then condition becomes true. Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

||

(A || B) is true.

!(A && B) is true.

There are following assignment operators supported by Java

language:

Operator Description = Simple assignment operator, Assigns values from right side operands to left side operand

Example C = A + B will assigne value of A + B into C

+=

Add AND assignment operator, It adds right C += A is equivalent operand to the left operand and assign the result to C = C + A to left operand Subtract AND assignment operator, It subtracts C -= A is equivalent right operand from the left operand and assign to C = C - A the result to left operand Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C *= A is equivalent to C = C * A C /= A is equivalent to C = C / A

-=

*=

/=

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 :
o variable x = (expression) ? value if true : value if false

public class Test { 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 ); } }

o Consider the following code snippet. int i = 10; int n = i++%5;


(i++), you use the prefix version (++i))?

What are the values of i and n after the code is executed? What are the final values of i and n if instead of using the postfix increment operator

o To invert the value of a boolean, which operator would you use? Which

operator is used to compare two values, = or == ? o Explain the following code sample: result = someCondition ? value1 : value2; o In the following program, explain why the value "6" is printed twice in a row:
class PrePostDemo { public static void main(String[] args){ int i = 3; i++; System.out.println(i); // "4" ++i; System.out.println(i); // "5" System.out.println(++i); // "6" System.out.println(i++); // "6" System.out.println(i); // "7" }}

What happens if you declare a variable to be some integer type and then

give it a number outside the range of values that variable can hold?

There are two types of decision making statements in Java. They are: o if statements o switch statements The if Statement: An if statement consists of a Boolean expression followed by one or more statements. Syntax: The syntax of an if statement is: if(Boolean_expression) { //Statements will execute if the Boolean expression is true } 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.

public class Test { public static void main(String args[]){ int x = 10; if( x < 20 ) { System.out.print("This is if statement"); } } }

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. Syntax: The syntax of a if...else is: if(Boolean_expression){ //Executes when the Boolean expression is true } Else { //Executes when the Boolean expression is false }

public class Test { public static void main(String args[]){ int x = 30; if( x < 20 ) { System.out.print("This is if statement"); } Else { System.out.print("This is else statement"); }}}

An if statement can be followed by an optional else if...else statement, which is very usefull to test various conditions using single if...else if statement. Syntax: The syntax of a if...else is: if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true } else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true } else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true } else { //Executes when the none of the above condition is true. }

public class Test { public static void main(String args[]){ int x = 30; if( x == 10 ){ System.out.print("Value of X is 10"); } else if( x == 20 ){ System.out.print("Value of X is 20"); } else if( x == 30 ){ System.out.print("Value of X is 30"); } else{ System.out.print("This is else statement"); }}}

class IfElseDemo { public static void main(String[] args) { int testscore = 76; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); } }

It is always legal to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement.
Syntax: The syntax for a nested if...else is as follows:

if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true }}

public class Test { public static void main(String args[]){ int x = 30; int y = 10; if( x == 30 ){ if( y == 10 ){ System.out.print("X = 30 and Y = 10"); }}}

A switch statement allows a variable to be tested for

equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

The 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 }

public class SwitchDemo { public static void main(String[] args) { int month = 8; String monthString; switch (month) { case 1: monthString = "January"; break; case 2: monthString = "February"; break; case 3: monthString = "March"; break; case 4: monthString = "April"; break; case 5: monthString = "May"; break; case 6: monthString = "June"; break; case 7: monthString = "July"; break; case 8: monthString = "August"; break; case 9: monthString = "September"; break; case 10: monthString = "October"; break; case 11: monthString = "November"; break; case 12: monthString = "December"; break; default: monthString = "Invalid month"; break; } System.out.println(monthString); } }

public class Test { public static void main(String args[]){ Char grade=D; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : break; case 'C' : System.out.println("Well done"); break; case 'D' : System.out.println("You passed"); break; case 'F' : System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); } }

Rewrite the above example 1 and 2 using if else

statement. Rewrite the above example in page 52 using case statement.

There may be a sitution when we need to execute a

block of code several number of times, and is often referred to as a loop. Java has very flexible three looping mechanisms. You can use one of the following three loops: while Loop do...while Loop for Loop

A while loop is a control structure that allows you to repeat a task a certain number of times when condition is true. Syntax: 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

public class Test { public static void main(String args[]) { int x = 10; while( x < 20 ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); }}}

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax: The syntax of a do...while loop is: do { //Statements } while(Boolean_expression);
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

public class Test { public static void main(String args[]){ int x = 10; do{ System.out.print("value of x : " + x ); x++; System.out.print("\n"); } while( x < 20 ); }}

The for statement provides a compact way to iterate over a range of

values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows: for (initialization; termination; increment) { statement(s) } When using this version of the for statement, keep in mind that: The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop. After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step,then Boolean expression). After the Boolean expression is false, the for loop terminates.

public class Test { public static void main(String args[]) { for(int x = 10; x < 20; x = x+1) { System.out.print("value of x : " + x ); System.out.print("\n"); }}}

The break Keyword:

The break keyword is used to stop the entire

loop. The break keyword must be used inside any loop or a switch statement The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.

public class tears { public static void main(String []args){ for(int x =0; x<=10;x++){ System.out.println("x is "+ x); if(x==6){ break; }}}}

The continue keyword can be used in any of the

loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes flow of control to immediately jump to the update statement. In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression

public class tears { public static void main(String []args){ for(int x =0; x<=10;x++){ if(x==5 || x==6){ continue; } System.out.println("x is "+ x); }}}

1.

Consider the following code snippet.

if (aNumber >= 0) if (aNumber == 0) System.out.println("first string");

else System.out.println("second string");


System.out.println("third string");

Use braces, { and }, to further clarify the code

What output do you think the code will produce if aNumber is 3?


Write a test program containing the previous code snippet; make aNumber 3. What is the output of the program? Is it what you predicted? Explain why the output is what it is; in other words, what is the control flow for the code snippet? Using only spaces and line breaks, reformat the code snippet to make the control flow easier to understand.

2. How do you write an infinite loop using the for statement? 3. How do you write an infinite loop using the while statement?

Java has a variation of the println command called

print that allows you to produce output on the current line without going to a new line of output. The println command really does two different things: It sends output to the current line, and then it moves to the beginning of a new line.

Identifier

A name given to an entity in a program, such as a

class or method.

Java has a set of predefined identifiers called

keywords that are reserved for particular uses.

Text that programmers include in a program to explain their code. The compiler ignores comments.

There are two comment forms in Java. In the first form, you open the comment with a slash followed by an asterisk and you close it with an asterisk followed by a slash:
/* like this */ You can put almost any text you like, including multiple lines, inside the comment: Java also provides a second comment form for shorter, single-line comments. You can use two slashes in a row to indicate that the rest of the current line (everything to the right of the two slashes) is a comment. For example, you can put a comment after a statement: System.out.println("You win!"); // Good job!

The array, which stores a fixed-size sequential

collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type Declaring Array Variables: To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable: dataType[] arrayRefVar; // preferred way. or dataType arrayRefVar[]; // works but not preferred way.

Note: The style dataType[] arrayRefVar is preferred. The style

dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

There are three steps to creating an array, declaring it,

allocating it and initializing it. Declaring Arrays Like other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. You cannot have an array that will store both ints and Strings, for instance. Like all other variables in Java an array must be declared. When you declare an array variable you suffix the type with [] to indicate that this variable is an array. Here are some examples: int[] k; float[] yt; String[] names;

Declaring an array merely says what it is. It does

not create the array. To actually create the array (or any other object) use the new operator. When we create an array we need to tell the compiler how many elements will be stored in it. Here's how we'd create the variables declared above: new k = new int[3]; yt = new float[7]; names = new String[50]; The numbers in the brackets specify the dimension of the array; i.e. how many slots it has to hold values. With the dimensions above k can hold three ints, yt can hold seven floats and names can hold fifty Strings.

Individual elements of the array are referenced

by the array name and by an integer which represents their position in the array. The numbers we use to identify them are called subscripts or indexes into the array. Subscripts are consecutive integers beginning with 0. Here's how we'd store values in the arrays we've been working with: k[0] = 2; k[1] = 5; k[2] = -2; yt[6] = 7.5f; names[4] = "Fred";

public class arr { public static void main(String []args){ int []g; g=new int[21]; for(int i=0;i<=20;i++){ g[i]=i*2; } for (int i=0;i<=20;i++){ System.out.println("sasa "+g[i]); }}}

We can declare and allocate an array at the same time

like this: int[] k = new int[3]; float[] yt = new float[7]; String[] names = new String[50]; We can even declare, allocate, and initialize an array at the same time providing a list of the initial values inside brackets like so:
int[] k = {1, 2, 3}; float[] yt = {0.0f, 1.2f, 3.4f, -9.87f, 65.4f, 0.0f,

567.9f};

class ArrayDemo { public static void main(String[] args) { // declares an array of integers int[] anArray; // allocates memory for 10 integers anArray = new int[10]; // initialize first element anArray[0] = 100; // initialize second element anArray[1] = 200; anArray[2] = 300; anArray[3] = 400; anArray[4] = 500; anArray[5] = 600; System.out.println("Element at index 0: " + anArray[0]); System.out.println("Element at index 1: " + anArray[1]); System.out.println("Element at index 2: " + anArray[2]); System.out.println("Element at index 3: " + anArray[3]); System.out.println("Element at index 4: " + anArray[4]); System.out.println("Element at index 5: " + anArray[5]); } }

public class Sum

{
public static void main(String[] args) { int[] x = new int [101]; for (int i = 0; i<x.length; i++ ) x[i] = i; int sum = 0; for(int i = 0; i<x.length; i++) sum += x[i]; System.out.println(sum); }

It means to copy data from one array to another. The precise way to

copy data from one array to another is public static void arraycopy(Object source, int srcIndex, Object dest, int destIndex, int length)
Thus apply system's arraycopy method for copying arrays.The

parameters being used are : src the source array srcIndex start position (first cell to copy) in the source array dest the destination array destIndex start position in the destination array length the number of array elements to be copied The following program, ArrayCopyDemo(in a .java source file), uses arraycopy to copy some elements from the copyFrom array to the copyTo array.

public class ArrayCopyDemo{

public static void main(String[] args){ char[] copyFrom = {'a','b','c','d','e','f','g','h','i','j'}; char[] copyTo = new char[5]; System.arraycopy(copyFrom, 2, copyTo, 0, 5); System.out.println(new String (copyTo)); } }

To store data in more dimensions a multi-

dimensional array is used. A multi-dimensional array of dimension n is a collection of items A multi dimensional array is one that can hold all the values below. You set them up like this: int[ ][ ] aryNumbers = new int[6][5];

They are set up in the same way as a normal array, except you

have two sets of square brackets. The first set of square brackets is for the rows and the second set of square brackets is for the columns. aryNumbers[0][0] = 10; aryNumbers[0][1] = 12; aryNumbers[0][2] = 43; aryNumbers[0][3] = 11; aryNumbers[0][4] = 22;
So the first row is row 0. The columns then go from 0 to 4, which

is 5 items. To fill the second row, it would be this: aryNumbers[1][0] = 20; aryNumbers[1][1] = 45; aryNumbers[1][2] = 56; aryNumbers[1][3] = 1; aryNumbers[1][4] = 33;

public class as { public static void main(String args[]){ int [][]myarr; myarr=new int[2][2]; myarr[0][0]=2; myarr[0][1]=4; myarr[1][0]=12; myarr[1][1]=27; int row=2,column=2; int x,y;

for(x=0;x<row;x++){
for(y=0;y<column;y++){ System.out.print(myarr[x][y]+ " ");} System.out.println(" ");}} }

int[ ] aryNums = { 24, 6, 47, 35, 2, 14 }; int i; int oddNum = 0; for (i=0; i < aryNums.length; i++) { oddNum = aryNums[ i ] %2; if (oddNum == 1) { System.out.println("odd number = " + aryNums[i]); } }

1. How many times does the following loop repeat? What is the output?

byte b = 1; do { b++; }while(!(b < 10)); System.out.println(b);

2.

What is the output of the following code?

int y = 100, x = 5; while(y > 0) { y--; if(y%x != 0) { continue; } System.out.println(y); }

writing a programme to print out all the values from

the spreadsheet. Your Output window should look something like this when you're done

What will be the output of the code below: class FillArray { public static void main (String args[]) { int[][] M; M = new int[4][5]; for (int row=0; row < 4; row++) { for (int col=0; col < 5; col++) { M[row][col] = row+col; } } } }

Você também pode gostar