SlideShare a Scribd company logo
Core Java          - Sharad Ballepu
       sharadballepu@sharmanj.com
                www.sharmanj.com




               1
Core Java      Servlets & JSPs
  Agenda


  • Introduction
  • Access Modifiers
  • Operators
  • Flow Control
  • Arrays and Strings
  • OOPS Explored
  • Exceptions
  • Garbage Collection
  • Collections
  • Threads
  • Demo
                                 2
Introduction – What is Java



 • Programming language
    – Another programming language using which we can develop applets,
        standalone applications, web applications and enterprise applications.

 • Platform Independent
    – A Java program written and compiled on one machine can be
        executed on any other machine (irrespective of the operating system)

 • Object Oriented
    – Complies to object oriented programming concepts. Your program is
        not object oriented unless you code that way

 • Compiled and Interpreted
    – The .java file is compiled to a .class file & the .class file is interpreted
        to machine code


                                                                3
Introduction – Java Virtual Machine




                                Java                .class
              .java file       Compiler               file




                             Java Virtual Machine




            Mac                  Microsoft                   UNIX

                                                        4
Introduction – My First Program Version 1



   package com.sharadballepu.test;

   public class HelloWorld
   {
     public static void main(String[] args)
     {
       System.out.println(“Hello World”);
     }
   }

   Compile the program: javac HelloWorld.java
   Execute the program: java HelloWorld
   Output: Hello World

                                                5
Introduction – My First Program Version 2


   package com.sharadballepu.test;

   public class HelloWorld
   {
     public static void main(String[] args)
     {
       HelloWorld hw = new HelloWorld();
       hw.display();
     }

       public void display()
       {
         System.out.println(“Hello World”);
       }
   }

   Compile the program: javac HelloWorld.java
   Execute the program: java HelloWorld
   Output: Hello World                          6
Introduction – My First Program Version 3


   package com.sharadballepu.test;

   public class HelloWorld
   {
     public static void main(String[] args)
     {
       HelloWorld hw = new HelloWorld();
       hw.display(args[0]);
     }

       public void display(String userName)
       {
         System.out.println(“Hello ” + userName);
       }
   }

   Compile the program: javac HelloWorld.java
   Execute the program: java HelloWorld Sharad
   Output: Hello Sharad                             7
Introduction – My First Program Version 4


   package com.sharadballepu.test;

   public class HelloWorld
   {
     String userName;
     public static void main(String[] args)
     {
       HelloWorld hw = new HelloWorld();
       hw.userName = args[0];
     }

    public void display()
    {
      System.out.println(“Hello ” + userName);
    }
   }
   Compile the program: javac HelloWorld.java
   Execute the program: java HelloWorld Sharad
   Output: Hello Sharad                          8
Introduction – Java Keywords



    abstract    boolean       break        byte         case        catch    char


      class      const      continue      default        do         double    else


     extends      final      finally       float         for         goto      if


   implements    import     instanceof      int       interface      long    native


      new       package      private     protected      public      return   short


     static     strictfp      super       switch     synchronized    this    throw


     throws     transient      try         void        volatile     while    assert




                                                                     9
Introduction – Stack v/s Heap




                                    A              B
          x = 10      y = new A()

               method2()


             method1()
                                        C
                   main()


                   Stack
                                            Heap
                                            10
Introduction - Object Oriented Concepts



   • Class
       – A blueprint that defines the attributes and methods

   • Object
       – An instance of a Class

   • Abstraction
       – Hide certain details and show only essential details

   • Encapsulation
       – Binding data and methods together

   • Inheritance
       – Inherit the features of the superclass

   • Polymorphism
       – One name having many forms
                                                                11
Introduction - Data Types


    Data type         Byt        Min    Max Value    Literal Values
                      es        Value
        byte           1         -27      27 – 1            123

       short           2         -215     215 – 1          1234

         int           4         -231     231 – 1   12345, 086, 0x675

        long           8         -263     263 – 1         123456

       float           4          -          -              1.0

      double           8          -          -            123.86

        char           2          0       216 – 1         ‘a’, ‘n’

     boolean           -          -          -         true, false
    General rule:
    Min value = 2(bits – 1)
    Max value = 2(bits-1) – 1
    (where 1 byte = 8 bits)                          12
Java Modifiers


     Modifier     Class     Class     Methods     Method
                          Variables              Variables
       public                         
      private                          
     protected                         
      default                         
       final                                    
      abstract                         
      strictfp                         
     transient              
   synchronized                         
      native                            
      volatile                             13
       static
Modifiers – Class



    • public
        – Class can be accessed from any other class present in any package

    • default
        – Class can be accessed only from within the same package. Classes outside the
           package in which the class is defined cannot access this class

    • final
        – This class cannot be sub-classed, one cannot extend this class

    • abstract
        – Class cannot be instantiated, need to sub-classs/extend.

    • strictfp
        – Conforms that all methods in the class will conform to IEEE standard rules for
           floating points



                                                                      14
Modifiers – Class Attributes



    • public
        – Attribute can be accessed from any other class present in any package
    • private
        – Attribute can be accessed from only within the class
    • protected
        – Attribute can be accessed from all classes in the same package and sub-classes.
    • default
        – Attribute can be accessed only from within the same package.
    • final
        – This value of the attribute cannot be changed, can assign only 1 value
    • transient
        – The attribute value cannot be serialized
    • volatile
        – Thread always reconciles its own copy of attribute with master.
    • static
        – Only one value of the attribute per class


                                                                    15
Modifiers – Methods


• public
    – Method can be accessed from any other class present in any package
• private
    – Method can be accessed from only within the class
• protected
    – Method can be accessed from all classes in the same package and sub-classes.
• default
    – Method can be accessed only from within the same package.
• final
    – The method cannot be overridden
• abstract
    – Only provides the method declaration
• strictfp
    – Method conforms to IEEE standard rules for floating points
• synchronized
    – Only one thread can access the method at a time
• native
    – Method is implemented in platform dependent language
• static
    – Cannot access only static members.



                                                                           16
Operators - Types



   • Definition:
      An operator performs a particular operation on the operands it is applied
      on



   • Types of operators
       –   Assignment Operators
       –   Arithmetic Operators
       –   Unary Operators
       –   Equality Operators
       –   Relational Operators
       –   Conditional Operators
       –   instaceof Operator
       –   Bitwise Operators
       –   Shift Operators

                                                             17
Operators – Assignment Operators/Arithmetic Operators



   • Assignment Operator
       Operator             Description        Example

          =                 Assignment         int i = 10;
                                               int j = i;




   • Arithmetic Operators
          Operator             Description     Example
              +                 Addition       int i = 8 + 9; byte b = (byte) 5+4;
              -                Subtraction     int i = 9 – 4;
              *               Multiplication   int i = 8 * 6;
              /                  Division      int i = 10 / 2;

              %                Remainder       int i = 10 % 3;

                                                                     18
Operators – Unary Operators/Equality Operators


   • Unary Operators
       Operator         Description       Example
          +             Unary plus        int i = +1;
           -            Unary minus       int i = -1;
          ++            Increment         int j = i++;
          --            Decrement         int j = i--;
           !            Logical Not       boolean j = !true;



 • Equality Operators

          Operator         Description   Example
               ==           Equality     If (i==1)
               !=         Non equality   If (i != 4)


                                                               19
Operators – Relational Operators/Conditional Operators


   • Relational Operators
       Operator             Description         Example
          >                 Greater than        if ( x > 4)
          <                  Less than          if ( x < 4)
          >=         Greater than or equal to   if ( x >= 4)
          <=          Less than or equal to     if ( x <= 4)




 • Conditional Operators
          Operator             Description      Example
               &&            Conditional and    If (a == 4 && b == 5)
               ||             Conditional or    If (a == 4 || b == 5)




                                                                        20
Operators – instanceof Operator/Bitwise Operators/shift operators


   • instanceof Operator
       Operator            Description            Example
       instanceof          Instamce of            If (john instance of person)

  • Bitwise Operators
           Operator           Description         Example
              &               Bitwise and         001 & 111 = 1
               |               Bitwise or         001 | 110 = 111
               ^              Bitwise ex-or       001 ^ 110 = 111
               ~                Reverse           ~011 = -10

  • Shift Operators
          Operator             Description         Example
             >>                Right shift         4 >> 1 = 100 >> 1 = 010 = 2
             <<                 Left Shift         4 << 1 = 100 << 1 = 1000 = 8
             >>>           Unsigned Right shift    4 >>> 1 = 100 >>> 121010 = 2
                                                                      =
Flow Control – if-else if-else




    • if-else
    Syntax                                 Example


    if (<condition-1>) {                   int a = 10;
      // logic for true condition-1 goes   if (a < 10 ) {
    here                                     System.out.println(“Less than 10”);
    } else if (<condition-2>) {            } else if (a > 10) {
      // logic for true condition-2 goes      System.out.pritln(“Greater than 10”);
    here                                   } else {
    } else {                                 System.out.println(“Equal to 10”);
      // if no condition is met, control   }
    comes here
    }
                                           Result: Equal to 10s



                                                                     22
Flow Control – switch



   • switch
   Syntax               Example

   switch (<value>) {   int a = 10;
    case <a>:           switch (a) {
     // stmt-1            case 1:
     break;                System.out.println(“1”);
    case <b>:              break;
     //stmt-2             case 10:
     break;                System.out.println(“10”);
    default:               break;
      //stmt-3            default:
                           System.out.println(“None”);

                        Result: 10


                                               23
Flow Control – do-while / while


   • do-while
       Syntax                      Example
       do {                        int i = 0;
        // stmt-1                  do {
       } while (<condition>);      System.out.println(“In do”); i++;
                                   } while ( i < 10);

                                   Result: Prints “In do” 11 times

 • while
       Syntax                     Example

       while (<condition>) {      int i = 0;
                 //stmt           while ( i < 10 ) {
       }                            System.out.println(“In while”); i++;
                                  }

                                  Result: “In while” 10 times
                                                         24
Flow Control – for loop



    • for
      Syntax                                     Example


      for ( initialize; condition; expression)   for (int i = 0; i < 10; i++)
      {                                          {
        // stmt                                    System.out.println(“In for”);
      }                                          }

                                                 Result: Prints “In do” 10 times




                                                                          25
Arrays and Strings – Arrays Declaration/Construction/Initialization



    • Array Declaration
           int myArray[];
           int[] myArray;
           double[][] doubleArray;
                                                    1   2   7    5   9   0
    • Array Construction
            int[] myArray = new int[5];
            int[][] twoDimArray = new int[5][4]

    • Array Initialization                              7   5    2
            int[] myArray = new int[5];
                                                        8   1    3
            for (int I = 0; I < 5; i++) {
              myArray[i] = i++;
            }

            int[5] myArray = {1,2,3,4,5};

                                                            26
Arrays and Strings – Arrays Representation



                                        Heap




                                    1    2   3   4   5




      myArray
                               int[ ] myArray = {1,2,3,4,5}
                                                              27
Arrays and Strings – Strings



    • Creating String Objects
     String myStr1 = new String(“abc”);
     String myStr2 = “abc”;
                                                           abc

  • Most frequently used String methods
      -   charAt (int index)
      -   compareTo (String str2)
      -   concat (String str2)
      -   equals (String str2)
      -   indexOf (int ch)
      -   length()
      -   replace (char oldChar, char newChar)
      -   substring (int beginIndex, int endIndex)   String Constant Pool



                                                             28
Constructors



   •   Creates instances for Classes
                                                            Employee emp = new Employee()
   •   Same name as Class name
   •   Can have any access modifier
   •   First statement should be a call to this() or
       super()

            public class Employee {
              public int empid;
              public String name;

                public Employee(int empid) {
                  this.empid = empid;
                }

                public Employee(String name, int empid) {
                  this.name = name;
                  this.empid = empid;
                }
            }
                                                                   29
OOPS Explored - Abstraction


   • Abstraction
            Hide certain details and show only essential details


         public abstract class Shape
         {
              String color;
              public abstract double getArea();
         }

          public interface Shape
          {
               String static final String color = “BLACK”;
               public abstract double getArea();
          }



      • Abstract class v/s interface

                                                                   30
OOPS Explored - Encapsulation



      I want to share
      my wedding gift                               I can share my
        only with my                                  puppy video
           friends                                   with everyone




                             My YouTube videos

                            My YouTube videos



                         My Cute       My Wedding
                        My Cute        My Hawaii
                          puppy            Gift
                          cat             trip
                                                    31
OOPS Explored - Encapsulation


   • Encapsulation
                Binding data and methods together

        public class Employee
        {
          private String empName;
          private int salary;

            public String getSalary(String role)
            {
              if(“Manager”.equals(role)) {
                 return salary;
              }
            }

            public String setSalary(String role, int newSal)
            {
              if (“Admin”.equals(role)) {
                 salary = newSal;
              }
            }
        }                                                      32
OOPS Explored - Inheritance


   • Inheritance
       Inherit the features of the superclass

        public class Car //superclass
        {
          public int maxSpeed;
          public String color;
          public int getSafeSpeed() { return maxSpeed/2.5; }
        }

        public class Nissan extends Car //subclass
        {
          public boolean inteligentKey;
             }




                                                               33
OOPS Explored - Polymorphism


   • Polymorphism
      One name, many forms

       public abstract class Shape
       {
         public abstract int getArea();
       }

       public class Square extends Shape
       {
         public int getArea(int s) { return s*s; }
         public int getArea() { retrun getArea(1); }
       }

       Public class Rectangle extends Shape
       {
         public int getArea(int length, int breadth) { return length * breadth; }
         public int getArea() { return getArea(1,1); }
       }

    • Runtime v/s Compile time Polymorphism                                  34
OOPS Explored – Polymorphism - Example


     public class Shape                               Shape s1 = new Shape();
     {                                                s1.display();
        public void display() {
           System.out.println(“In Shape”);            Square s2 = new Square ();
        }                                             s2.display();
     }
     public class Square extends Shape                Shape s3 = new Square ();
     {                                                s3.display();
       public void display() {
          System.out.println(“In Square”);
                                                      Square s4 = new Shape ();
       }
     }                                                s4.display();


                 s4
                                             square
                S3
                                                        shape
                 s2

                 s1                                           35
Exceptions – Exception Hierarchy



                             Throwable




               Error                     Exception




                            Checked                  Unchecked
                            Exception                 Exception




                                                     36
Exceptions – Handling exceptions



   • What do you do when an Exception occurs?
      – Handle the exception using try/catch/finally
      – Throw the Exception back to the calling method.


   • Try/catch/finally
        public class MyClass {
          public void exceptionMethod() {
            try {
              // exception-block
            } catch (Exception ex) {
              // handle exception
            } finally {
              //clean-up
            }
          }
        }

                                                          37
Exceptions – Handling exceptions

 • Try/catch/finally - 2
       public class MyClass {
         public void exceptionMethod() {
           try {
             // exception-block
           } catch (FileNotFoundException ex) {
             // handle exception
            } catch (Exception ex) {
             // handle exception
           } finally { //clean-up }
         }
       }


  • Using throws
       public class MyClass {
         public void exceptionMethod() throws Exception {
           // exception-block
         }
       }
                                                            38
Exceptions – try-catch-finally flow




    Put exception code in try         no    Handle exceptions
                                                In catch?



                                           yes

                                                                no
      Handle exception                       More exceptions           Execute
      In the catch block                       To handle?              finally?


                                            yes                                   no
                                                                      yes
         Clean-up code
           in finally




              END
                                                                 39
Garbage Collection




                     40
Garbage Collection



   • What is Garbage Collection?



   • Can we force Garbage Collection?
      Runtime – gc()
      System - gc()


   • Making your objects eligible for Garbage Collection
      – Reassign reference variable
      – Set a null value
      – Islands of isolation




                                                           41
Garbage Collection


     A a = new A();
     a.Name = ‘A1’;                           A1        A2
     a = A2;
                       Reassign Reference




     A a = new A();
     a = null;                                    A1
                      Set null




                                                       B
                       Islands Of Isolation
                                              A              C


                                                       42
Collections - Introduction



      String student1 = “a”;
      String student2 = “b”;
      String student3 = “c”;
      String student4 = “d”;
      String student5 = “e”;
      String student6 = “f”;




      • Difficult to maintain multiple items of same type as
      different variables

      • Data-manipulation issues

      • Unnecessary code


                                                               43
Collections – Arrays v/s Collections




         abc             def           ghi        jkl


    Arrays




         abc             123       new Person()   def


    Collections


                                                        44
Collections - Overview




           LinkedHashSet




                           45
Collections – Collection types



    • Three basic flavors of collections:
        Lists - Lists of things (classes that implement List)
        Sets - Unique things (classes that implement Set)
        Maps - Things with a unique ID (classes that implement Map)



    • The sub-flavors:
          Ordered - You can iterate through the collection in a specific order.
          Sorted - Collection is sorted in the natural order (alphabetical for Strings).
          Unordered
          Unsorted




                                                                                            46
Collections – Lists


    • ArrayList
            Resizable-array implementation of the List interface.
            Ordered collection.
            Should be considered when there is more of data retrieval than   add/delete.
            Often used methods – add(), get(), remove(), set(), size()




     • Vector
             Ordered collection
             To be considered when thread safety is a concern.
             Often used methods – add(), remove(), set(), get(), size()


     • Linked List
             Ordered collection.
             Faster insertion/deletion and slower retrieval when compared to ArrayList



                                                                                            47
Collections – Set


    • HashSet
               Not Sorted
               Not Ordered
               Should be used if only requirement is uniqueness
               Often used methods – add(), contains(), remove(), size()




   • LinkedHashSet
       Not Sorted
            Ordered
            Subclass of HashSet
            Should be used if the order of elements is important




   • TreeSet
           Sorted
           Ordered
           Should be used if you want to store objects in a sorted fashion
           Often used methods – first(), last(), add(), addAll(), subset()



                                                                              48
Collections – Map


   • HashMap
           Not Sorted, not ordered
           Can have one null key and any number of null values
           Not thread-safe
           Often used methods – get(), put(), containsKey(), keySet()




   • Hashtable
         Not Sorted, not ordered
         Cannot have null keys or values
         Thread-safe


   • LinkedHashMap
        Not sorted, but ordered


   • TreeMap
        Sorted, ordered


                                                                         49
Threads - Introduction


   What are Threads/ Why Threads?
   • A thread is a light-weight process.
   • Used to provide the ability to perform multiple things at the same time.




             method1()
           thread1.start()


               main()                    thread1.run()

   Thread Creation
   • There are 2 ways one can create a thread
       – Extending the Thread Class
       – Implementing the Runnable Interface


                                                                    50
Threads - Introduction



                                                        maintenance
  EXECUTION




                                      Process report

                   User validation


                                          TIME




                                         maintenance
       EXECUTION




                                       Process report             Multi-threaded
                                                                   environment
                    User validation

                                                                  51
                                             TIME
Threads - Creation



    Extending the Thread Class              Implementing the Runnable Interface


    public Class MyThread extends Thread    public Class MyThread implements Runnable
    {                                       {
      public void run()                       public void run()
      {                                       {
         System.out.println(“In Thread”);        System.out.println(“In Thread”);
      }                                       }
    }                                       }



    To Invoke:                              To Invoke:
    MyThread t1 = new MyThread();           MyThread t1 = new MyThread();
    t1.start();                             Thread t = new Thread(t1);
                                            t.Start();


                                                                   52
Threads – Thread Life cycle



       T1   T2
                                T1
        start                 blocked




            T2                T1     T2        T1    T2
       T1
      runnable                running               end




                                          53
Threads – Important Methods



   From the Thread class
   • public void start()
   • public void run()
   • public static void sleep(long millis) throws InterruptedException
   • public static void yield()
   • public final void join()
   • public final void setPriority(int newPriority)
                 –   Thread.MIN_PRIORITY    : 1
                 –   Thread.NORM_PRIORITY   : 5
                 –   Thread.MAX_PRIORITY     : 10

   From the Object class


   •   public final void wait()
   •   public final void notify()
   •   public final void notifyAll()



                                                                         54
Threads – Synchronization



 100 90 = getAccount (123);
  Account acct
                                                             Account
  MyThread t1 = new MyThread(acct);
 100 50 t2 = new MyThread(acct);
  MyThread
  t1.start();
 100 140
  t2.start();
                                                             shared object
  public class Account {
     private int bal;
     private int acctId;
     …
    public Account(int acctId) {
      this.acctId = acctId;
    }
    public boolean withdraw(int amt) {
      if (bal > 0) {                      acct             acct
        // give money                     run()           run()
        // other related activities
        bal = bal – amt;
      }                                  T1 stack        T2 stack
    }
  }
                                                    55
56

More Related Content

PDF
Ppl for students unit 4 and 5
PPT
Core java
PDF
Clojure - An Introduction for Java Programmers
PDF
Java Course 4: Exceptions & Collections
PDF
Java Course 3: OOP
PDF
Clojure - An Introduction for Lisp Programmers
PDF
Java Course 7: Text processing, Charsets & Encodings
Ppl for students unit 4 and 5
Core java
Clojure - An Introduction for Java Programmers
Java Course 4: Exceptions & Collections
Java Course 3: OOP
Clojure - An Introduction for Lisp Programmers
Java Course 7: Text processing, Charsets & Encodings

What's hot (20)

PPTX
Objective-c for Java Developers
ODP
Method Handles in Java
PDF
Java Course 5: Enums, Generics, Assertions
PDF
Java Course 2: Basics
PDF
New Features Of JDK 7
PDF
A Brief, but Dense, Intro to Scala
PPTX
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
PDF
Introduction to Clojure
PPTX
Core java complete ppt(note)
PDF
Clojure A Dynamic Programming Language for the JVM
PDF
Clojure talk at Münster JUG
PPT
Core Java Programming | Data Type | operator | java Control Flow| Class 2
PPTX
Scala, Play 2.0 & Cloud Foundry
ODP
Refactoring to Scala DSLs and LiftOff 2009 Recap
PPTX
Ch5 inheritance
PPTX
Unit1 introduction to Java
PDF
camel-scala.pdf
PPTX
Java Programming and J2ME: The Basics
PPTX
Core java1
PDF
Java Course 1: Introduction
Objective-c for Java Developers
Method Handles in Java
Java Course 5: Enums, Generics, Assertions
Java Course 2: Basics
New Features Of JDK 7
A Brief, but Dense, Intro to Scala
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Introduction to Clojure
Core java complete ppt(note)
Clojure A Dynamic Programming Language for the JVM
Clojure talk at Münster JUG
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Scala, Play 2.0 & Cloud Foundry
Refactoring to Scala DSLs and LiftOff 2009 Recap
Ch5 inheritance
Unit1 introduction to Java
camel-scala.pdf
Java Programming and J2ME: The Basics
Core java1
Java Course 1: Introduction
Ad

Viewers also liked (9)

PPTX
Java tutorial part 4
PDF
Java Advanced Features (TCF 2014)
DOC
Ieee java projects list
DOC
Non ieee dot net projects list
DOC
Non ieee java projects list
PPTX
Java tutorial part 3
PPTX
MBA Internship.ppt
PPTX
Internship Project Power Point Presentation
PPTX
Internship final presentation
Java tutorial part 4
Java Advanced Features (TCF 2014)
Ieee java projects list
Non ieee dot net projects list
Non ieee java projects list
Java tutorial part 3
MBA Internship.ppt
Internship Project Power Point Presentation
Internship final presentation
Ad

Similar to Core java (20)

PPTX
14.jun.2012
PPT
core java
PDF
Mobile Software Engineering Crash Course - C02 Java Primer
PDF
Core java 5 days workshop stuff
PDF
core java
PDF
Java 7
PPTX
Java fundamentals
PDF
First fare 2011 frc-java-introduction
PPT
Core Java
PPTX
Android webinar class_java_review
PPTX
What is so great about Java 6
PDF
Sdtl manual
PDF
03 expressions.ppt
PPTX
ppt_on_java.pptx
PPTX
Core Java Tutorials by Mahika Tutorials
PPTX
java Basic Programming Needs
PPTX
Java-Intro.pptx
PPT
Java security
PDF
JAVA Object Oriented Programming (OOP)
14.jun.2012
core java
Mobile Software Engineering Crash Course - C02 Java Primer
Core java 5 days workshop stuff
core java
Java 7
Java fundamentals
First fare 2011 frc-java-introduction
Core Java
Android webinar class_java_review
What is so great about Java 6
Sdtl manual
03 expressions.ppt
ppt_on_java.pptx
Core Java Tutorials by Mahika Tutorials
java Basic Programming Needs
Java-Intro.pptx
Java security
JAVA Object Oriented Programming (OOP)

Core java

  • 1. Core Java - Sharad Ballepu sharadballepu@sharmanj.com www.sharmanj.com 1
  • 2. Core Java Servlets & JSPs Agenda • Introduction • Access Modifiers • Operators • Flow Control • Arrays and Strings • OOPS Explored • Exceptions • Garbage Collection • Collections • Threads • Demo 2
  • 3. Introduction – What is Java • Programming language – Another programming language using which we can develop applets, standalone applications, web applications and enterprise applications. • Platform Independent – A Java program written and compiled on one machine can be executed on any other machine (irrespective of the operating system) • Object Oriented – Complies to object oriented programming concepts. Your program is not object oriented unless you code that way • Compiled and Interpreted – The .java file is compiled to a .class file & the .class file is interpreted to machine code 3
  • 4. Introduction – Java Virtual Machine Java .class .java file Compiler file Java Virtual Machine Mac Microsoft UNIX 4
  • 5. Introduction – My First Program Version 1 package com.sharadballepu.test; public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello World”); } } Compile the program: javac HelloWorld.java Execute the program: java HelloWorld Output: Hello World 5
  • 6. Introduction – My First Program Version 2 package com.sharadballepu.test; public class HelloWorld { public static void main(String[] args) { HelloWorld hw = new HelloWorld(); hw.display(); } public void display() { System.out.println(“Hello World”); } } Compile the program: javac HelloWorld.java Execute the program: java HelloWorld Output: Hello World 6
  • 7. Introduction – My First Program Version 3 package com.sharadballepu.test; public class HelloWorld { public static void main(String[] args) { HelloWorld hw = new HelloWorld(); hw.display(args[0]); } public void display(String userName) { System.out.println(“Hello ” + userName); } } Compile the program: javac HelloWorld.java Execute the program: java HelloWorld Sharad Output: Hello Sharad 7
  • 8. Introduction – My First Program Version 4 package com.sharadballepu.test; public class HelloWorld { String userName; public static void main(String[] args) { HelloWorld hw = new HelloWorld(); hw.userName = args[0]; } public void display() { System.out.println(“Hello ” + userName); } } Compile the program: javac HelloWorld.java Execute the program: java HelloWorld Sharad Output: Hello Sharad 8
  • 9. Introduction – Java Keywords abstract boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while assert 9
  • 10. Introduction – Stack v/s Heap A B x = 10 y = new A() method2() method1() C main() Stack Heap 10
  • 11. Introduction - Object Oriented Concepts • Class – A blueprint that defines the attributes and methods • Object – An instance of a Class • Abstraction – Hide certain details and show only essential details • Encapsulation – Binding data and methods together • Inheritance – Inherit the features of the superclass • Polymorphism – One name having many forms 11
  • 12. Introduction - Data Types Data type Byt Min Max Value Literal Values es Value byte 1 -27 27 – 1 123 short 2 -215 215 – 1 1234 int 4 -231 231 – 1 12345, 086, 0x675 long 8 -263 263 – 1 123456 float 4 - - 1.0 double 8 - - 123.86 char 2 0 216 – 1 ‘a’, ‘n’ boolean - - - true, false General rule: Min value = 2(bits – 1) Max value = 2(bits-1) – 1 (where 1 byte = 8 bits) 12
  • 13. Java Modifiers Modifier Class Class Methods Method Variables Variables public    private   protected   default    final     abstract   strictfp   transient  synchronized  native  volatile  13 static
  • 14. Modifiers – Class • public – Class can be accessed from any other class present in any package • default – Class can be accessed only from within the same package. Classes outside the package in which the class is defined cannot access this class • final – This class cannot be sub-classed, one cannot extend this class • abstract – Class cannot be instantiated, need to sub-classs/extend. • strictfp – Conforms that all methods in the class will conform to IEEE standard rules for floating points 14
  • 15. Modifiers – Class Attributes • public – Attribute can be accessed from any other class present in any package • private – Attribute can be accessed from only within the class • protected – Attribute can be accessed from all classes in the same package and sub-classes. • default – Attribute can be accessed only from within the same package. • final – This value of the attribute cannot be changed, can assign only 1 value • transient – The attribute value cannot be serialized • volatile – Thread always reconciles its own copy of attribute with master. • static – Only one value of the attribute per class 15
  • 16. Modifiers – Methods • public – Method can be accessed from any other class present in any package • private – Method can be accessed from only within the class • protected – Method can be accessed from all classes in the same package and sub-classes. • default – Method can be accessed only from within the same package. • final – The method cannot be overridden • abstract – Only provides the method declaration • strictfp – Method conforms to IEEE standard rules for floating points • synchronized – Only one thread can access the method at a time • native – Method is implemented in platform dependent language • static – Cannot access only static members. 16
  • 17. Operators - Types • Definition: An operator performs a particular operation on the operands it is applied on • Types of operators – Assignment Operators – Arithmetic Operators – Unary Operators – Equality Operators – Relational Operators – Conditional Operators – instaceof Operator – Bitwise Operators – Shift Operators 17
  • 18. Operators – Assignment Operators/Arithmetic Operators • Assignment Operator Operator Description Example = Assignment int i = 10; int j = i; • Arithmetic Operators Operator Description Example + Addition int i = 8 + 9; byte b = (byte) 5+4; - Subtraction int i = 9 – 4; * Multiplication int i = 8 * 6; / Division int i = 10 / 2; % Remainder int i = 10 % 3; 18
  • 19. Operators – Unary Operators/Equality Operators • Unary Operators Operator Description Example + Unary plus int i = +1; - Unary minus int i = -1; ++ Increment int j = i++; -- Decrement int j = i--; ! Logical Not boolean j = !true; • Equality Operators Operator Description Example == Equality If (i==1) != Non equality If (i != 4) 19
  • 20. Operators – Relational Operators/Conditional Operators • Relational Operators Operator Description Example > Greater than if ( x > 4) < Less than if ( x < 4) >= Greater than or equal to if ( x >= 4) <= Less than or equal to if ( x <= 4) • Conditional Operators Operator Description Example && Conditional and If (a == 4 && b == 5) || Conditional or If (a == 4 || b == 5) 20
  • 21. Operators – instanceof Operator/Bitwise Operators/shift operators • instanceof Operator Operator Description Example instanceof Instamce of If (john instance of person) • Bitwise Operators Operator Description Example & Bitwise and 001 & 111 = 1 | Bitwise or 001 | 110 = 111 ^ Bitwise ex-or 001 ^ 110 = 111 ~ Reverse ~011 = -10 • Shift Operators Operator Description Example >> Right shift 4 >> 1 = 100 >> 1 = 010 = 2 << Left Shift 4 << 1 = 100 << 1 = 1000 = 8 >>> Unsigned Right shift 4 >>> 1 = 100 >>> 121010 = 2 =
  • 22. Flow Control – if-else if-else • if-else Syntax Example if (<condition-1>) { int a = 10; // logic for true condition-1 goes if (a < 10 ) { here System.out.println(“Less than 10”); } else if (<condition-2>) { } else if (a > 10) { // logic for true condition-2 goes System.out.pritln(“Greater than 10”); here } else { } else { System.out.println(“Equal to 10”); // if no condition is met, control } comes here } Result: Equal to 10s 22
  • 23. Flow Control – switch • switch Syntax Example switch (<value>) { int a = 10; case <a>: switch (a) { // stmt-1 case 1: break; System.out.println(“1”); case <b>: break; //stmt-2 case 10: break; System.out.println(“10”); default: break; //stmt-3 default: System.out.println(“None”); Result: 10 23
  • 24. Flow Control – do-while / while • do-while Syntax Example do { int i = 0; // stmt-1 do { } while (<condition>); System.out.println(“In do”); i++; } while ( i < 10); Result: Prints “In do” 11 times • while Syntax Example while (<condition>) { int i = 0; //stmt while ( i < 10 ) { } System.out.println(“In while”); i++; } Result: “In while” 10 times 24
  • 25. Flow Control – for loop • for Syntax Example for ( initialize; condition; expression) for (int i = 0; i < 10; i++) { { // stmt System.out.println(“In for”); } } Result: Prints “In do” 10 times 25
  • 26. Arrays and Strings – Arrays Declaration/Construction/Initialization • Array Declaration int myArray[]; int[] myArray; double[][] doubleArray; 1 2 7 5 9 0 • Array Construction int[] myArray = new int[5]; int[][] twoDimArray = new int[5][4] • Array Initialization 7 5 2 int[] myArray = new int[5]; 8 1 3 for (int I = 0; I < 5; i++) { myArray[i] = i++; } int[5] myArray = {1,2,3,4,5}; 26
  • 27. Arrays and Strings – Arrays Representation Heap 1 2 3 4 5 myArray int[ ] myArray = {1,2,3,4,5} 27
  • 28. Arrays and Strings – Strings • Creating String Objects String myStr1 = new String(“abc”); String myStr2 = “abc”; abc • Most frequently used String methods - charAt (int index) - compareTo (String str2) - concat (String str2) - equals (String str2) - indexOf (int ch) - length() - replace (char oldChar, char newChar) - substring (int beginIndex, int endIndex) String Constant Pool 28
  • 29. Constructors • Creates instances for Classes Employee emp = new Employee() • Same name as Class name • Can have any access modifier • First statement should be a call to this() or super() public class Employee { public int empid; public String name; public Employee(int empid) { this.empid = empid; } public Employee(String name, int empid) { this.name = name; this.empid = empid; } } 29
  • 30. OOPS Explored - Abstraction • Abstraction Hide certain details and show only essential details public abstract class Shape { String color; public abstract double getArea(); } public interface Shape { String static final String color = “BLACK”; public abstract double getArea(); } • Abstract class v/s interface 30
  • 31. OOPS Explored - Encapsulation I want to share my wedding gift I can share my only with my puppy video friends with everyone My YouTube videos My YouTube videos My Cute My Wedding My Cute My Hawaii puppy Gift cat trip 31
  • 32. OOPS Explored - Encapsulation • Encapsulation Binding data and methods together public class Employee { private String empName; private int salary; public String getSalary(String role) { if(“Manager”.equals(role)) { return salary; } } public String setSalary(String role, int newSal) { if (“Admin”.equals(role)) { salary = newSal; } } } 32
  • 33. OOPS Explored - Inheritance • Inheritance Inherit the features of the superclass public class Car //superclass { public int maxSpeed; public String color; public int getSafeSpeed() { return maxSpeed/2.5; } } public class Nissan extends Car //subclass { public boolean inteligentKey; } 33
  • 34. OOPS Explored - Polymorphism • Polymorphism One name, many forms public abstract class Shape { public abstract int getArea(); } public class Square extends Shape { public int getArea(int s) { return s*s; } public int getArea() { retrun getArea(1); } } Public class Rectangle extends Shape { public int getArea(int length, int breadth) { return length * breadth; } public int getArea() { return getArea(1,1); } } • Runtime v/s Compile time Polymorphism 34
  • 35. OOPS Explored – Polymorphism - Example public class Shape Shape s1 = new Shape(); { s1.display(); public void display() { System.out.println(“In Shape”); Square s2 = new Square (); } s2.display(); } public class Square extends Shape Shape s3 = new Square (); { s3.display(); public void display() { System.out.println(“In Square”); Square s4 = new Shape (); } } s4.display(); s4 square S3 shape s2 s1 35
  • 36. Exceptions – Exception Hierarchy Throwable Error Exception Checked Unchecked Exception Exception 36
  • 37. Exceptions – Handling exceptions • What do you do when an Exception occurs? – Handle the exception using try/catch/finally – Throw the Exception back to the calling method. • Try/catch/finally public class MyClass { public void exceptionMethod() { try { // exception-block } catch (Exception ex) { // handle exception } finally { //clean-up } } } 37
  • 38. Exceptions – Handling exceptions • Try/catch/finally - 2 public class MyClass { public void exceptionMethod() { try { // exception-block } catch (FileNotFoundException ex) { // handle exception } catch (Exception ex) { // handle exception } finally { //clean-up } } } • Using throws public class MyClass { public void exceptionMethod() throws Exception { // exception-block } } 38
  • 39. Exceptions – try-catch-finally flow Put exception code in try no Handle exceptions In catch? yes no Handle exception More exceptions Execute In the catch block To handle? finally? yes no yes Clean-up code in finally END 39
  • 41. Garbage Collection • What is Garbage Collection? • Can we force Garbage Collection? Runtime – gc() System - gc() • Making your objects eligible for Garbage Collection – Reassign reference variable – Set a null value – Islands of isolation 41
  • 42. Garbage Collection A a = new A(); a.Name = ‘A1’; A1 A2 a = A2; Reassign Reference A a = new A(); a = null; A1 Set null B Islands Of Isolation A C 42
  • 43. Collections - Introduction String student1 = “a”; String student2 = “b”; String student3 = “c”; String student4 = “d”; String student5 = “e”; String student6 = “f”; • Difficult to maintain multiple items of same type as different variables • Data-manipulation issues • Unnecessary code 43
  • 44. Collections – Arrays v/s Collections abc def ghi jkl Arrays abc 123 new Person() def Collections 44
  • 45. Collections - Overview LinkedHashSet 45
  • 46. Collections – Collection types • Three basic flavors of collections:  Lists - Lists of things (classes that implement List)  Sets - Unique things (classes that implement Set)  Maps - Things with a unique ID (classes that implement Map) • The sub-flavors:  Ordered - You can iterate through the collection in a specific order.  Sorted - Collection is sorted in the natural order (alphabetical for Strings).  Unordered  Unsorted 46
  • 47. Collections – Lists • ArrayList  Resizable-array implementation of the List interface.  Ordered collection.  Should be considered when there is more of data retrieval than add/delete.  Often used methods – add(), get(), remove(), set(), size() • Vector  Ordered collection  To be considered when thread safety is a concern.  Often used methods – add(), remove(), set(), get(), size() • Linked List  Ordered collection.  Faster insertion/deletion and slower retrieval when compared to ArrayList 47
  • 48. Collections – Set • HashSet  Not Sorted  Not Ordered  Should be used if only requirement is uniqueness  Often used methods – add(), contains(), remove(), size() • LinkedHashSet  Not Sorted  Ordered  Subclass of HashSet  Should be used if the order of elements is important • TreeSet  Sorted  Ordered  Should be used if you want to store objects in a sorted fashion  Often used methods – first(), last(), add(), addAll(), subset() 48
  • 49. Collections – Map • HashMap  Not Sorted, not ordered  Can have one null key and any number of null values  Not thread-safe  Often used methods – get(), put(), containsKey(), keySet() • Hashtable  Not Sorted, not ordered  Cannot have null keys or values  Thread-safe • LinkedHashMap  Not sorted, but ordered • TreeMap  Sorted, ordered 49
  • 50. Threads - Introduction What are Threads/ Why Threads? • A thread is a light-weight process. • Used to provide the ability to perform multiple things at the same time. method1() thread1.start() main() thread1.run() Thread Creation • There are 2 ways one can create a thread – Extending the Thread Class – Implementing the Runnable Interface 50
  • 51. Threads - Introduction maintenance EXECUTION Process report User validation TIME maintenance EXECUTION Process report Multi-threaded environment User validation 51 TIME
  • 52. Threads - Creation Extending the Thread Class Implementing the Runnable Interface public Class MyThread extends Thread public Class MyThread implements Runnable { { public void run() public void run() { { System.out.println(“In Thread”); System.out.println(“In Thread”); } } } } To Invoke: To Invoke: MyThread t1 = new MyThread(); MyThread t1 = new MyThread(); t1.start(); Thread t = new Thread(t1); t.Start(); 52
  • 53. Threads – Thread Life cycle T1 T2 T1 start blocked T2 T1 T2 T1 T2 T1 runnable running end 53
  • 54. Threads – Important Methods From the Thread class • public void start() • public void run() • public static void sleep(long millis) throws InterruptedException • public static void yield() • public final void join() • public final void setPriority(int newPriority) – Thread.MIN_PRIORITY : 1 – Thread.NORM_PRIORITY : 5 – Thread.MAX_PRIORITY : 10 From the Object class • public final void wait() • public final void notify() • public final void notifyAll() 54
  • 55. Threads – Synchronization 100 90 = getAccount (123); Account acct Account MyThread t1 = new MyThread(acct); 100 50 t2 = new MyThread(acct); MyThread t1.start(); 100 140 t2.start(); shared object public class Account { private int bal; private int acctId; … public Account(int acctId) { this.acctId = acctId; } public boolean withdraw(int amt) { if (bal > 0) { acct acct // give money run() run() // other related activities bal = bal – amt; } T1 stack T2 stack } } 55
  • 56. 56