Java Programming Lect1

Embed Size (px)

Citation preview

  • 7/28/2019 Java Programming Lect1

    1/92

    The Ba sic Java A pplicatio nhttp://www.tutorialspoint.com/java/index.htm

    http://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html

    http://www.tutorialspoint.com/java/index.htmhttp://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.htmlhttp://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.htmlhttp://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.htmlhttp://www.tutorialspoint.com/java/index.htm
  • 7/28/2019 Java Programming Lect1

    2/92

    A Program is a sequence of instructions that acomputer can execute to perform some task.

    Java is an object-oriented programming languagedeveloped by Sun Microsystems, a company best

    known for its high-end Unix workstations.What is Object-Oriented Programming

    Object-Oriented Programming (OOP) is differentfrom procedural programming languages (C, Pascal,etc.) in several ways. Everything in OOP is grouped as"objects"

  • 7/28/2019 Java Programming Lect1

    3/92

    The Java virtual machine (JVM) is a softwareimplementation of a computer that executes programslike a real machine.

    The Java virtual machine is written specifically for aspecific operating system, e.g. for Linux a specialimplementation is required as well as for Windows.

    Java programs are compiled by the Java compiler intoso-called bytecode. The Java virtual machineinterprets this bytecode and executes the Javaprogram.

    Bytecodes are a set of instructions that looks a lotlike some machine codes, but that is not specific toany one processor.

  • 7/28/2019 Java Programming Lect1

    4/92

    Java comes in two flavors, the Java RuntimeEnvironment (JRE) and the Java Development Kit(JDK).

    The Java runtime environment (JRE) consists of

    the JVM and the Java class libraries and containsthe necessary functionality to start Javaprograms.

    The JDK contains in addition the development

    tools necessary to create Java programs. TheJDK consists therefore of a Java compiler, theJava virtual machine, and the Java class libraries.

  • 7/28/2019 Java Programming Lect1

    5/92

    Java has the following properties: Platform independent: Java programs use the Java

    virtual machine as abstraction and do not access theoperating system directly. This makes Java programshighly portable. A Java program which is standard

    complaint and follows certain rules can run unmodifiedon 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 variablesmust be pre-defined and conversion to other objectsis relatively strict, e.g. must be done in most cases bythe programmer.

  • 7/28/2019 Java Programming Lect1

    6/92

    Interpreted and compiled language: Java source code istransferred into the bytecode format which does notdepend on the target platform. These bytecodeinstructions will be interpreted by the Java Virtualmachine (JVM). The JVM contains a so called Hotspot-Compiler which translates performance critical bytecodeinstructions into native code instructions.

    Automatic memory management(Robust): Java managesthe memory allocation and de-allocation for creating newobjects. The program does not have direct access to thememory. 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 asdifferent variables.

  • 7/28/2019 Java Programming Lect1

    7/92

    Java is distributedCommonly used Internet protocols such as HTTP and FTP as wellas calls for network access are built into Java. Internetprogrammers can call on the functions through the suppliedlibraries and be able to access files on the Internet as easily aswriting to a local file system. Java is secure

    The Java language has built-in capabilities to ensure thatviolations 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 withbetween compilation and runtime. Java guards against this byusing the bytecode verifier to check the bytecode for languagecompliance when the code first enters the interpreter, before

    it ever even gets the chance to run.

  • 7/28/2019 Java Programming Lect1

    8/92

    Java is portableBy porting an interpreter for the Java Virtual Machineto any computer hardware/operating system, one isassured that all code compiled for it will run on thatsystem. This forms the basis for Java's portability.

    Another feature which Java employs in order toguarantee portability is by creating a single standardfor data sizes irrespective of processor or operatingsystem platforms. Java is high-performance

    The Java language supports many high-performancefeatures such as multithreading, just-in-timecompiling, and native code usage.

  • 7/28/2019 Java Programming Lect1

    9/92

    The programmer writes Java source code in a texteditor which supports plain text. Normally theprogrammer uses an Integrated DevelopmentEnvironment (IDE) for programming. An IDE supports

    the programmer in the task of writing code, e.g. itprovides 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 thebytecode instructions. . These instructions are storedin .class files and can be executed by the Java VirtualMachine.

  • 7/28/2019 Java Programming Lect1

    10/92

    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 Javaprogram, the resulting Java bytecodes are stored

    in a file with the same name and the extension.class.

  • 7/28/2019 Java Programming Lect1

    11/92

  • 7/28/2019 Java Programming Lect1

    12/92

    Java programming OOP

  • 7/28/2019 Java Programming Lect1

    13/92

    ClassA unit of code that is the basic building block of Javaprograms. OrA class is a blueprint or prototype from whichobjects are created.

    The basic form of a Java class is as follows:public class {

    ...}

  • 7/28/2019 Java Programming Lect1

    14/92

    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 inmethods where the logics are written, data is manipulated and all theactions are executed.

    OrMethods are functions defined inside classes that operate on instances ofthose 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."); }}

  • 7/28/2019 Java Programming Lect1

    15/92

    ObjectAn object is an instance of a class.

    Objects have states and behaviors.

    An object's state is created by the values assignedto these instant variables.

  • 7/28/2019 Java Programming Lect1

    16/92

    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 bein 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 firstletter 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 donot 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..

  • 7/28/2019 Java Programming Lect1

    17/92

    A name given to an entity in a program, such as a class or method.OrNames used for classes, variables and methods are calledidentifiers.

    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_valueo Examples of illegal identifiers : 123abc, -salary

  • 7/28/2019 Java Programming Lect1

    18/92

    A sample of a class is given below:

    public class Dog{String breed;int age;

    String color;

    void barking(){}void hungry(){

    }void sleeping(){}}

  • 7/28/2019 Java Programming Lect1

    19/92

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

  • 7/28/2019 Java Programming Lect1

    20/92

    The first line of the class is known as the classheader.

    The word public in the header indicates that thisclass is available to anyone to use.

    Class is enclosed in curly brace characters ({ }).These characters are used in Java to grouptogether related bits of code. In this case, the

    curly braces are indicating that everythingdefined within them is part of this public class.

  • 7/28/2019 Java Programming Lect1

    21/92

    The Main method is the method in which execution to any java programbegins.

    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 beginexecution of the program.

    It is Static because it be available for execution without an objectinstance. you may know that you need an object instance to invoke anymethod. So you cannot begin execution of a class without its object if themain 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 theMain method

    The last parameter is String args[]. This is used to signify that the usermay opt to enter parameters to the java program at command line. We canuse both String[] args or String args[]. The Java compiler would acceptboth forms.

  • 7/28/2019 Java Programming Lect1

    22/92

    One of the simplest and most common statements isSystem.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 thefollowing line of output:

    This line uses the println method.

  • 7/28/2019 Java Programming Lect1

    23/92

    Modifiers are keywords that you add to those definitionsto change their meanings. The Java language has a widevariety of modifiers, including the following

    The access to classes, constructors, methods and fieldsare regulated using access modifiers i.e. a class can control

    what information or data can be accessible by otherclasses.

    Package?

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

    Modifier Used on Meaning

  • 7/28/2019 Java Programming Lect1

    24/92

    Modifier Used on Meaning

    protected member Accessible only within its package and its subclasses

    public class

    interface

    member

    Accessible anywhere

    Accessible anywhere

    Accessible anywhere its class is.

    none(package) class

    member

    Accessible only in its package

    Accessible only in its package

    private member Accessible only in its class(which defines it).

    final class

    method

    variable

    Cannot be subclassed

    Cannot be overridden and dynamically looked up

    Cannot change its value

  • 7/28/2019 Java Programming Lect1

    25/92

    Java provides a number of access modifiers to setaccess levels for classes, variables, methods andconstructors. 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 implementationsof classes, methods, and variables. The abstract modifier for creating abstract classes

    and methods.

  • 7/28/2019 Java Programming Lect1

    26/92

    A class can contain any of the following variable types. Local variables . variables defined inside methods,

    constructors or blocks are called local variables. Thevariable will be declared and initialized within themethod 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 variablesare instantiated when the class is loaded. Instancevariables 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 thestatic keyword.

  • 7/28/2019 Java Programming Lect1

    27/92

    Instance Variables (Non-Static Fields) Technically

    speaking, objects store their individual states in "non-static fields", that is, fields declared without thestatic keyword. Non-static fields are also known asinstance variables because their values are unique toeach instance of a class (to each object, in otherwords);

    Class Variables (Static Fields) A class variable is anyfield declared with the static modifier; this tells thecompiler that there is exactly one copy of this

    variable in existence, regardless of how many timesthe class has been instantiated.When a number of objects are created from the sameclass, each instance has its own copy of class variables.

  • 7/28/2019 Java Programming Lect1

    28/92

    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);

    }}

  • 7/28/2019 Java Programming Lect1

    29/92

    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);}}

  • 7/28/2019 Java Programming Lect1

    30/92

  • 7/28/2019 Java Programming Lect1

    31/92

    Variables are nothing but reserved memorylocations to store values. This means that when

    you create a variable you reserve some space inmemory.

    Based on the data type of a variable, theoperating system allocates memory and decideswhat can be stored in the reserved memory.

    There are two data types available in Java:a. Primitive Data Typesb. Reference/Object Data Types

  • 7/28/2019 Java Programming Lect1

    32/92

    Primitive Data Types:There are eight primitive data types supported by Java.Primitive data types are predefined by the language andnamed by a key word. Let us now look into detail about theeight 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 thanan int.

    Example : byte a = 100 , byte b = -50

  • 7/28/2019 Java Programming Lect1

    33/92

    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 = -20000int: 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

  • 7/28/2019 Java Programming Lect1

    34/92

    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 = -200000Lfloat: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

  • 7/28/2019 Java Programming Lect1

    35/92

    double:o

    double data type is a double-precision 64-bit IEEE 754floating 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.4boolean: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

  • 7/28/2019 Java Programming Lect1

    36/92

    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 Data Types:Reference variables are created using defined constructors of the classes.They are used to access objects. These variables are declared to be of aspecific 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")

  • 7/28/2019 Java Programming Lect1

    37/92

  • 7/28/2019 Java Programming Lect1

    38/92

    Java provides a rich set of operators to manipulatevariables. We can divide all the Java operators intothe following groups:

    Arithmetic Operators

    Relational Operators

    Bitwise Operators

    Logical Operators Assignment Operators

  • 7/28/2019 Java Programming Lect1

    39/92

  • 7/28/2019 Java Programming Lect1

    40/92

    There are following relational operators supported by Java

    languageOperator

    Description Example

    ==Checks if the value of two operands are equal or not, ifyes then condition becomes true.

    (A == B) is nottrue.

    != Checks if the value of two operands are equal or not, ifvalues are not equal then condition becomes true.

    (A != B) is true.

    >Checks if the value of left operand is greater than thevalue of right operand, if yes then condition becomestrue.

    (A > B) is nottrue.

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

    (A < B) is true.

    >=Checks if the value of left operand is greater than orequal to the value of right operand, if yes then conditionbecomes true.

    (A >= B) is nottrue.

  • 7/28/2019 Java Programming Lect1

    41/92

    Operator Description Example

  • 7/28/2019 Java Programming Lect1

    42/92

    Operator Description Example

    &Binary AND Operator copies a bit to theresult if it exists in both operands.

    (A & B) will give 12 whichis 0000 1100

    |Binary OR Operator copies a bit if it exists

    in eather operand.

    (A | B) will give 61 which is

    0011 1101

    ^Binary XOR Operator copies the bit if it isset in one operand but not both.

    (A ^ B) will give 49 whichis 0011 0001

    ~Binary Ones Complement Operator is unaryand has the efect of 'flipping' bits.

    (~A ) will give -60 which is1100 0011

    Binary Right Shift Operator. The leftoperands value is moved right by the

    number of bits specified by the rightoperand.

    A >> 2 will give 15 which is

    1111

    >>>

    Shift right zero fill operator. The leftoperands value is moved right by thenumber of bits specified by the right

    operand and shifted values are filled upwith zeros.

    A >>>2 will give 15 which is0000 1111

  • 7/28/2019 Java Programming Lect1

    43/92

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

    holds false then:

    Operator Description Example

    &&Called Logical AND operator. If both theoperands are non zero then then conditionbecomes true.

    (A && B) is false.

    ||Called Logical OR Operator. If any of the twooperands are non zero then then conditionbecomes true.

    (A || B) is true.

    !

    Called Logical NOT Operator. Use to reversesthe logical state of its operand. If a conditionis true then Logical NOT operator will make

    false.

    !(A && B) is true.

  • 7/28/2019 Java Programming Lect1

    44/92

    There are following assignment operators supported by Javalanguage:

    Operator Description Example

    =Simple assignment operator, Assigns values fromright side operands to left side operand

    C = A + B willassigne value of A +B into C

    += Add AND assignment operator, It adds rightoperand to the left operand and assign the resultto left operand

    C += A is equivalentto C = C + A

    -=Subtract AND assignment operator, It subtractsright operand from the left operand and assignthe result to left operand

    C -= A is equivalentto C = C - A

    *=Multiply AND assignment operator, It multipliesright operand with the left operand and assignthe result to left operand

    C *= A is equivalentto C = C * A

    /=Divide AND assignment operator, It divides leftoperand with the right operand and assign the

    result to left operand

    C /= A is equivalent

    to C = C / A

  • 7/28/2019 Java Programming Lect1

    45/92

    Conditional operator is also known as the ternary operator. Thisoperator consists of three operands and is used to evaluate booleanexpressions. The goal of the operator is to decide which valueshould 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 ); }}

  • 7/28/2019 Java Programming Lect1

    46/92

  • 7/28/2019 Java Programming Lect1

    47/92

    There are two types of decision making statements in Java. Theyare:o if statementso switch statementsThe if Statement:

    An if statement consists of a Boolean expression followed by one ormore 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 codeinside the if statement will be executed. If not the first set ofcode after the end of the if statement(after the closing curlybrace) will be executed.

  • 7/28/2019 Java Programming Lect1

    48/92

  • 7/28/2019 Java Programming Lect1

    49/92

  • 7/28/2019 Java Programming Lect1

    50/92

    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");} } }

  • 7/28/2019 Java Programming Lect1

    51/92

  • 7/28/2019 Java Programming Lect1

    52/92

  • 7/28/2019 Java Programming Lect1

    53/92

    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); } }

  • 7/28/2019 Java Programming Lect1

    54/92

  • 7/28/2019 Java Programming Lect1

    55/92

  • 7/28/2019 Java Programming Lect1

    56/92

  • 7/28/2019 Java Programming Lect1

    57/92

    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); } }

  • 7/28/2019 Java Programming Lect1

    58/92

  • 7/28/2019 Java Programming Lect1

    59/92

  • 7/28/2019 Java Programming Lect1

    60/92

  • 7/28/2019 Java Programming Lect1

    61/92

  • 7/28/2019 Java Programming Lect1

    62/92

  • 7/28/2019 Java Programming Lect1

    63/92

  • 7/28/2019 Java Programming Lect1

    64/92

  • 7/28/2019 Java Programming Lect1

    65/92

    The for statement provides a compact way to iterate over a range ofvalues. Programmers often refer to it as the "for loop" because of theway 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 allowsyou to declare and initialize any loop control variables. You are notrequired to put a statement here, as long as a semicolon appears.

    Next, the Boolean expression is evaluated. If it is true, the body of theloop is executed. If it is false, the body of the loop does not executeand 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 anyloop control variables. This statement can be left blank, as long as asemicolon appears after the Boolean expression.

    The Boolean expression is now evaluated again. If it is true, the loopexecutes and the process repeats itself (body of loop, then updatestep,then Boolean expression). After the Boolean expression is false,the for loop terminates.

  • 7/28/2019 Java Programming Lect1

    66/92

    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");

    } } }

  • 7/28/2019 Java Programming Lect1

    67/92

    The break Keyword: The break keyword is used to stop the entire

    loop. The break keyword must be used inside anyloop or a switch statement

    The break keyword will stop the execution of theinnermost loop and start executing the next lineof code after the block.

  • 7/28/2019 Java Programming Lect1

    68/92

    public class tears {public static void main(String []args){

    for(int x =0; x

  • 7/28/2019 Java Programming Lect1

    69/92

  • 7/28/2019 Java Programming Lect1

    70/92

  • 7/28/2019 Java Programming Lect1

    71/92

  • 7/28/2019 Java Programming Lect1

    72/92

    Java has a variation of the println command calledprint that allows you to produce output on thecurrent line without going to a new line of output.The println command really does two different

    things: It sends output to the current line, andthen it moves to the beginning of a new line.

  • 7/28/2019 Java Programming Lect1

    73/92

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

    class or method.

    Java has a set of predefined identifiers calledkeywords that are reserved for particular uses.

  • 7/28/2019 Java Programming Lect1

    74/92

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

    There are two comment forms in Java. In the first form, you open thecomment with a slash followed by an asterisk and you close it with anasterisk followed by a slash:

    /* like this */You can put almost any text you like, including multiple lines, inside thecomment:

    Java also provides a second comment form for shorter, single-linecomments. You can use two slashes in a row to indicate that the rest ofthe current line (everything to the right of the two slashes) is acomment. For example, you can put a comment after a statement:

    System.out.println("You win!"); // Good job!

  • 7/28/2019 Java Programming Lect1

    75/92

    The array, which stores a fixed-size sequential

    collection of elements of the same type. An arrayis used to store a collection of data, but it isoften more useful to think of an array as acollection 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 mustspecify 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.

  • 7/28/2019 Java Programming Lect1

    76/92

  • 7/28/2019 Java Programming Lect1

    77/92

    Note: The style dataType[] arrayRefVar is preferred. The styledataType 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 typelike byte, int, String or double. Only variables of the appropriatetype can be stored in an array. You cannot have an array that willstore 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 [] toindicate that this variable is an array. Here are some examples:

    int[] k;float[] yt;String[] names;

  • 7/28/2019 Java Programming Lect1

    78/92

    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. Whenwe create an array we need to tell the compiler howmany elements will be stored in it. Here's how we'd

    create the variables declared above: new k = newint[3];

    yt = new float[7];names = new String[50];

    The numbers in the brackets specify the dimensionof the array; i.e. how many slots it has to holdvalues. With the dimensions above k can hold threeints, yt can hold seven floats and names can hold

    fifty Strings.

  • 7/28/2019 Java Programming Lect1

    79/92

  • 7/28/2019 Java Programming Lect1

    80/92

    public class arr {public static void main(String []args){

    int []g;

    g=new int[21];for(int i=0;i

  • 7/28/2019 Java Programming Lect1

    81/92

    We can declare and allocate an array at the same timelike 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 valuesinside brackets like so:

    int[] k = {1, 2, 3};

    float[] yt = {0.0f, 1.2f, 3.4f, -9.87f, 65.4f, 0.0f,567.9f};

  • 7/28/2019 Java Programming Lect1

    82/92

  • 7/28/2019 Java Programming Lect1

    83/92

    public class Sum{

    public static void main(String[] args){

    int[] x = new int [101];for (int i = 0; i

  • 7/28/2019 Java Programming Lect1

    84/92

    It means to copy data from one array to another. The precise way tocopy 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 arraycopymethod for copying arrays.Theparameters being used are :-

    src the source arraysrcIndex start position (first cell to copy) in the source arraydest the destination arraydestIndex start position in the destination arraylength the number of array elements to be copied

    The following program, ArrayCopyDemo(in a .java source file), usesarraycopyto copy some elements from the copyFrom array to thecopyTo array.

  • 7/28/2019 Java Programming Lect1

    85/92

    public classArrayCopyDemo{

    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(newString (copyTo));}}

  • 7/28/2019 Java Programming Lect1

    86/92

    To store data in more dimensions a multi-dimensional array is used. A multi-dimensionalarray 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];

  • 7/28/2019 Java Programming Lect1

    87/92

  • 7/28/2019 Java Programming Lect1

    88/92

    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

  • 7/28/2019 Java Programming Lect1

    89/92

    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]);

    }}

  • 7/28/2019 Java Programming Lect1

    90/92

    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);

    }

  • 7/28/2019 Java Programming Lect1

    91/92

    writing a programme to print out all the values fromthe spreadsheet. Your Output window should looksomething like this when you're done

  • 7/28/2019 Java Programming Lect1

    92/92

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

    } }}