complete java basics

Upload: manoj-simha

Post on 07-Apr-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/4/2019 Complete Java Basics

    1/42

    http://www.hudatutorials.com

    1

    JAVAWhat is a Language?A Language is a communication media between two persons or two things.

    What is a Program?A Program is a set of operations grouped in a single file.

    What is Java?Java is a programming language and computing platform first released by SunMicrosystems in 1995.

    Is Java free to download?Yes, Java is free to download. Get the latest version at http://java.com.

    JAVA Basics

    Java is a simple, portable, distributed, robust, secure, dynamic, architecture neutral,object oriented programming language. And its syntax is like C/C++ Language syntax.It is divided into three categories.

    1. Java Standard Edition (JSE)2. Java Enterprise Edition (JEE)3. Java Mobile Edition (JME)

    Java Standard Edition (JSE)It is used to create Standalone Applications as well as Graphical User Interface (GUI)Applications.

    Java Enterprise Edition (JEE)It is used to create Web Applications as well as Enterprise Applications.

    Java Mobile Edition (JME)It is used to create Mobile Applications.

    JAVA Data Types

    DataType

    Range Memory(in bytes)

    DefaultValue

    boolean true or false 1 bit false

    byte -128 to 127 1 0

    char any character or 0 to 65535 2 '\u0000'short -32768 to 32767 2 0

    int -2147483648 to 2147483647 4 0

    float 1.40129846432481707e-45 to 3.40282346638528860e+38 4 0.0f

    long -9223372036854775808 to 9223372036854775807 8 0L

    double 4.94065645841246544e-324d to 1.79769313486231570e+308d 8 0.0d

    JAVA Keywords

    These are reserved words. So you cannot use as identifiers.

    The keywords const and goto are reserved, even though they are not currently used.

    Java compiler produce error messages if these are appear in programs.

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    2/42

    http://www.hudatutorials.com

    2

    abstract continue for new switch

    assert default goto package synchronized

    boolean do if private this

    break double implements protected throw

    byte else import public throws

    case enum instanceof return transient

    catch extends int short try

    char final interface static void

    class finally long strictfp volatile

    const float native super while

    Operators in JAVA

    Type Operator

    Arithmetic +, -, *, /, %

    Assignment =Arithmetic Assignment +=, -=, *=, /=

    Logical !, ||, &&

    Relational ==, !=, >, =, >>

    Separator ,

    Conditional (Ternary) ?:

    JAVA Control Flow StatementsIt is sometimes necessary to perform repeated actions or skip some statements in aprogram. For these actions certain control statements are available. These statements

    control the flow of execution of the programs.

    Decision Making Statementsifif elseswitch

    Looping or Iteration Statementsforwhiledo while

    Branching Statementsbreakcontinuereturn

    Commenting // Single Line Comment /* */ Multi Line Comment/** */ Documentation Comment

    Software Requirements for Creating Java Programs

    Any one of the followingNotepad or any Text EditorNetBeans IDE

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    3/42

    http://www.hudatutorials.com

    3

    Eclips IDE

    Software Requirements to Run JavaJava Development Kit (JDK) for CompilationJava Runtime Environment (JRE) for Running Java Programs

    Your First JAVA Programpublic class MyFirstJavaProgram{

    public static void main(String args[]){

    System.out.println("WELCOME to HudaTutorials.com");}

    }

    Before going to execute the above program, we have to know the rules of JAVAprogram.Rule 1: JAVA Program name should be the class name. MyFirstJavaProgram in the caseof above program with .java extension.

    So you should type the above program in Notepad of windows OS. And save the filewith MyFirstJavaProgram.java in the location C:\HudaTutorials.com\

    Before running the above program you should know how to run dos prompt and somebasic commands. Go to start menu Programs Accessories click onCommand PromptYou will get the DOS command prompt window. Type MD C:\HudaTutorials.com atthe command prompt then press enter.After type CD C:\HudaTutorials.com press again enter. Your prompt changes toC:\HudaTutorials.com> here we knowing the MD command which is creates a

    directory and another command is CD it is changing the current directory.

    Type java version at your command prompt and then press enter, it shows which JAVAversion is installed on your computer. The recommended JAVA Version is 1.6.0.14 it iscalled as JAVA 6 Version.

    Then type javac at your command prompt and then press enter. It shows some textthat means your environmental variables are working fine.

    If you want to run your first JAVA program, you should follow following steps.

    1. Compile the JAVA program.2. Run the JAVA program.

    CompilationType javac MyFirstJavaProgram.java then press enter. It does not show any messagethat means your JAVA program compiled successfully. If any text showing except yourcommand prompt there are some errors in your program. Check the program thencorrect the errors then compile again.

    After successful compilation the javac compiler creates MyFirstJavaProgram.class file inc:\HudaTutorials.com. To check if class file is created type DIR then press enter at yourdos prompt.

    Running

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    4/42

    http://www.hudatutorials.com

    4

    Type java MyFirstJavaProgram then press enter. It shows the message WELCOME toHudaTutorials.com. You are successfully compiled and ran the program.

    Explanation for MyFirstJavaProgram.javaLike C programs JAVA program execution starts from public static void main(Stringargs[]) method. The System.out.println("WELCOME to HudaTutorials.com"); print themessage WELCOME to HudaTutorials.com on the screen.

    JAVA Data Types

    boolean Data Type

    /* boolean Data Type Example *//* Save with file name BooleanDataType.java */

    public class BooleanDataType{

    public static void main(String args[]){boolean b; //TYPE DECLARATION DEFAULT VALUE OF boolean IS falseSystem.out.println();System.out.println("boolean Example");System.out.println("===============");System.out.println();b = true; //ASSIGN A VALUESystem.out.println("Assigned boolean Value : " + b);

    }}

    byte Data Type

    /* byte Data Type Example *//* Save with file name ByteDataType.java */

    public class ByteDataType{

    public static void main(String args[]){

    byte b; //TYPE DECLARATION DEFAULT VALUE OF byte IS 0System.out.println();System.out.println("byte Example");System.out.println("============");System.out.println();b = 77; //ASSIGN A VALUESystem.out.println("Assigned byte Value : " + b);

    }}

    char Data Type

    /* char Data Type Example *//* Save with file name CharDataType.java */

    public class CharDataType{

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    5/42

    http://www.hudatutorials.com

    5

    public static void main(String args[]){

    char c; //TYPE DECLARATION DEFAULT VALUE OF char IS '\u0000'System.out.println();System.out.println("char Example");System.out.println("============");

    System.out.println();c = 'A'; //ASSIGN A VALUESystem.out.println("Assigned char Value : " + c);c = 97; //ASSIGN small a ascii valueSystem.out.println("Assigned char ASCII Value : " + c);

    }}

    short Data Type

    /* short Data Type Example *//* Save with file name ShortDataType.java */

    public class ShortDataType{

    public static void main(String args[]){

    short s; //TYPE DECLARATION DEFAULT VALUE OF short IS 0System.out.println();System.out.println("short Example");System.out.println("=============");System.out.println();s = 123; //ASSIGN A VALUESystem.out.println("Assigned short Value : " + s);

    }}

    int Data Type

    /* int Data Type Example *//* Save with file name IntDataType.java */

    public class IntDataType{

    public static void main(String args[]){

    int i; //TYPE DECLARATION DEFAULT VALUE OF int IS 0System.out.println();System.out.println("int Example");System.out.println("=============");System.out.println();i = 5; //ASSIGN A VALUESystem.out.println("Assigned int Value : " + i);

    }}

    float Data Type

    /* float Data Type Example *//* Save with file name FloatDataType.java */

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    6/42

    http://www.hudatutorials.com

    6

    public class FloatDataType{

    public static void main(String args[]){

    float a; //TYPE DECLARATION DEFAULT VALUE OF float IS 0f

    System.out.println();System.out.println("float Example");System.out.println("=============");System.out.println();/* ASSIGN A VALUE LIKE THIS COMPILER SHOW ERROR *//* POSSIBLE LOSS OF PRECISION FOUND DOUBLE REQUIRED FLOAT *//*a = 5.25; //GET ERROR COMPILER ASSUMES double */

    a = 5.25f; //ASSIGN A float VALUESystem.out.println("Assigned float Value : " + a);

    }}

    long Data Type

    /* long Data Type Example *//* Save with file name LongDataType.java */

    public class LongDataType{

    public static void main(String args[]){

    long a; //TYPE DECLARATION DEFAULT VALUE OF long IS 0LSystem.out.println();

    System.out.println("long Example");System.out.println("=============");System.out.println();a = 45000L; //ASSIGN A VALUESystem.out.println("Assigned long Value : " + a);

    }}

    double Data Type

    /* double Data Type Example *//* Save with file name DoubleDataType.java */

    public class DoubleDataType{

    public static void main(String args[]){

    double a; //TYPE DECLARATION DEFAULT VALUE OF double IS 0dSystem.out.println();System.out.println("double Example");System.out.println("==============");System.out.println();a = 5.25d; //ASSIGN A double VALUESystem.out.println("Assigned double Value : " + a);

    }}

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    7/42

    http://www.hudatutorials.com

    7

    JAVA Keywords Definitions

    abstractA Java keyword used in a class definition to specify that a class is not to be instantiated,but rather inherited by other classes. An abstract class can have abstract methods that

    are not implemented in the abstract class, but in subclasses.

    abstract classA class that contains one or more abstract methods, and therefore can never beinstantiated. Abstract classes are defined so that other classes can extend them andmake them concrete by implementing the abstract methods.

    abstract methodA method that has no implementation.

    assertAn assertion is a statement in the JAVA programming language that enables you to test

    your assumptions about your program.

    booleanRefers to an expression or variable that can have only a true or false value. The Javaprogramming language provides the boolean type and the literal values true and false.

    breakA Java keyword used to resume program execution at the statement immediatelyfollowing the current statement. If followed by a label, the program resumes executionat the labeled statement.

    byteA sequence of eight bits. Java provides a corresponding byte type.

    caseA Java keyword that defines a group of statements to begin executing if a value specifiedmatches the value defined by a preceding switch keyword.

    catchA Java keyword used to declare a block of statements to be executed in the event that aJava exception, or run time error, occurs in a preceding try block.

    char

    A Java keyword used to declare a variable of type character.

    classIn the Java programming language, a type that defines the implementation of aparticular kind of object. A class definition defines instance and class variables andmethods, as well as specifying the interfaces the class implements and the immediatesuperclass of the class. If the superclass is not explicitly specified, the superclass willimplicitly be Object.

    class methodA method that is invoked without reference to a particular object. Class methods affectthe class as a whole, not a particular instance of the class. Also called a static method.

    class variable

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    8/42

    http://www.hudatutorials.com

    8

    A data item associated with a particular class as a whole--not with particular instances ofthe class. Class variables are defined in class definitions. Also called a static field.

    ClasspathAn environmental variable which tells the Java Virtual Machine and Java technology-based applications where to find the class libraries, including user-defined class libraries.

    constA reserved Java keyword not used by current versions of the Java programminglanguage.

    continueA Java keyword used to resume program execution at the end of the current loop. Iffollowed by a label, continue resumes execution where the label occurs.

    defaultA Java keyword optionally used after all case conditions in a switch statement. If all case

    conditions are not matched by the value of the switch variable, the default keyword willbe executed.

    doA Java keyword used to declare a loop that will iterate a block of statements. The loop'sexit condition can be specified with the while keyword.

    doubleA Java keyword used to define a variable of type double.

    double precisionIn the Java programming language specification, describes a floating point number that

    holds 64 bits of data.

    elseA Java keyword used to execute a block of statements in the case that the test conditionwith the if keyword evaluates to false.

    enumA Java keyword used to declare an enumerated type.

    extendsextends is a JAVA keyword used to inherit the properties and methods of another class.

    class X extends class Y to add functionality, either by adding fields or methods to class Y,or by overriding methods of class Y. An interface extends another interface by addingmethods. Class X is said to be a subclass of class Y.

    finalIf you declare class, method or field those are not modifiable at any point afterdeclaration. A final class cannot be subclassed, a final method cannot be overridden anda final variable cannot change from its initialized value.

    finallyA Java keyword that executes a block of statements regardless of whether a JavaException, or run time error, occurred in a block defined previously by the try keyword.

    float

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    9/42

    http://www.hudatutorials.com

    9

    A Java keyword used to define a floating point number variable.

    forA Java keyword used to declare a loop that reiterates statements. The programmer canspecify the statements to be executed, exit conditions, and initialization variables for theloop.

    gotoIt is not used by current versions of the Java programming language.

    ifA Java keyword used to conduct a conditional test and execute a block of statements ifthe test evaluates to true.

    implementsA Java keyword included in the class declaration to specify any interfaces that areimplemented by the current class.

    importA Java keyword used at the beginning of a source file that can specify classes or entirepackages to be referred to later without including their package names in the reference.

    instanceofA two-argument Java keyword that tests whether the runtime type of its first argumentis assignment compatible with its second argument.

    intA Java keyword used to define a variable of type integer.

    interfaceA Java keyword used to define a collection of method definitions and constant values. Itcan later be implemented by classes that define this interface with the "implements"keyword.

    longA Java keyword used to define a variable of type long.

    nativeA Java keyword that is used in method declarations to specify that the method is notimplemented in the same Java source file, but rather in another language.

    newA Java keyword used to create an instance of a class.

    packageA group of types. Packages are declared with the package keyword.

    privateA Java keyword used in a method or variable declaration. It signifies that the method orvariable can only be accessed by other elements of its class.

    protected

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    10/42

    http://www.hudatutorials.com

    10

    A Java keyword used in a method or variable declaration. It signifies that the method orvariable can only be accessed by elements residing in its class, subclasses, or classes inthe same package.

    publicA Java keyword used in a class, method or variable declaration. It signifies that themethod or variable can be accessed by elements residing in other classes.

    returnA Java keyword used to finish the execution of a method. It can be followed by a valuerequired by the method definition.

    shortA Java keyword used to define a variable of type short.

    staticA Java keyword used to define a variable as a class variable. Classes maintain one copy

    of class variables regardless of how many instances exist of that class. static can also beused to define a method as a class method. Class methods are invoked by the classinstead of a specific instance, and can only operate on class variables.

    strictfpstrictfp is a Java keyword used to restrict floating-point calculations to ensure portability.The modifier was introduced into the Java programming language with the Java virtualmachine version 1.2.

    Basically, what it all boils down to is whether or not you care that the results of floating-point expressions in your code are fast or predictable. For example, if you need theanswers that your code comes up with which uses floating-point values to be consistent

    across multiple platforms then use strictfp.

    What Does "strictfp" Do?, When this modifier is specified, the JVM sticks to the Javaspecifications and returns the consistent value independent of the platform. That is, ifyou want the answers from your code (which uses floating point values) to be consistentin all platforms, then you need to specify the strictfp modifier.Java's default class Math uses this strictfp modifier as shown belowpublic final strictfp class Math{ }

    superA Java keyword used to access members of a class inherited by the class in which itappears.

    switchA Java keyword used to evaluate a variable that can later be matched with a valuespecified by the case keyword in order to execute a group of statements.

    synchronizedIf synchronized keyword applied to a method or code block, guarantees that at most onethread at a time executes that code.

    thisIt is used to represent an instance of the class in which it appears. this can be used toaccess class variables and methods.

    throw

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    11/42

    http://www.hudatutorials.com

    11

    It is used to throw an exception or any class that implements the "throwable" interface.

    throwsIt is used in method declarations that specify which exceptions are not handled withinthe method but rather passed to the next higher level of the program.

    transientIt indicates that a field is not part of the serialized form of an object. When an object isserialized, the values of its transient fields are not included in the serial representation,while the values of its non-transient fields are included.

    tryA Java keyword that defines a block of statements that may throw a Java languageexception. If an exception is thrown, an optional catch block can handle specificexceptions thrown within the try block. Also, an optional finally block will be executedregardless of whether an exception is thrown or not.

    voidIt is used in method declarations to specify that the method does not return any value.void can also be used as a nonfunctional statement.

    volatileIt is used in variable declarations that specifies that the variable is modifiedasynchronously by concurrently running threads.

    whileA Java keyword used to declare a loop that iterates a block of statements. The loop's exitcondition is specified as part of the while statement.

    JAVA OperatorsThese are used to manipulate primitive data types. Java operators can be classified asUnary, Binary and Ternary i.e. taking one, two or three arguments. A Unary operatormay appear before its argument or after its argument. A Binary or Ternary operatorappears between its arguments.

    Arithmetic Operators1) + for Addition (Add two numbers) or Concatenation (Add two strings)2) - for Subtraction3) * for Multiplication4)/ for Division5) % for modulo Division (Remainder)

    /* Arithmetic Operators Example *//* Save with file name ArithmeticOperators.java */

    public class ArithmeticOperators{

    public static void main(String args[]){

    System.out.println();System.out.println("Arithmetic Operators Example");System.out.println("============================");System.out.println();

    System.out.println("Assignment (20+10) = " + (20+10)); //AssignmentsSystem.out.println("Subtraction (20-10) = " + (20-10)); //Subtraction

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    12/42

    http://www.hudatutorials.com

    12

    System.out.println("Multiplication (20X10) = " + (20*10)); //MultiplicationSystem.out.println("Division (20/10) = " + (20/10)); //DisivionSystem.out.println("Modulo Division (20%12) = " + (20%12)); //Modulo

    Division}

    }

    Assignment Operator

    /* Assignment Operator Example *//* Save with file name AssignmentOperator.java */

    public class AssignmentOperator{

    public static void main(String args[]){

    int a; //VARIABLE DECLARATION

    System.out.println();System.out.println("Assignment Operator Example");System.out.println("===========================");System.out.println();a = 10; //ASSIGNMENTSystem.out.println("Value of a After Assignment : " + a); //PRINTS TEN

    }}

    Arithmetic Assignment Operators1) +=2) -=3) *=4)/=

    /* Arithmetic Assignment Operators Example *//* Save with file name ArithmeticAssignmentOperators.java */

    public class ArithmeticAssignmentOperators{

    public static void main(String args[]){

    int a = 1, b = 7; //VARIABLE DECLARATION AND ASSIGN A VALUEa +=10;System.out.println();System.out.println("Arithmetic Assignment Operators Example");

    System.out.println("=======================================");

    System.out.println();System.out.println("Addition : " + a);b -= 2;System.out.println("Subtraction : " + b);float c; //YOU CAN ALSO DECLARE A VARIABLE AT ANY PLACE

    c = 3;c *= 5;System.out.println("Multiplication : " + c);

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    13/42

    http://www.hudatutorials.com

    13

    double d = 20;d /= 10;System.out.println("Division : " + d);

    }}

    Logical OperatorsLogical operators return true or false value only i.e. the result is always a boolean datatype.

    1) && - AND2) || - OR3) ! - NOT

    /* Logical Operators Example *//* Save with file name LogicalOperators.java */

    public class LogicalOperators{

    public static void main(String args[]){

    boolean T = true, F = false; //VARIABLES DECLARATION SAME TYPE WITHCOMMA OPERATOR

    System.out.println();System.out.println("Logical Operators Example");System.out.println("=========================");System.out.println();System.out.println("T AND F : " + (T && F)); //TRUE AND FALSE = FALSESystem.out.println("T OR F : " + (T || F)); //TRUE OR FALSE =

    TRUESystem.out.println("NOT T : " + (!T)); //NOT TRUE = FALSE

    }}

    Relational OperatorsThese are used to compare two values or two objects.

    1) == - EQUAL TO2) != - NOT EQUAL TO3) > - GREATER THAN4) < - LESS THAN5) >= - GREATER THAN OR EQUAL TO6) 2));System.out.println("1 Less Than 2 : " + (1

  • 8/4/2019 Complete Java Basics

    14/42

    http://www.hudatutorials.com

    14

    System.out.println("3 Greater Than or Equal to 2 : " + (3>=2));System.out.println("1 Less Than or Equal to 2 : " + (16) >>>

    /* Bitwise Operators Example *//* Save with file name BitwiseOperators.java */

    public class BitwiseOperators{

    public static void main(String args[])

    { int a = 10, b = 20;System.out.println();

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    15/42

    http://www.hudatutorials.com

    15

    System.out.println("Bitwise Operators Example ");System.out.println("=========================");System.out.println();System.out.println("a & b : " + (a & b));System.out.println("a | b : " + (a | b));System.out.println("a ^ b : " + (a ^ b));

    System.out.println("~a : " + (~a));System.out.println("a > b : " + (a >> b));System.out.println("a >>> b : " + (a >>> b));//There is no unsigned left shift operator

    }}

    Conditional (Ternary) Operator1) ? - Question Mark2) : - colon

    The Conditional operator is ternary i.e. it takes three arguments. The operator evaluatesthe first argument and, if true then evaluates the second argument. If the first argumentevaluates to false, then the third argument is evaluated. The conditional operator is theexpression equivalent of the if-else statement. The conditional expression can be nestedand the conditional operator associates from right to left

    /* Conditional Operator Example *//* Save with file name ConditionalOperator.java */

    public class ConditionalOperator{

    public static void main(String args[])

    {int a = 10, b = 20, c, d;c=d=0; //ASSIGN A VALUE TO c, d VARIABLES AT A TIMESystem.out.println();System.out.println("Conditional (Ternary) Operator Example ");

    System.out.println("======================================");

    System.out.println();c = (a > b ? 100 : b); //c VALUE IS 20d = (a == 10 ? 0 : 15); //d VALUE IS 0System.out.println("Value of c : " + c);

    System.out.println("Value of d : " + d);}}

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    16/42

    http://www.hudatutorials.com

    16

    JAVA Control Flow Statements

    It is sometimes necessary to perform repeated actions or skip some statements in aprogram. For these actions certain control statements are available. These statementscontrol the flow of execution of the programs.

    Decision Making Statementsifif elseswitch

    if Statement

    Syntax :if(){

    Statement1;Statement2;Statementn;

    }/* if Statement Example *//* Save with file name IfStatement.java */

    public class IfStatement{

    public static void main(String args[]){

    int a = 30, b = 40;System.out.println();

    System.out.println("if Statement Example ");System.out.println("====================");System.out.println();

    if(a > b)System.out.println("a is greater than b");

    System.out.println("Greater Value"); //OUT PUT STATEMENT

    if(a < b)System.out.println("a is less than b"); //OUT PUT STATEMENT

    System.out.println("Lesser Value"); //OUT PUT STATEMENTSystem.out.println();

    System.out.println("------- ANOTHER WAY -------");System.out.println();

    /* ANOTHER WAY OF IF STATEMENT *//* IF THE CONDITION HAS MORE THAN ONE STATEMENT *//* THEN YOU SHOULD USE THOSE STATEMENTS WITH IN BRACES */if(a > b){

    System.out.println("a is greater than b");System.out.println("Greater Value");

    }

    if(a < b){System.out.println("a is less than b"); //OUT PUT STATEMENT

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    17/42

    http://www.hudatutorials.com

    17

    System.out.println("Lesser Value"); //OUT PUT STATEMENT}

    }}

    if else Statement

    Syntax :if(){

    Statement1;Statement2;Statementn;

    }else{

    Statement1;

    Statement2;Statementn;

    }/* if else Statement Example *//* Save with file name IfElseStatement.java */

    public class IfElseStatement{

    public static void main(String args[]){

    int a = 30, b = 40;System.out.println();

    System.out.println("if Else Statement Example ");System.out.println("====================");System.out.println();

    if(a > b)System.out.println("a is greater than b");

    elseSystem.out.println("a is less than b"); //OUT PUT STATEMENT

    System.out.println();

    System.out.println("------- ANOTHER WAY -------");System.out.println();

    /* ANOTHER WAY OF IF STATEMENT *//* IF THE CONDITION HAS MORE THAN ONE STATEMENT *//* THEN YOU SHOULD USE THOSE STATEMENTS WITH IN BRACES */if(a > b){

    System.out.println("a is greater than b");System.out.println("Greater Value");

    }else{

    System.out.println("a is less than b"); //OUT PUT STATEMENTSystem.out.println("Lesser Value"); //OUT PUT STATEMENT

    }

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    18/42

    http://www.hudatutorials.com

    18

    }}

    switch Statement

    Syntax:

    switch(){

    Case1;Case2;Casen;DefaultCase;

    }

    /* switch Statement Example *//* Save with file name IntSwitchStatement.java */

    public class IntSwitchStatement

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

    int a = 2, b = 40;System.out.println();System.out.println("int Switch Statement Example ");System.out.println("============================");System.out.println();

    /* int value parameter single statement in case */switch(a){

    case 1:System.out.println("a value is One");

    case 2:System.out.println("a value is Two");

    default:System.out.println("a value is Default Value");

    }

    System.out.println("------------------------");/* int value parameter Multiple statements in case */switch(a){

    case 1:{System.out.println("Case 1 executed");System.out.println("a value is One");break;

    }case 2:{

    System.out.println("Case 2 executed");System.out.println("a value is Two");break;

    }default:

    {System.out.println("Default Case executed");

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    19/42

    http://www.hudatutorials.com

    19

    System.out.println("a value is Default Value");break; //NOT REQUIRE BECAUSE LAST STATEMENT

    }}

    }

    }

    /* switch Statement Example *//* Save with file name CharSwitchStatement.java */

    public class CharSwitchStatement{

    public static void main(String args[]){

    char c = 'b'; //char DATA TYPE DECLARATION AND ASSIGN A VALUESystem.out.println();System.out.println("char Switch Statement Example ");

    System.out.println("=============================");System.out.println();

    /* char value parameter single statement in case */switch(c){

    case 'a':System.out.println("case a");

    case 'b':System.out.println("case b");

    case 'c':System.out.println("case c");

    default:System.out.println("default case");

    }

    System.out.println("------------");/* char value parameter Multiple statements in case */switch(c){

    case 'a':{

    System.out.println("Case a");

    break;}case 'b':{

    System.out.println("Case b");break;

    }case 'c':{

    System.out.println("Case c");System.out.println("a value is Two");break;

    }

    default:{

    http://www.hudatutorials.com/http://www.hudatutorials.com/http://www.hudatutorials.com/
  • 8/4/2019 Complete Java Basics

    20/42

    http://www.hudatutorials.com

    20

    System.out.println("Default Case");break; //NOT REQUIRE BECAUSE LAST STATEMENT

    }}

    }

    }

    Looping or Iteration Statementsforwhiledo while

    for loopSyntax :for(;;){

    Statement1;

    Statement2;Statementn;

    }Tips

    If you ignore the braces after loop statement the first statement after loop isexecuted in loop.If you put ; (semi colon) to loop without braces no statement is executed.If you put ; (semi colon) to loop with braces the body of the loop is executedonce.

    /* for loop Example */

    /* Save with file name ForLoop.java */

    public class ForLoop{

    public static void main(String args[]){

    System.out.println();System.out.println("for loop Example ");System.out.println("================");System.out.println();

    for(int count=1 ; count

  • 8/4/2019 Complete Java Basics

    21/42

    http://www.hudatutorials.com

    21

    System.out.println();System.out.println("Loop 3 output");System.out.println();/* LOOP WITH NO BODY */int j=0;for(;j

  • 8/4/2019 Complete Java Basics

    22/42

    http://www.hudatutorials.com

    22

    /* do while loop Example *//* Save with file name DoWhileLoop.java */

    public class DoWhileLoop{

    public static void main(String args[])

    {System.out.println();System.out.println("do while loop Example ");System.out.println("=====================");System.out.println();

    int count = 1;do{

    /* POST INCREMENT */System.out.println("Loop Statement : " + count);count++;

    } while(count

  • 8/4/2019 Complete Java Basics

    23/42

    http://www.hudatutorials.com

    23

    public class ContinueStatement{

    public static void main(String args[]){

    System.out.println();System.out.println("continue Statement Example ");

    System.out.println("==========================");System.out.println();

    int count = 1;while(count

  • 8/4/2019 Complete Java Basics

    24/42

    http://www.hudatutorials.com

    24

    JAVA Arrays

    An array is a collection of variables of the same type. It stores a fixed size sequentialcollection of elements of the same type. An array is used to store a collection of data.

    Arrays are declared with [] (square brackets). If you put [] (square brackets) after anyvariable of any type only that variable is of type array remaining variables in thatdeclaration are not array variables those are normal variables of that type. If you put [](square brackets) after any data type all the variables in that declaration are arrayvariables. All the elements in the array are accessed with index. The array elementindex is starting from 0 to n-1 number i.e. if the array has 5 elements then startingindex is 0 and ending index is 4. In this tutorial you can learn how to declare arrays,how to assign values to arrays and how get values from arrays.

    Syntax: [];[] ; [length of array];

    boolean Array

    It is used to store boolean data type values only. With the following examples you canlearn how to declare boolean array, how to assign values to boolean array and how toget values from boolean array.

    /* boolean Array Example *//* Save with file name BooleanArray.java */

    public class BooleanArray{

    public static void main(String args[]){

    //BOOLEAN ARRAY DECLARATIONboolean b[];//MEMORY ALLOCATION FOR BOOLEAN ARRAYb = new boolean[4];//ASSIGNING ELEMENTS TO BOOLEAN ARRAYb[0] = true;b[1] = false;b[2] = false;b[3] = false;//BOOLEAN ARRAY OUTPUT

    System.out.println();System.out.println("boolean Array Example");System.out.println("=====================");System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    25/42

    http://www.hudatutorials.com

    25

    /* boolean Array Example 2 *//* Save with file name BooleanArray2.java */

    public class BooleanArray2{

    public static void main(String args[])

    {//BOOLEAN ARRAY DECLARATION AND ASSIGNMENTboolean b[] = {false,false,true,true};//BOOLEAN ARRAY OUTPUTSystem.out.println();System.out.println("boolean Array Example");System.out.println("=====================");System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    26/42

  • 8/4/2019 Complete Java Basics

    27/42

    http://www.hudatutorials.com

    27

    //BYTE ARRAY OUTPUTSystem.out.println();System.out.println("byte Array Example");System.out.println("==================");System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    28/42

    http://www.hudatutorials.com

    28

    System.out.println("byte Array Example");System.out.println("==================");System.out.println();System.out.println("a value is : "+a);System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    29/42

    http://www.hudatutorials.com

    29

    /* char Array Example *//* Save with file name CharArray.java */

    public class CharArray{

    public static void main(String args[])

    {//CHAR ARRAY DECLARATIONchar c[];//MEMORY ALLOCATION FOR CHAR ARRAYc = new char[4];//ASSIGNING ELEMENTS TO CHAR ARRAYc[0] = 'a';c[1] = 'c';c[2] = 'D';c[3] = 'B';//CHAR ARRAY OUTPUTSystem.out.println();

    System.out.println("char Array Example");System.out.println("==================");System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    30/42

    http://www.hudatutorials.com

    30

    public class CharArray3{

    public static void main(String args[]){

    //CHAR ARRAY DECLARATIONchar c[], a;//c IS AN ARRAY a IS NOT AN ARRAY

    //MEMORY ALLOCATION FOR CHAR ARRAYc = new char[4];//ASSIGNING ELEMENTS TO CHAR ARRAYc[0] = 'a';c[1] = 'c';c[2] = 'D';c[3] = 'B';a = 'X';//CHAR ARRAY OUTPUTSystem.out.println();System.out.println("char Array Example");System.out.println("==================");

    System.out.println();System.out.println("a value is : "+a);System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    31/42

    http://www.hudatutorials.com

    31

    }System.out.println();System.out.println("a array values");for(int i=0;i

  • 8/4/2019 Complete Java Basics

    32/42

    http://www.hudatutorials.com

    32

    System.out.println();System.out.println("short Array Example");System.out.println("==================");System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    33/42

    http://www.hudatutorials.com

    33

    //ASSIGNING ELEMENTS TO SHORT ARRAYs[0] = 10;s[1] = 30;s[2] = 40;s[3] = 7;//ASSIGNING s ARRAY TO s2 ARRAY VARIABLE

    s2 = s;//SHORT ARRAY OUTPUTSystem.out.println();System.out.println("short Array Example");System.out.println("==================");System.out.println();System.out.println("s array values");for(int i=0;i

  • 8/4/2019 Complete Java Basics

    34/42

    http://www.hudatutorials.com

    34

    }}

    }

    In this example you can learn how to assign values to int array at the time ofdeclaration.

    /* int Array Example 2 *//* Save with file name IntArray2.java */

    public class IntArray2{

    public static void main(String args[]){

    //INT ARRAY DECLARATIONint n[] = {5,3,4,7};//INT ARRAY OUTPUTSystem.out.println();

    System.out.println("int Array Example");System.out.println("==================");System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    35/42

    http://www.hudatutorials.com

    35

    }}

    }

    In this example you can learn how to assign int array to other int array.

    /* int Array Example 4 *//* Save with file name IntArray4.java */

    public class IntArray4{

    public static void main(String args[]){

    //INT ARRAY DECLARATIONint[] n, n2; //n AND n2 ARE ARRAY VARIABLES//MEMORY ALLOCATION FOR INT ARRAYn = new int[4];//ASSIGNING ELEMENTS TO INT ARRAY

    n[0] = 5;n[1] = 3;n[2] = 4;n[3] = 7;//ASSIGNING n ARRAY TO n2 ARRAY VARIABLEn2 = n;//INT ARRAY OUTPUTSystem.out.println();System.out.println("int Array Example");System.out.println("==================");System.out.println();System.out.println("n array values");

    System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    36/42

    http://www.hudatutorials.com

    36

    {//FLOAT ARRAY DECLARATIONfloat f[];//MEMORY ALLOCATION FOR FLOAT ARRAYf = new float[4];//ASSIGNING ELEMENTS TO FLOAT ARRAY

    f[0] = 10.10f;f[1] = 30.3f;f[2] = 40.60f;f[3] = 77.50f;//FLOAT ARRAY OUTPUTSystem.out.println();System.out.println("float Array Example");System.out.println("==================");System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    37/42

    http://www.hudatutorials.com

    37

    //MEMORY ALLOCATION FOR FLOAT ARRAYf = new float[4];//ASSIGNING ELEMENTS TO FLOAT ARRAYf[0] = 10.10f;f[1] = 30.3f;f[2] = 40.60f;

    f[3] = 77.50f;f2 = 555.55f;//FLOAT ARRAY OUTPUTSystem.out.println();System.out.println("float Array Example");System.out.println("==================");System.out.println();System.out.println("f2 value is : "+f2);System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    38/42

    http://www.hudatutorials.com

    38

    System.out.println("Element at Index : "+ i + " " + f2[i]);}

    }}

    long Array

    It is used to store long data type values only. With the following examples you can learnhow to declare long array, how to assign values to long array and how to get valuesfrom long array.

    /* long Array Example *//* Save with file name LongArray.java */

    public class LongArray{

    public static void main(String args[]){

    //LONG ARRAY DECLARATIONlong a[];//MEMORY ALLOCATION FOR LONG ARRAYa = new long[4];//ASSIGNING ELEMENTS TO LONG ARRAYa[0] = 100000L;a[1] = 300000L;a[2] = 400000L;a[3] = 786777L;//LONG ARRAY OUTPUTSystem.out.println();System.out.println("long Array Example");

    System.out.println("==================");System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    39/42

    http://www.hudatutorials.com

    39

    {System.out.println("Element at Index : "+ i + " " + a[i]);

    }}

    }

    In this example you can learn how to declare long array with other long variables.

    /* long Array Example 3 *//* Save with file name LongArray3.java */

    public class LongArray3{

    public static void main(String args[]){

    //LONG ARRAY DECLARATIONlong a[], a2; //a IS AN ARRAY a2 IS NOT AN ARRAY//MEMORY ALLOCATION FOR LONG ARRAY

    a = new long[4];//ASSIGNING ELEMENTS TO LONG ARRAYa[0] = 100000L;a[1] = 300000L;a[2] = 400000L;a[3] = 786777L;a2 = 222222L;//LONG ARRAY OUTPUTSystem.out.println();System.out.println("long Array Example");System.out.println("==================");System.out.println();

    System.out.println("a2 value is : "+a2);System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    40/42

    http://www.hudatutorials.com

    40

    //ASSIGNING a ARRAY TO a2 ARRAY VARIABLEa2 = a;//LONG ARRAY OUTPUTSystem.out.println();System.out.println("long Array Example");System.out.println("==================");

    System.out.println();System.out.println("a array values");System.out.println();for(int i=0;i

  • 8/4/2019 Complete Java Basics

    41/42

    http://www.hudatutorials.com

    41

    In this example you can learn how to assign values to double array at the time ofdeclaration.

    /* double Array Example 2 *//* Save with file name DoubleArray2.java */

    public class DoubleArray2{

    public static void main(String args[]){

    //DOUBLE ARRAY DECLARATIONdouble a[] = {100000d,300000d,400000d,786777d};//DOUBLE ARRAY OUTPUTSystem.out.println();System.out.println("double Array Example");System.out.println("==================");System.out.println();

    for(int i=0;i

  • 8/4/2019 Complete Java Basics

    42/42

    http://www.hudatutorials.com

    In this example you can learn how to assign double array to other double array.

    /* double Array Example 4 *//* Save with file name DoubleArray4.java */

    public class DoubleArray4{

    public static void main(String args[]){

    //DOUBLE ARRAY DECLARATIONdouble[] a, a2; //a AND a2 ARE ARRAY VARIABLES//MEMORY ALLOCATION FOR DOUBLE ARRAYa = new double[4];//ASSIGNING ELEMENTS TO DOUBLE ARRAYa[0] = 100000d;a[1] = 300000d;a[2] = 400000d;

    a[3] = 786777d;//ASSIGNING a ARRAY TO a2 ARRAY VARIABLEa2 = a;//DOUBLE ARRAY OUTPUTSystem.out.println();System.out.println("double Array Example");System.out.println("==================");System.out.println();System.out.println("a array values");System.out.println();for(int i=0;i