Basics Of Java I PRESENTED BY DEVASHISH BHATTACHARJEE
Basics Of Java - I PRESENTED BY: DEVASHISH BHATTACHARJEE +91 -9066262782 24 -May-21 Basics of Java - I 1
Java Coding Convention • • • Identifier Declaration Rules Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number! After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers. In practice, there is no limit to the number of characters an identifier can contain. We can't use a Java keyword as an identifier Identifiers in Java are case-sensitive; phone and PHONE are two different identifiers. int my. Salary; //valid int 9 A; //invalid 24 -May-21 Basics of Java - I 2
Sun JAVA’s Code Convention • • Classes and interfaces : The first letter should be capitalized, and if several words are linked together to form the name, the first letter of the inner words should be uppercase (a format that's sometimes called "camel. Case"). For classes, the names should typically be nouns. For example: Account, Print. Writer For interfaces, the names should typically be adjectives like Runnable, Serializable • Methods : The first letter should be lowercase, and then normal camel. Case rules should be used. In addition, the names should typically be verb-noun pairs. For example: get. Balance, do. Calculation • Variables: Like methods, the camel. Case format should be used, starting with a lowercase letter. Sun recommends short, meaningful names, which sounds good to us. Some examples: button. Width, account. Balance, my. String • Constants : Java constants are created by marking variables static and final. They should be named using uppercase letters with underscore characters as separators: MIN_HEIGHT 24 -May-21 Basics of Java - I 3
Java. Beans Standards Java. Beans Property Naming Rules • If the property is not a boolean, the getter method's prefix must be get. E. g. get. Size() • If the property is a boolean, the getter method's prefix is either get or is. E. g. get. Stopped() or is. Stopped() • The setter method's prefix must be set. E. g. set. Size() • Setter method signatures must be marked public, with a void return type and an argument that represents the property type. • Getter method signatures must be marked public, take no arguments, and have a return type that matches the argument type of the setter method for that property. Java. Beans Listener Naming Rules • Listener method names used to "register" a listener with an event source must use the prefix add, followed by the listener type. E. g. add. Action. Listener() • Listener method names used to remove ("unregister") a listener must use the prefix remove, followed by the listener type • The type of listener to be added or removed must be passed as the argument to the method. • Listener method names must end with the word "Listener". 24 -May-21 Basics of Java - I 4
Source File Declaration Rules • • There can be only one public class per source code file. Comments can appear at the beginning or end of any line in the source code If there is a public class in a file, the name of the file must match the name If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present. If there are import statements, they must go between the package statement and the class declaration. import and package statements apply to all classes within a source code file. A file can have more than one nonpublic class. Files with no public classes can have a name that does not match any of the classes in the file. 24 -May-21 Basics of Java - I 5
Interface • • An interface is a group of related methods with empty bodies. It makes the OO principle of loose coupling to be implemented easily. • • Rules for interfaces: All interface methods are implicitly public and abstract. All variables defined in an interface must be public, static, and final. Interface methods must not be static. Because interface methods are abstract, they cannot be marked final , strictfp, or native. An interface can extend one or more other interfaces. An interface cannot extend anything but another interface. An interface cannot implement another interface or class. An interface must be declared with the keyword interface. 24 -May-21 Basics of Java - I 6
Classes and Objects • A class is a template for an object, and an object is an instance of a class. • • A class can contain any of the following variable types. Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. Instance variables: Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. Class variables: Class variables are variables declared with in a class, outside any method, with the static keyword. • • 24 -May-21 Basics of Java - I 7
Classes and Objects • • • contd. . Creating an Object There are three steps when creating an object from a class: Declaration: A variable declaration with a variable name with an object type. Instantiation: The 'new' key word is used to create the object. Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new object. 24 -May-21 Basics of Java - I 8
Constructors and Instantiation • • Constructors are used for initializing all the instance variables in the class. Constructor chaining: Class Animal 4. Object() 3. Animal() calls super() 2. Horse() calls super() Class Horse extends Animal 1. main() calls new Horse() • • We use the keyword super() to call the constructor of the immediate parent class. This must be the first line inside the constructor of the derived class. Rules for Constructors can use any access modifier, including private. A private constructor means only code within the class itself can instantiate an object of that type, so if the private constructor class wants to allow an instance of the class to be used, the class must provide a static method or variable that allows access to an instance created from within the class. The constructor name must match the name of the class. Constructors must not have a return type. It's legal to have a method with the same name as the class, but that doesn't make it a constructor. 24 -May-21 Basics of Java - I 9
Constructors and Instantiation • • • contd. . A default constructor will be automatically generated by the compiler. The default constructor is always a no-arg constructor. If we want a no-arg constructor and we have typed any other constructor(s) into your class code, the compiler won't provide the no-arg constructor. Every constructor has, as its first statement, either a call to an overloaded constructor (this()) or a call to the super class constructor (super()). A call to super() can be either a no-arg call or can include arguments passed to the super constructor. A no-arg constructor is not necessarily the default (i. e. , compiler-supplied) constructor, although the default constructor is always a no-arg constructor. We cannot make a call to an instance method, or access an instance variable until after the super constructor runs. Only static variables and methods can be accessed as part of the call to super() or this(). (Example: super(Animal. NAME) is OK, because NAME is declared as a static variable. ) Abstract classes have constructors, and those constructors are always called when a concrete subclass is instantiated. Interfaces do not have constructors. Interfaces are not part of an object‘s inheritance tree. The only way a constructor can be invoked is from within another constructor. Overloaded Constructors : Overloading a constructor means typing in multiple versions of the constructor, each having a different argument list. 24 -May-21 Basics of Java - I 10
Modifiers Access Modifiers: default, public , private and protected Non-accesss modifier: strictfp, final, static • • • Final: The final keyword prevents a method from being overridden in a subclass, and is often used to enforce the API functionality of a method. Abstract Methods: An abstract method is a method that's been declared (as abstract) but not implemented. Synchronized Methods: The synchronized keyword indicates that a method can be accessed by only one thread at a time. Native Methods The native modifier indicates that a method is implemented in platform-dependent code, often in C. strictfp : It forces floating points (and any floating-point operations) to adhere to the IEEE 754 standard. 24 -May-21 Basics of Java - I 11
Enums • • An enumerationis a list of named constants. An enumeration is created using the enum keyword. E. g. enum Leaves{ Sick, Privilege} A Java enumeration is a class type We can give them constructors, add instance variables and methods, and even implement interfaces. 24 -May-21 Basics of Java - I 12
Encapsulation • • • Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. Keep instance variables protected (with an access modifier, often private). Make public accessor methods, and force calling code to use those methods rather than directly accessing the instance variable. For the methods, use the Java. Beans naming convention of set<some. Property> and set<some. Property>. Class B { get. Size(); set. Size(); } Class A { B b=new B(); int x=b. get. Size(); } Class A cannot access Class B instance variable data without going through getter and setter methods. Data is marked private; only the accessor methods are public. 24 -May-21 Basics of Java - I 13
Inheritance • Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the concept of hierarchical classification. • IS-A : In OO, the concept of IS-A is based on class inheritance or interface implementation. We express the IS-A relationship in Java through the keywords extends (for class inheritance) and implements (for interface implementation). E. g. public class Vehicle {. . . } public class Car extends Vehicle {. . . } • HAS-A relationships are based on usage, rather than inheritance. In other words, class A HAS -A B if code in class A has a reference to an instance of class B. E. g. public class Processor{…} Public class Mobile { Processor processor; //HAS-A …} 24 -May-21 Basics of Java - I 14
Polymorphism • • • • Is a feature that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature. Overridden Methods Any time we have a class that inherits a method from a superclass, you have the opportunity to override the method (unless the method is marked final). The key benefit of overriding is the ability to define behavior that's specific to a particular subclass type. The rules for overriding a method are as follows: The argument list must exactly match that of the overridden method. The return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass. The access level can't be more restrictive than the overridden method's. The access level CAN be less restrictive than that of the overridden method. Instance methods can be overridden only if they are inherited by the subclass. A subclass within the same package as the instance's superclass can override any superclass method that is not marked private or final. A subclass in a different package can override only those non-final methods marked public or protected. The overriding method CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception. The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. We cannot override a static method. 24 -May-21 Basics of Java - I 15
Polymorphism • • contd. . Overloaded Methods: Overloaded methods lets us reuse the same method name in a class, but with different arguments (and optionally, a different return type). The rules are as follows: Overloaded methods MUST change the argument list. Overloaded methods CAN change the return type. Overloaded methods CAN change the access modifier. Overloaded methods CAN declare new or broader checked exceptions. A method can be overloaded in the same class or in a subclass. Overidden method Overiding method Overloaded method The above example illustrates the overloading and the overriding concepts. 24 -May-21 Basics of Java - I 16
Casting • • • It is fairly common to assign a value of one type to a variable of another type. Java’s Automatic Conversions Two conditions are met: • The two types are compatible. • The destination type is larger than the source type. Casting Incompatible Types : To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. It has this general form: (target-type) value. E. g. int a; byte b; b = (byte) a; Reference Type Casting It's both possible and common to use generic reference variable types to refer to more specific object types. 24 -May-21 Basics of Java - I 17
Casting 24 -May-21 Basics of Java - I contd. . 18
Statics • When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. Static variable counter obj 1 • • • obj 2 obj 3 Static members Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable before any objects exist. Static methods main( ) is declared as static because it must be called before any objects Methods declared as static have several restrictions: They can only call other static methods. They must only access static data. They cannot refer to this or super in any way. Static methods can't be overridden. 24 -May-21 Basics of Java - I 19
Coupling and Cohesion As with most OO design discussions, the goals for an application are • Ease of creation • Ease of maintenance • Ease of enhancement • Coupling: Coupling is the degree to which one class knows about another class. A good design is in which the classes are loosely coupled. For the purpose we use interfaces to expose the methods of one class to another. • Cohesion: While coupling has to do with how classes interact with each other, cohesion is all about how a single class is designed. The term cohesion is used to indicate the degree to which a class has a single, well-focused purpose. 24 -May-21 Basics of Java - I 20
Passing object reference in methods Referring to the actual object , Referring to a new client object , 24 -May-21 Basics of Java - I 21
Passing object reference in methods • • contd. . For primitives, we pass a copy of the actual value. For references to objects, we pass a copy of the reference. 24 -May-21 Basics of Java - I 22
Array Declaration and Initialization • • • Arrays are declared by stating the type of element the array will hold, which can be an object or a primitive, followed by square brackets to the left or right of the identifier. E. g. int[] key; Phone [] phones = new Phone[5]; Here , the single object referenced by threads holds five Thread reference variables, but no Thread objects have been created or assigned to those references. phone[0]=new Phone(); Arrays can be one dimensional or multui-dimensional; int[][] my. Array = new int[3][]; Anonymous arrays: It is a shortcut form of array declaration and initialization. E. g. int[] test. Scores; test. Scores = new int[] {4, 7, 2}; Arrays of Object References: If the declared array type is a class, we can put objects of any subclass of the declared type into the array. class Car {} class Subaru extends Car {} class Ferrari extends Car {}. . . Car [] my. Cars = {new Subaru(), new Car(), new Ferrari()}; 24 -May-21 Basics of Java - I 23
Array Declaration and Initialization 24 -May-21 Basics of Java - I contd. . 24
Wrapper Classes • There is a wrapper class for every primitive in Java. • All of the wrapper classes except Character provide two constructors: one that takes a primitive of the type being constructed, and one that takes a String representation of the type being constructed—for example, Integer i 1 = new Integer(42); Integer i 2 = new Integer("42"); 24 -May-21 Basics of Java - I 25
Wrapper Classes • • • contd. . Integer i 2 = Integer. value. Of("100", 2); // 2 is the radix. We can convert to octal , hexadecimal or binary. xxx. Value() : When we need to convert the value of a wrapped numeric to a primitive, use one of the many xxx. Value() methods. E. g. Integer i 2 = new Integer(42); // make a new wrapper object byte b = i 2. byte. Value(); // convert i 2's value to a byte primitive parse. Xxx(String) - To convert a String to a primitive. It returns the named primitive. double d 4 = Double. parse. Double("3. 14"); value. Of(String) -to convert a String to a Wrapper. It returns a newly created wrapped object of the type that invoked the method. Integer i=Integer. value. Of(3); to. Xxx. String() (Binary, Hexadecimal, Octal): The Integer and Long wrapper classes let you convert numbers in base 10 to other bases. String s 3 = Integer. to. Hex. String(254); // convert 254 to hex System. out. println("254 is " + s 3); // result: "254 is fe" 24 -May-21 Basics of Java - I 26
Wrapper Classes 24 -May-21 Basics of Java - I contd. . 27
Autoboxing • • • Boxing is simply meaning of encapsulating particular primitive to the corresponding class. Integer i 1 = new Interger(12); Autoboxing: with Java 5. 0 onwards we have one great facility Integer i 1=12; Unboxing means, extract the primitive member value from the object. Integer i 1 = new Integer(12); int a = i 1; //No problem, unboxing is done In order to save memory, two instances of the following wrapper objects (created through boxing), will always be equal when their primitive values are the same: ■ Boolean ■ Byte ■ Characterfrom u 0000 to u 007 f ■ Shortand Integerfrom -128 to 127 24 -May-21 Basics of Java - I 28
Autoboxing contd. . • true false 24 -May-21 Basics of Java - I true false 29
Garbage Collection • • • Java's garbage collector provides an automatic solution to memory management. The garbage collector is under the control of the JVM. An object is eligible for garbage collection when no live thread can access it. “Deutsche” 0 X 8000 “NAB” 0 X 8080 24 -May-21 Basics of Java - I 30
Garbage Collection • • • contd. . We can even do a forced garbage collection by the utility gc() on the runtime class object. Runtime rt = Runtime. get. Runtime(); rt. gc(); We can directly call the System. gc() , to have as much free memory possible (theoretically). We can simply nullify the reference to make it eligible for garbage collection. Client client =new Client(“Deutsche”); client=null; 24 -May-21 Basics of Java - I 31
Operators Assignment Operator: The “=“ operator is used to assign the values to the identifiers. “+=“, ”-=“, ”*=“ and “/=“ are the compound assignment operators. Relational Operators : < , <=, >, >=, == and != are the relational operators. These always return boolean values. instanceof Operator: The instanceof operator is used for object reference variables only, and we can use it to check whether an object is of a particular type. E. g. class Vehicle {. . } class Car extends Vehicle { public static void main(String args[]) { Vehicle vehicle=new Car(); if(vehicle instanceof Car) true {}}} Arithmetic operators : +, -, * and / are the arithmentic operators. E. g. System. out. print(3+4); //7 System. out. print(3+” 4”); //34 ++(prefix and postfix) , --(prefix and postfix) are the increment and decrement operators which operate only on one operand. 24 -May-21 Basics of Java - I 32
Operators Conditional operator : The conditional operator is a ternary operator (it has three operands) and is used to evaluate boolean expressions, much like an if statement boolean result=3>4? true: (1<2? true: false); //true Logical operators: There are six logical operators (&, |, ^, !, &&, and ||) && and || are known as shortcut logical operators because they check the left side of the operation first (operand one). 24 -May-21 Basics of Java - I 33
Java 1. 7 new features • • • Using strings in switch statements Automatic resource management : Resources such as Connections, Files, Input/Out. Streams, etc. should be closed manually by the developer by writing bog-standard code. However, Java 7 has introduced another cool feature to manage the resources automatically. It is simple in operation, too. All we have to do is declare the resources in the try block. Improved exception handling : 24 -May-21 Basics of Java - I 34
Bibliography • • Complete Reference Java SCJP Exam 6 http: //docs. oracle. com/ www. javaranch. com/ 24 -May-21 Basics of Java - I 35
Questions? 24 -May-21 Basics of Java - I 36
Thank You 24 -May-21 Basics of Java - I 37
- Slides: 37