SlideShare uma empresa Scribd logo
1 de 51
Core Java

Language Fundamentals
Keywords
 Keywords are special reserved words in Java that you
  cannot use as identifiers (names) for classes, methods,
  or variables. They have meaning to the compiler;
Access Modifiers
• private Makes a method or a variable accessible only
  from within its own class.


• protected Makes a method or a variable accessible
  only to classes in the same package or subclasses of the
  class.


• public Makes a class, method, or variable accessible
  from any other class.
Class, Method, and Variable Modifiers

• abstract Used to declare a class that cannot be
  instantiated, or a method that must be implemented by a
  nonabstract subclass.

• class Keyword used to specify a class.

• extends Used to indicate the superclass that a
  subclass is extending.

• final Makes it impossible to extend a class, override a
  method, or reinitialize a variable.
• implements Used to indicate the interfaces that
  a class will implement.

• interface Keyword used to specify an interface.

• native Indicates a method is written in a
  platform-dependent language such as C.

• new Used to instantiate an object by invoking
  the constructor.
• static Makes a method or a variable belong to a class as opposed
  to an instance.

• strictfp Used in front of a method or class to indicate that
  floating-point numbers will follow FP-strict rules in all expressions.

• synchronized Indicates that a method can be accessed by only
  one
  thread at a time.

• transient Prevents fields from ever being serialized. Transient fields
  are always skipped when objects are serialized.

• volatile Indicates a variable may change out of sync because it is
  used in threads.
Flow Control
•   break Exits from the block of code in which it resides.

•   case Executes a block of code, dependent on what the switch tests for.

•   continue Stops the rest of the code following this statement from
    executing in a loop and then begins the next iteration of the loop.

•   default Executes this block of code if none of the switch-case
    statements match.

•   do Executes a block of code one time, then, in conjunction with the
    while statement, it performs a test to determine whether the block should
    be executed again.

•   else Executes an alternate block of code if an if test is false.
• for Used to perform a conditional loop for a block of code.

• if Used to perform a logical test for true or false.

• instanceof Determines whether an object is an instance of a class,
  superclass, or interface.

• return Returns from a method without executing any code that
  follows the statement (can optionally return a variable).

• switch Indicates the variable to be compared with the case
  statements.

• while Executes a block of code repeatedly while a certain condition
  is true.
Error Handling
•   catch Declares the block of code used to handle an exception.

•   finally Block of code, usually following a try-catch statement, which is
    executed no matter what program flow occurs when dealing with an
    exception.

•   throw Used to pass an exception up to the method that called this method.

•   throws Indicates the method will pass an exception to the method that
    called it.

•   try Block of code that will be tried, but which may cause an exception.

•   assert Evaluates a conditional expression to verify the programmer’s
    assumption.
Package Control
• import Statement to import packages or
  classes into code.

• package Specifies to which package all
  classes in a source file belong.
Primitives
•   boolean A value indicating true or false.

•   byte An 8-bit integer (signed).

•   char A single Unicode character (16-bit unsigned)

•   double A 64-bit floating-point number (signed).

•   float A 32-bit floating-point number (signed).

•   int A 32-bit integer (signed).

•   long A 64-bit integer (signed).

•   short A 16-bit integer (signed).
Variable Keywords
    The following keywords are a special type of reference variable:

• super Reference variable referring to the immediate superclass.

• this Reference variable referring to the current instance of an
  object.


                Void Return Type Keyword

    The void keyword is used only in the return value placeholder
    of a method declaration.
Ranges of Primitive Types
•   All six number types in Java are
    signed, meaning they can be         Type    No. of bytes
    negative or positive.
                                                it allocates
•    The leftmost bit (the most
    significant digit) is used to       byte         1
    represent the sign, where a 1
    means negative and 0 means
    positive.                          short         2
                                        int          4
                                        long         8
                                        float        4
                                       double        8
• Primitive type char is used to hold unicode
  characters in java. It is used to store characters
  found in languages other than English. Unicode
  characters are represented by unsigned 16-bit
  integers.

• boolean is used to hold either true or false.
Integer Literals
Ways to represent integer numbers in JAVA :- 3


4.     Decimal Literals
5.     Octal Literals
6.     Hexadecimal Literals


All three integer literals (octal, decimal, and hexadecimal) are
      defined as int by default, but they may also be specified as
      long by placing a suffix of L or l after the number:

Ex :
       long x = 110599L;
• Floating-point Literals
• Character Literals
• String Literals
Class
A way to implement object-oriented
            concepts.
Class Declaration
class Name
{
        // instance variable declaration
        // class variable declaration
        // constructor declaration

        Type methodName(parameterList)
        {}
        static Type methodName(parameterList)
        {}
        .
        .
}
What does a class declaration may have?

•   One or more instance variables
•   One or more class variables
•   One or more constructors
•   One or more non-static methods
•   One or more static methods
•   One or more nested classes
•   One or more nested interfaces
•   Static or non-static block of code
Instance or Object Variables

•   Variables specific to every object of the class.
•   Objects use these variables to store their own data.
•   These aren’t static.
•   These can be private, protected, public.

class Student
{
       String name;
       int roll;
       int marks; // all these variables are object variables
}
Creating & Using Objects/Instances

class Test
{
        public static void main (String[] args)
        {
                 Student s1,s2;
                 s1 = new Student();
                 s2 = new Student();
                 s1.name=“Ram”; s1.roll=1; s1.marks=97;

               s2.name=“Ramesh”; s2.roll=2; s2.marks=78;

               System.out.println(s1.name+”   “+s1.roll+” “+s1.marks);
               System.out.println(s2.name+”   “+s2.roll+” “+s2.marks);
       }
}
Points To Think
Think of s1 & s2
• Type : Local Reference Variables
• Scope : main()
• Initialized : No
• Default value : null
Conclusion : Local ref. variables are auto-initialized
  with null.
• Data of Objects are not secure. main() can
  misuse those.
Enabling the Objects to secure its Data

• Change the instance variable declaration. Objects will protect
  their data automatically.

class Student
{
       private String name;
       private int roll;
       private int marks;

       public void setRecord(String n,int r,int m)
       { name=n; roll=r; marks=m; }
       public void showRecord()
       {
                System.out.println( name+” “+roll+” “+marks);
       }
}
An Access Specifier helps securing the data in
                 an Object.

Types of Access Specifiers : 4

• public : gives no security at all

• private : gives maxm security

• protected : used in the context of inheritance

• default : behaves like public for the package the class
  belongs to. For other packages, it acts like private.
Static or Class Variables
• Variables declared as static in the class aren’t
  specific to any object of the class.

• There is a single copy of such variables.

• These are primarily used to hold the data to be
  shared among objects of the class.

• These are allocated & initialized only once when
  the respective class is loaded.
class Monitor
{
       static String company=“LG”;
       String modelNo;
       float price;
       public static void main(String args[])
       {
                 Monitor m1,m2;
                 m1 = new Monitor();
                 m2 = new Monitor();
       }
}

• Both m1 & m2 are having separate copies of modelNo and price but
  sharing same variable company.

• A static variable can be accessed with the name of its class as well
  as with the object reference also.

• A static method can access static variables of its class directly if
  they aren’t hidden by local declarations.
Constructors
•   A non-static method of a class that has name same as that of its
    class.

•   Invoked automatically for every instance of the class.

•   Doesn’t have a return value provision.

•   Can be overloaded.

•   Can invoke other constructors of the same class.

•   Can invoke specific constructors of the super class also.

•   Can’t be made recursive.

•   Can’t be declared final.

•   Can be declared private, protected or public.
class Account
{
         String holder;
         String accountNo;
         String accountType;
         Account()
         {
                   System.out.println(“Default constructor”);
         }
         Account(String h,String aNo,String aType)
         {
                   holder=h;      accountNo=aNo;
                   accountType=aType;
                   System.out.println(“Parameterized constructor”);
         }
}
class Manager
{
         public static void main(String[] args)
         {
                   Account a1,a2;
                   a1=new Account();
                   a2 = new Account(“Sudi”,”1245235212”,”Savings”);
         }
}
this
•   Available to every non-static method.
•   Holds the object’s reference, the non-static
    method has been invoked on.

• Serves 2 purposes :
5. Accessing object’s variable when it’s hidden by
   a local variable with the same name.
6. Used to invoke another constructor of the
   same class.
Non-static or Instance methods
• Always invoked on the reference of an object.

• Primarily act as interfaces to the instance
  variables of the object for the methods outside
  the class.

• Can also access the static variables.

• Can invoke other static or non-static method of
  its class directly.
class Test
{
        static int s=9;
        int i=12;
        static void showS()
        {
                  System.out.println(“s = “+s);
        }
        void showI()
        {
                  System.out.println(“i = “+i);
                  showS();
                  s=16;
                  showS();
        }
}
class Main
{
        public static void main(String[] args)
        {
                  Test t = new Test();
                  t.showI();
        }
}
Static methods
• Can be invoked with the name of the class
  they belong to.

• Can access other static members of its
  class directly.

• Requires an object’s reference to access
  non-static members of its class.
Nesting of classes
A nested class can be of 2 kinds:
2.    Static Nested class
3.    Non-static Nested class or Inner class

ex :
class X
{
      …..
      static class Y // static Nested class of X
      {
      …..
      }
}
class X
{
      …..
      class Y       // Inner class of X
      {
      …..
      }
}
Static Nested Class
• A nested class marked as static.

• Requires an object to access the instance
  variables of its outer class.

• Outer class also requires an object to
  access the instance variables of its static
  nested class.
class X
{
          int i=12;
          static int j=10;
          static class Y
          {                                              class Main
                        int p=6;
                        static int q=5;                  {
                                                             public static void main(String[ ] args)
                       void showP()
                       { System.out.println(quot;p : quot;+p); }     {
                                                                   X refX = new X();
                       void showI()
                       {                                           X.Y refY = new X.Y();
                       X ref = new X();
                       System.out.println( ref.i );
                       System.out.println(i); //invalid           refX.showI();
                       System.out.println(quot;j : quot;+X.j);            refY.showP();
                       }
          }
          void showI()                                            refY.showP();
          { System.out.println(quot;i : quot;+i); }
          void showP()                                            refY.showI();
          {                                                   }
                     Y ref = new Y();
                     System.out.println( ref.p );
                                                          }
                     System.out.println( Y.p ); //invalid
                     System.out.println( Y.q );
          }
}
Non-static nested or Inner classes
•   For reuse and flexibility/extensibility, we keep our classes
    specialized. Any other behavior should be part of another class
    better suited for that job.

•   Think, while designing a class we need a behavior that belongs in
    a separate, specialized class, but also needs to be intimately tied
    to the class being designed.

•   Ex : Event Handlers used in a typical Chat-client Application

•   An inner class maintains a special relationship with its enclosing
    (outer) class. Methods in the inner class can access every member
    of the outer as if it were an integral part of outer.
Inner Classes : 3 Types
1. Regular Inner Class
      Normally, defined within the body of a class
      outside every methods.

2. Method-Local Inner class
      defined within any method (static or non-static) of a
      class.

3. Anonymous Inner class
      An unnamed regular or method-local inner
  class.
Regular Inner Class
     An object of inner class accessing the most secure members of its
     outer class object.
class X
{
    private int a=4;                               class Test
    private void msg()
                                                   {
    {
                                                       public static void main(String[] args)
           System.out.println(quot;Hello from Xquot;);
    }                                                  {
    class Y // inner class                                   X.Y ref = new X().new Y();
    {                                                        ref.showA();
           private int b=5;
                                                       }
           void showA()
           {
                                                   }
                       System.out.println(quot;a : quot;+a);
                       msg();
           }
    }
}
Regular Inner Class contd.
Think of reverse.. Can the outer object access the inner object?

class X                                      In order to access the members of inner.
{                                                Outer object need an instance of
    void showB()                                 inner.
    { System.out.println(quot;b : quot;+b); }
    class Y                                  void showB()
    { private int b=5; }                     {
}                                               System.out.println(“b : “+new Y().b);
class Test                                   }
{
    public static void main(String[] args)   It’s not a meaningful approach at all.
    {
          X ref = new X();
          ref.showB();
    }
}
Regular Inner Class contd.
Inner class declarations can hide outer class declarations….

class X
{
   private int a=3;
   class Y
   {
        int a=2;
        void show()
        {
                  int a=1;
                  System.out.println(a);
                  System.out.println( this.a );
                  System.out.println( X.this.a );
        }
   }
}
Regular Inner Class contd.
An inner class can’t have static declarations…

 class X
 {
     class Y
     {
           static{
                     System.out.println(“static block of Y”);
           }
           static int a=5;
           static int square( int num )
           { return num*num; }
     }
 }
Regular Inner Class contd.

How to create an instance of a regular inner class??
       Depends on where we’re creating the instance.

Is this a good practice to create an instance of inner class outside
the outer class??
         Not at all. Instead of this, create a regular class.

Which modifiers can be applied to a regular inner class?
      abstract, final, private, protected & public
Regular Inner Class contd.
Think of the followings…


class X
                           class X
{                          {
   private class Y            class Y
   {                          {
   }                               private Y(){}
}                                  protected Y(int a){}
                                   public Y(float f){}
                                   Y(int a,int b){}
                              }
                           }
Method-Local Inner Class
• It can be instantiated only within the method
  where the inner class is defined.

• The inner class object can use the local
  variables of the method only & only if they are
  declared final.

• The only modifiers applied to it are abstract and
  final. But not both at the same times.
Method-Local Inner Class contd.
class X
{
    private int a=3;
    public void mX()
    {
          int p=4;
          final int q=5;
          // we can’t create instance of Y here
          class Y
          {
                     void mY()
                     {
                               System.out.println(a);
                               System.out.println(q);
                               System.out.println(p); // won't compile
                     }
          }
          new Y().mY();
    }
}
Anonymous Inner Class

• An inner class declared without any class
  name.
• Types : 2
  – Anonymous subclass of a class
  – Anonymous implementer of a specified interface.
Anonymous subclass
class X
{
    void show()
    {
            System.out.println(quot;I'm from Xquot;);
    }
}
class Test
{
    X ref1 = new X()
    {
            void show()
            {
                       System.out.println(quot;I'm from an unnamed classquot;);
            }
    };
    X ref2 = new X(){ };          // neither ref1 nor ref2 refers to an object of type X. Instead
    both
                                   // refer to 2 different object of an unnamed subclass of X.
    public static void main(String[]args)
    {
           Test t = new Test();
           t.ref1.show();
    }
}                      Output : I’m from an unnamed class
Anonymous subclass                                  contd.




• The .class files generated :
         – X.class , Test.class , Test$1.class , Test$2.class

• Both Test$1 & Test$2 are final subclasses of X.
• Generated constructors have following declarations :
   – Test$1(Test)
   – Test$2(Test)
• Both Test$1 & Test$2 are inner classes of Test.

Think… Can an anonymous inner class have constructors, if

        no, why?
Polymorphism &Anonymous subclass
•     Think.. Can we use ref1 & ref2 to invoke a method not defined in X?
        – No
    class X
    {
         void show()
         {
                 System.out.println(quot;I'm from Xquot;);
         }
    }
    class Test
    {
         X ref1 = new X()
         {
                 void show() { System.out.println(quot;I'm from an unnamed classquot;); }
                 void disp() { System.out.println(“ I’m disp “); // valid
         };
         public static void main(String[]args)
         {
                 Test t = new Test();
                 t.ref1.show();
                 t.ref1.disp(); // invalid
         }
    }
Anonymous implementer
interface X
{
     void show();
}
class Test
{
       X ref = new X()            // completely valid
     {
            public void show()
            {
                System.out.println(quot; Hello quot;);
            }
     };
     public static void main(String[]args)
     {
              Test t = new Test();
              t.ref.show();
     }
}

This program is more polymorphic than the previous
Argument-Defined Anonymous Inner Class
interface A
{
   void disp();
}
interface B
{
     void show(A ref);
}
class Test
{
     B ref = new B()
     {
          public void show(A ref)
          {
             System.out.println(quot; Hello quot;);
             ref.disp();
          }
     };
     public static void main(String[]args)
     {
              Test t = new Test();
              t.ref.show(
                             new A()
                            { public void disp() { System.out.println(quot;Hiquot;); } }
                         );
     }
}

Mais conteúdo relacionado

Mais procurados

Action Script
Action ScriptAction Script
Action ScriptAngelin R
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
Fundamental programming structures in java
Fundamental programming structures in javaFundamental programming structures in java
Fundamental programming structures in javaShashwat Shriparv
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Courseparveen837153
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to ScalaRiccardo Cardin
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to javaSadhanaParameswaran
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Andrew Petryk
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statementsİbrahim Kürce
 
Learning core java
Learning core javaLearning core java
Learning core javaAbhay Bharti
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and StringsEduardo Bergavera
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
Review of c_sharp2_features_part_ii
Review of c_sharp2_features_part_iiReview of c_sharp2_features_part_ii
Review of c_sharp2_features_part_iiNico Ludwig
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and VariablesSyed Afaq Shah MACS CP
 

Mais procurados (20)

Action Script
Action ScriptAction Script
Action Script
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Fundamental programming structures in java
Fundamental programming structures in javaFundamental programming structures in java
Fundamental programming structures in java
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statements
 
Learning core java
Learning core javaLearning core java
Learning core java
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
M C6java3
M C6java3M C6java3
M C6java3
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
JavaScript Data Types
JavaScript Data TypesJavaScript Data Types
JavaScript Data Types
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
Review of c_sharp2_features_part_ii
Review of c_sharp2_features_part_iiReview of c_sharp2_features_part_ii
Review of c_sharp2_features_part_ii
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 

Destaque

Expansión del universo
Expansión del universoExpansión del universo
Expansión del universoantonio_52
 
developmental session(presentation)
developmental session(presentation)developmental session(presentation)
developmental session(presentation)Cleon McGarrell
 
Presentacion de teclados y mause
Presentacion de teclados y mausePresentacion de teclados y mause
Presentacion de teclados y mauseBrayan Sanchez
 
Petrochemistry 2016 a4 brochure
Petrochemistry 2016 a4 brochurePetrochemistry 2016 a4 brochure
Petrochemistry 2016 a4 brochureSanfour Adlen
 
Diversitat lingüística a l'aula
Diversitat lingüística a l'aulaDiversitat lingüística a l'aula
Diversitat lingüística a l'aulaRocio Avila
 
Correcció escrits
Correcció escritsCorrecció escrits
Correcció escritsRocio Avila
 
Graston Technique® Introductory Power Point
Graston Technique® Introductory Power PointGraston Technique® Introductory Power Point
Graston Technique® Introductory Power Pointbiker104
 
The Southern Wright Whales with Surf and Sun
The Southern Wright Whales  with Surf and SunThe Southern Wright Whales  with Surf and Sun
The Southern Wright Whales with Surf and SunAshley Smith
 
Surf & Sun - Fun and Great things to do with their Kids in Adelaide
Surf & Sun - Fun and Great things to do with  their Kids in AdelaideSurf & Sun - Fun and Great things to do with  their Kids in Adelaide
Surf & Sun - Fun and Great things to do with their Kids in AdelaideAshley Smith
 

Destaque (15)

Expansión del universo
Expansión del universoExpansión del universo
Expansión del universo
 
developmental session(presentation)
developmental session(presentation)developmental session(presentation)
developmental session(presentation)
 
Presentacion de teclados y mause
Presentacion de teclados y mausePresentacion de teclados y mause
Presentacion de teclados y mause
 
Petrochemistry 2016 a4 brochure
Petrochemistry 2016 a4 brochurePetrochemistry 2016 a4 brochure
Petrochemistry 2016 a4 brochure
 
Jennifer Y
Jennifer YJennifer Y
Jennifer Y
 
Los perros
Los perrosLos perros
Los perros
 
El universo primitivo
El universo primitivoEl universo primitivo
El universo primitivo
 
Diversitat lingüística a l'aula
Diversitat lingüística a l'aulaDiversitat lingüística a l'aula
Diversitat lingüística a l'aula
 
Assistente Pessoal de Compras MC18
Assistente Pessoal de Compras MC18 Assistente Pessoal de Compras MC18
Assistente Pessoal de Compras MC18
 
Correcció escrits
Correcció escritsCorrecció escrits
Correcció escrits
 
Pesquisa Rápida CLOUD
Pesquisa Rápida CLOUDPesquisa Rápida CLOUD
Pesquisa Rápida CLOUD
 
Graston Technique® Introductory Power Point
Graston Technique® Introductory Power PointGraston Technique® Introductory Power Point
Graston Technique® Introductory Power Point
 
Apresentação Memor x3
Apresentação Memor x3Apresentação Memor x3
Apresentação Memor x3
 
The Southern Wright Whales with Surf and Sun
The Southern Wright Whales  with Surf and SunThe Southern Wright Whales  with Surf and Sun
The Southern Wright Whales with Surf and Sun
 
Surf & Sun - Fun and Great things to do with their Kids in Adelaide
Surf & Sun - Fun and Great things to do with  their Kids in AdelaideSurf & Sun - Fun and Great things to do with  their Kids in Adelaide
Surf & Sun - Fun and Great things to do with their Kids in Adelaide
 

Semelhante a Core Java

C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio) rnkhan
 
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)rnkhan
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variablesPushpendra Tyagi
 
Chapter 3.2
Chapter 3.2Chapter 3.2
Chapter 3.2sotlsoc
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2Todor Kolev
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2Todor Kolev
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)heoff
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3Mahmoud Alfarra
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Languagezone
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de JavascriptBernard Loire
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoobirbal
 
Lecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxLecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxSaqlainYaqub1
 

Semelhante a Core Java (20)

C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio)
 
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)
 
Javascript
JavascriptJavascript
Javascript
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Core java
Core javaCore java
Core java
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
 
dizital pods session 2.pptx
dizital pods session 2.pptxdizital pods session 2.pptx
dizital pods session 2.pptx
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Chapter 3.2
Chapter 3.2Chapter 3.2
Chapter 3.2
 
Javascript
JavascriptJavascript
Javascript
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
 
Lecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxLecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptx
 

Mais de Bharat17485

Channel Based Io
Channel Based IoChannel Based Io
Channel Based IoBharat17485
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded ApplicationsBharat17485
 
Interfaces & Abstract Classes
Interfaces & Abstract ClassesInterfaces & Abstract Classes
Interfaces & Abstract ClassesBharat17485
 
Exceptions & Its Handling
Exceptions & Its HandlingExceptions & Its Handling
Exceptions & Its HandlingBharat17485
 
Primitive Wrappers
Primitive WrappersPrimitive Wrappers
Primitive WrappersBharat17485
 
Regular Expression
Regular ExpressionRegular Expression
Regular ExpressionBharat17485
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input OutputBharat17485
 
Applying Generics
Applying GenericsApplying Generics
Applying GenericsBharat17485
 

Mais de Bharat17485 (12)

Channel Based Io
Channel Based IoChannel Based Io
Channel Based Io
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
 
Interfaces & Abstract Classes
Interfaces & Abstract ClassesInterfaces & Abstract Classes
Interfaces & Abstract Classes
 
Enum
EnumEnum
Enum
 
Exceptions & Its Handling
Exceptions & Its HandlingExceptions & Its Handling
Exceptions & Its Handling
 
Jstl & El
Jstl & ElJstl & El
Jstl & El
 
Primitive Wrappers
Primitive WrappersPrimitive Wrappers
Primitive Wrappers
 
Regular Expression
Regular ExpressionRegular Expression
Regular Expression
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
 
String Handling
String HandlingString Handling
String Handling
 
Swing
SwingSwing
Swing
 
Applying Generics
Applying GenericsApplying Generics
Applying Generics
 

Último

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Último (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Core Java

  • 2. Keywords  Keywords are special reserved words in Java that you cannot use as identifiers (names) for classes, methods, or variables. They have meaning to the compiler;
  • 3. Access Modifiers • private Makes a method or a variable accessible only from within its own class. • protected Makes a method or a variable accessible only to classes in the same package or subclasses of the class. • public Makes a class, method, or variable accessible from any other class.
  • 4. Class, Method, and Variable Modifiers • abstract Used to declare a class that cannot be instantiated, or a method that must be implemented by a nonabstract subclass. • class Keyword used to specify a class. • extends Used to indicate the superclass that a subclass is extending. • final Makes it impossible to extend a class, override a method, or reinitialize a variable.
  • 5. • implements Used to indicate the interfaces that a class will implement. • interface Keyword used to specify an interface. • native Indicates a method is written in a platform-dependent language such as C. • new Used to instantiate an object by invoking the constructor.
  • 6. • static Makes a method or a variable belong to a class as opposed to an instance. • strictfp Used in front of a method or class to indicate that floating-point numbers will follow FP-strict rules in all expressions. • synchronized Indicates that a method can be accessed by only one thread at a time. • transient Prevents fields from ever being serialized. Transient fields are always skipped when objects are serialized. • volatile Indicates a variable may change out of sync because it is used in threads.
  • 7. Flow Control • break Exits from the block of code in which it resides. • case Executes a block of code, dependent on what the switch tests for. • continue Stops the rest of the code following this statement from executing in a loop and then begins the next iteration of the loop. • default Executes this block of code if none of the switch-case statements match. • do Executes a block of code one time, then, in conjunction with the while statement, it performs a test to determine whether the block should be executed again. • else Executes an alternate block of code if an if test is false.
  • 8. • for Used to perform a conditional loop for a block of code. • if Used to perform a logical test for true or false. • instanceof Determines whether an object is an instance of a class, superclass, or interface. • return Returns from a method without executing any code that follows the statement (can optionally return a variable). • switch Indicates the variable to be compared with the case statements. • while Executes a block of code repeatedly while a certain condition is true.
  • 9. Error Handling • catch Declares the block of code used to handle an exception. • finally Block of code, usually following a try-catch statement, which is executed no matter what program flow occurs when dealing with an exception. • throw Used to pass an exception up to the method that called this method. • throws Indicates the method will pass an exception to the method that called it. • try Block of code that will be tried, but which may cause an exception. • assert Evaluates a conditional expression to verify the programmer’s assumption.
  • 10. Package Control • import Statement to import packages or classes into code. • package Specifies to which package all classes in a source file belong.
  • 11. Primitives • boolean A value indicating true or false. • byte An 8-bit integer (signed). • char A single Unicode character (16-bit unsigned) • double A 64-bit floating-point number (signed). • float A 32-bit floating-point number (signed). • int A 32-bit integer (signed). • long A 64-bit integer (signed). • short A 16-bit integer (signed).
  • 12. Variable Keywords The following keywords are a special type of reference variable: • super Reference variable referring to the immediate superclass. • this Reference variable referring to the current instance of an object. Void Return Type Keyword The void keyword is used only in the return value placeholder of a method declaration.
  • 13. Ranges of Primitive Types • All six number types in Java are signed, meaning they can be Type No. of bytes negative or positive. it allocates • The leftmost bit (the most significant digit) is used to byte 1 represent the sign, where a 1 means negative and 0 means positive. short 2 int 4 long 8 float 4 double 8
  • 14. • Primitive type char is used to hold unicode characters in java. It is used to store characters found in languages other than English. Unicode characters are represented by unsigned 16-bit integers. • boolean is used to hold either true or false.
  • 15. Integer Literals Ways to represent integer numbers in JAVA :- 3 4. Decimal Literals 5. Octal Literals 6. Hexadecimal Literals All three integer literals (octal, decimal, and hexadecimal) are defined as int by default, but they may also be specified as long by placing a suffix of L or l after the number: Ex : long x = 110599L;
  • 16. • Floating-point Literals • Character Literals • String Literals
  • 17. Class A way to implement object-oriented concepts.
  • 18. Class Declaration class Name { // instance variable declaration // class variable declaration // constructor declaration Type methodName(parameterList) {} static Type methodName(parameterList) {} . . }
  • 19. What does a class declaration may have? • One or more instance variables • One or more class variables • One or more constructors • One or more non-static methods • One or more static methods • One or more nested classes • One or more nested interfaces • Static or non-static block of code
  • 20. Instance or Object Variables • Variables specific to every object of the class. • Objects use these variables to store their own data. • These aren’t static. • These can be private, protected, public. class Student { String name; int roll; int marks; // all these variables are object variables }
  • 21. Creating & Using Objects/Instances class Test { public static void main (String[] args) { Student s1,s2; s1 = new Student(); s2 = new Student(); s1.name=“Ram”; s1.roll=1; s1.marks=97; s2.name=“Ramesh”; s2.roll=2; s2.marks=78; System.out.println(s1.name+” “+s1.roll+” “+s1.marks); System.out.println(s2.name+” “+s2.roll+” “+s2.marks); } }
  • 22. Points To Think Think of s1 & s2 • Type : Local Reference Variables • Scope : main() • Initialized : No • Default value : null Conclusion : Local ref. variables are auto-initialized with null. • Data of Objects are not secure. main() can misuse those.
  • 23. Enabling the Objects to secure its Data • Change the instance variable declaration. Objects will protect their data automatically. class Student { private String name; private int roll; private int marks; public void setRecord(String n,int r,int m) { name=n; roll=r; marks=m; } public void showRecord() { System.out.println( name+” “+roll+” “+marks); } }
  • 24. An Access Specifier helps securing the data in an Object. Types of Access Specifiers : 4 • public : gives no security at all • private : gives maxm security • protected : used in the context of inheritance • default : behaves like public for the package the class belongs to. For other packages, it acts like private.
  • 25. Static or Class Variables • Variables declared as static in the class aren’t specific to any object of the class. • There is a single copy of such variables. • These are primarily used to hold the data to be shared among objects of the class. • These are allocated & initialized only once when the respective class is loaded.
  • 26. class Monitor { static String company=“LG”; String modelNo; float price; public static void main(String args[]) { Monitor m1,m2; m1 = new Monitor(); m2 = new Monitor(); } } • Both m1 & m2 are having separate copies of modelNo and price but sharing same variable company. • A static variable can be accessed with the name of its class as well as with the object reference also. • A static method can access static variables of its class directly if they aren’t hidden by local declarations.
  • 27. Constructors • A non-static method of a class that has name same as that of its class. • Invoked automatically for every instance of the class. • Doesn’t have a return value provision. • Can be overloaded. • Can invoke other constructors of the same class. • Can invoke specific constructors of the super class also. • Can’t be made recursive. • Can’t be declared final. • Can be declared private, protected or public.
  • 28. class Account { String holder; String accountNo; String accountType; Account() { System.out.println(“Default constructor”); } Account(String h,String aNo,String aType) { holder=h; accountNo=aNo; accountType=aType; System.out.println(“Parameterized constructor”); } } class Manager { public static void main(String[] args) { Account a1,a2; a1=new Account(); a2 = new Account(“Sudi”,”1245235212”,”Savings”); } }
  • 29. this • Available to every non-static method. • Holds the object’s reference, the non-static method has been invoked on. • Serves 2 purposes : 5. Accessing object’s variable when it’s hidden by a local variable with the same name. 6. Used to invoke another constructor of the same class.
  • 30. Non-static or Instance methods • Always invoked on the reference of an object. • Primarily act as interfaces to the instance variables of the object for the methods outside the class. • Can also access the static variables. • Can invoke other static or non-static method of its class directly.
  • 31. class Test { static int s=9; int i=12; static void showS() { System.out.println(“s = “+s); } void showI() { System.out.println(“i = “+i); showS(); s=16; showS(); } } class Main { public static void main(String[] args) { Test t = new Test(); t.showI(); } }
  • 32. Static methods • Can be invoked with the name of the class they belong to. • Can access other static members of its class directly. • Requires an object’s reference to access non-static members of its class.
  • 33. Nesting of classes A nested class can be of 2 kinds: 2. Static Nested class 3. Non-static Nested class or Inner class ex : class X { ….. static class Y // static Nested class of X { ….. } } class X { ….. class Y // Inner class of X { ….. } }
  • 34. Static Nested Class • A nested class marked as static. • Requires an object to access the instance variables of its outer class. • Outer class also requires an object to access the instance variables of its static nested class.
  • 35. class X { int i=12; static int j=10; static class Y { class Main int p=6; static int q=5; { public static void main(String[ ] args) void showP() { System.out.println(quot;p : quot;+p); } { X refX = new X(); void showI() { X.Y refY = new X.Y(); X ref = new X(); System.out.println( ref.i ); System.out.println(i); //invalid refX.showI(); System.out.println(quot;j : quot;+X.j); refY.showP(); } } void showI() refY.showP(); { System.out.println(quot;i : quot;+i); } void showP() refY.showI(); { } Y ref = new Y(); System.out.println( ref.p ); } System.out.println( Y.p ); //invalid System.out.println( Y.q ); } }
  • 36. Non-static nested or Inner classes • For reuse and flexibility/extensibility, we keep our classes specialized. Any other behavior should be part of another class better suited for that job. • Think, while designing a class we need a behavior that belongs in a separate, specialized class, but also needs to be intimately tied to the class being designed. • Ex : Event Handlers used in a typical Chat-client Application • An inner class maintains a special relationship with its enclosing (outer) class. Methods in the inner class can access every member of the outer as if it were an integral part of outer.
  • 37. Inner Classes : 3 Types 1. Regular Inner Class Normally, defined within the body of a class outside every methods. 2. Method-Local Inner class defined within any method (static or non-static) of a class. 3. Anonymous Inner class An unnamed regular or method-local inner class.
  • 38. Regular Inner Class An object of inner class accessing the most secure members of its outer class object. class X { private int a=4; class Test private void msg() { { public static void main(String[] args) System.out.println(quot;Hello from Xquot;); } { class Y // inner class X.Y ref = new X().new Y(); { ref.showA(); private int b=5; } void showA() { } System.out.println(quot;a : quot;+a); msg(); } } }
  • 39. Regular Inner Class contd. Think of reverse.. Can the outer object access the inner object? class X In order to access the members of inner. { Outer object need an instance of void showB() inner. { System.out.println(quot;b : quot;+b); } class Y void showB() { private int b=5; } { } System.out.println(“b : “+new Y().b); class Test } { public static void main(String[] args) It’s not a meaningful approach at all. { X ref = new X(); ref.showB(); } }
  • 40. Regular Inner Class contd. Inner class declarations can hide outer class declarations…. class X { private int a=3; class Y { int a=2; void show() { int a=1; System.out.println(a); System.out.println( this.a ); System.out.println( X.this.a ); } } }
  • 41. Regular Inner Class contd. An inner class can’t have static declarations… class X { class Y { static{ System.out.println(“static block of Y”); } static int a=5; static int square( int num ) { return num*num; } } }
  • 42. Regular Inner Class contd. How to create an instance of a regular inner class?? Depends on where we’re creating the instance. Is this a good practice to create an instance of inner class outside the outer class?? Not at all. Instead of this, create a regular class. Which modifiers can be applied to a regular inner class? abstract, final, private, protected & public
  • 43. Regular Inner Class contd. Think of the followings… class X class X { { private class Y class Y { { } private Y(){} } protected Y(int a){} public Y(float f){} Y(int a,int b){} } }
  • 44. Method-Local Inner Class • It can be instantiated only within the method where the inner class is defined. • The inner class object can use the local variables of the method only & only if they are declared final. • The only modifiers applied to it are abstract and final. But not both at the same times.
  • 45. Method-Local Inner Class contd. class X { private int a=3; public void mX() { int p=4; final int q=5; // we can’t create instance of Y here class Y { void mY() { System.out.println(a); System.out.println(q); System.out.println(p); // won't compile } } new Y().mY(); } }
  • 46. Anonymous Inner Class • An inner class declared without any class name. • Types : 2 – Anonymous subclass of a class – Anonymous implementer of a specified interface.
  • 47. Anonymous subclass class X { void show() { System.out.println(quot;I'm from Xquot;); } } class Test { X ref1 = new X() { void show() { System.out.println(quot;I'm from an unnamed classquot;); } }; X ref2 = new X(){ }; // neither ref1 nor ref2 refers to an object of type X. Instead both // refer to 2 different object of an unnamed subclass of X. public static void main(String[]args) { Test t = new Test(); t.ref1.show(); } } Output : I’m from an unnamed class
  • 48. Anonymous subclass contd. • The .class files generated : – X.class , Test.class , Test$1.class , Test$2.class • Both Test$1 & Test$2 are final subclasses of X. • Generated constructors have following declarations : – Test$1(Test) – Test$2(Test) • Both Test$1 & Test$2 are inner classes of Test. Think… Can an anonymous inner class have constructors, if no, why?
  • 49. Polymorphism &Anonymous subclass • Think.. Can we use ref1 & ref2 to invoke a method not defined in X? – No class X { void show() { System.out.println(quot;I'm from Xquot;); } } class Test { X ref1 = new X() { void show() { System.out.println(quot;I'm from an unnamed classquot;); } void disp() { System.out.println(“ I’m disp “); // valid }; public static void main(String[]args) { Test t = new Test(); t.ref1.show(); t.ref1.disp(); // invalid } }
  • 50. Anonymous implementer interface X { void show(); } class Test { X ref = new X() // completely valid { public void show() { System.out.println(quot; Hello quot;); } }; public static void main(String[]args) { Test t = new Test(); t.ref.show(); } } This program is more polymorphic than the previous
  • 51. Argument-Defined Anonymous Inner Class interface A { void disp(); } interface B { void show(A ref); } class Test { B ref = new B() { public void show(A ref) { System.out.println(quot; Hello quot;); ref.disp(); } }; public static void main(String[]args) { Test t = new Test(); t.ref.show( new A() { public void disp() { System.out.println(quot;Hiquot;); } } ); } }