Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Core Java


Published on

Published in: Technology

Core Java

  1. 1. Core Java Language Fundamentals
  2. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 16. • Floating-point Literals • Character Literals • String Literals
  17. 17. Class A way to implement object-oriented concepts.
  18. 18. Class Declaration class Name { // instance variable declaration // class variable declaration // constructor declaration Type methodName(parameterList) {} static Type methodName(parameterList) {} . . }
  19. 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. 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. 21. Creating & Using Objects/Instances class Test { public static void main (String[] args) { Student s1,s2; s1 = new Student(); s2 = new Student();“Ram”; s1.roll=1; s1.marks=97;“Ramesh”; s2.roll=2; s2.marks=78; System.out.println(” “+s1.roll+” “+s1.marks); System.out.println(” “+s2.roll+” “+s2.marks); } }
  22. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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();; } } Output : I’m from an unnamed class
  48. 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. 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.disp(); // invalid } }
  50. 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();; } } This program is more polymorphic than the previous
  51. 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(); new A() { public void disp() { System.out.println(quot;Hiquot;); } } ); } }