Sunteți pe pagina 1din 9

Java Revision

Package provides a naming context for classes and interfaces. (Diff. Package & Interface) Packages can be used as naming context, to manage related classes and interfaces in single API unit. Java.lang is always default-imported package. Field variables are variables that are declared as members of classes. Local variables, also called as automatic variable, are declared related a method, constructor. Default package- no name. Identifiers begin with a Unicode letter, underscore (_), or dollar sign ( $ ). Variables declared, as primitive types are not references to objects. Primitive Data types: int, short, long, double, char, float, Boolean, byte. Boolean T/F bit 7 7 Byte : -(2 ) to 2 -1 byte char: 0 to 216 1 word short: 215 to 2 15 1 word int: - 231 to 231 1 Dword long: -263 to 263-1 Qword Compilation Unit: java source code file Classes define variables, which provide named access to data, methods, which perform actions consisting of operation on data and, constructors, which create instance of classes, referred as objects. Access identifiers and static words can be interchanged in order. The args array is used to collect command-line arguments. Numeric promotion: converting the values of the operands to a common type. The operands are converted to data type, which has maximum storage space. (Double>float>long>int). This is done in both unary and binary operators. This means byte, char, short are converted to int. Division by 0: if int, then ArithmaticExpression is thrown. If +ve float, results in POSITIVE_INFINITY, if ve float, NEGATIVE_INFINITY. Overflow, larger value than max capacity. Underflow when value less than minimum capacity. Java handles this by discarding high-order bytes that wont fit in to number of bytes allowable size. While executing an expression, first, numerical promotion is done, then the expression is executed, and again the result is converted in the destination type.

Equal: == is not equals. == compares the reference location and equals compares the actual value. String s1,s2 will reference to different memory locations, so == operator will always return false. The values in s1,s2 may be same. InstanceOf operator is binary operator, that determines whether an object reference ( left operand) is instance of class, interface, or array type specified by the right hand operand. RHS is subclass of LHS class, or RHS implements the LHS interface, or RHS is array data type of LHS array. Java supports 2 types of logical operators: Boolean & Short-circuit operators. Short-circuit operators execute in different way, it first evaluates first of its operands (expressions), if && is used and result of first is true, then second is evaluated and its value is returned, else execution of second is skipped. If || is used, and result of 1 st is true, true is returned without executing 2nd , but is false then the result of 2nd is returned. Assignment operators: The if left hand is class then right should be subclass or null. If left is interface then right must me sub-interface, subclass that implements that interface or null. It is right associative. I.e. a = b = c. will be a=(b=c) first. Cast operator: Used to convert numeric values from one numeric type to another or to change an object reference to a compatible type, assigning the compiler-incompatible types. Widening conversion is conversion from a smaller numeric type to larger numeric type. (type of Boxing in .NET) Narrowing conversion is conversion from larger to smaller numeric type, this requires explicit type casting. Widening is done in numeric promotion. A reference to any object can be cast into a reference to an object of class Object. (type of UnBoxing in .NET) Ternary operator: Conditional operators: ?: Ope1?Ope2:Ope3; Execute Ope2 if Ope1 is true, else Ope3. Ope1 should be Boolean expression. Variable Declarations: used to identify the type associated with a variable. When a variable is declared as a primitive data type, the variables declaration identifies the type of primitive values that may be stored by the variable. Java supports 2 types of variable declarations: Field & Local(Automatic) Field: declared as members of a class. Automatic, local: declared as function specific.

Field Variables: Valid modifiers: access: public, protected, private Special: final, static, transient, volatile Array: when declared, values automatically initialized to data type defaults. Words this and super refers to current instance. this should not be used in static methods. Why? As this refers to object, static methods are not object specific. Local variable modifiers: only final. Final Modifier: after assigning final, the value of variable can not be changed. Field Vs Local: scope: class instance Vs Method. Passing arguments to methods: only copy of variables is done, and passed to methods. Allowed modifiers to a method: Private, public, protected, default( package access) Package access is considered as friend in C++, not exactly but kind of. Encapsulation allows classes to be restricted to a well-defined interface. Modifier order does not affect the object\method properties. Neither abstract methods or abstract classes can be declared as final. If class extends an abstract class then it must implement its methods or be declared as abstract. Native methods cannot be declared as abstract. Native methods are used to access the code written in language other than java. The semicolon after native method declaration acts as abstract. Non-static methods can access both static and non-static variables, but static methods can access only static members. Static variables of a class are not serialized. Synchronized is used to control the access a variable shared between threads. Transient modifier indicates that variable can not be serialized. Transient variable cannot be declared as static or final. Volatile is used to indicate the variable is shared by different processors, in case of multiprocessor platform, or a variable shared by many variables without synchronization.

Finally is always executed, no matter the exception is thrown or not, except there is no statement of System.exit in try or catch block. Java implements all aspects of OO: object reuse, class hierarchy, inheritance, encapsulation, polymorphism, and dynamic binding. Classification is a way that we organize knowledge in general. Except Multiple Inheritance. Encapsulation is the way of binding, the data and the methods that manipulate this data, under one common name or package, i.e. class, object. This also protects members to be safe from external handling. Late Binding: The way in which the definition of an object is decided run-time. Over net, if we dont know the type of incoming data object, then this kind of binding that is done by run-time is called as late-binding, or dynamic binding. This is truly OO concept. Inner classes are the special classes those are declared with in context of an other class, interface, or statement block. Class Modifiers: public, final, abstract, default (package access). If there is no extends class, then java.lang.Object as default. A class can have only one parent. Strict Subclass: A class that is subclass of a class, but except the parent itself. A class is considered as subclass of itself. The is a relationship defines subclass relationship, and has a defines field relationship. A circle IS A shape, and HAS A radius value, and HAS A center. A man IS A Human Being and man HAS A head. Constructors are not inherited. Each class must define its own constructors else compiler will define a constructor that will be an empty body. If we dont want to instantiate an object at the point of declaration, then just define constructors as private. If this() and super() appears in method body, then these must the first sentences of the body, but should not use both in one body. A class cannot be extended if it does not define any accessible i.e. public constructor. Remedy, provide factory method in parent class. Interface is a collection of methods that is implemented by a class. Modifier: public, abstract (theoretically all interfaces are abstract by nature.) Any variables defined in interface become final implicitly.

Non-static inner classes: Closely assigned to outer class. Instance of an inner cannot be declared without instantiating out class. So to instantiate inner class, we have to access the object of outer class in new statement. Variables defined in outer class are accessible by inner class, but static inner class can access only static members. Static Inner class: As the inner class is static, there is no need to instantiate outer class for accessing the inner class. Static blocks are considered as top-level blocks in java. Local Inner Class: when inner class is defined in scope of a method. Anonymous Classes: Method to declare classes on the spot. They are declared with the name of class they extend or interface that they implements. No extends or implements modifiers are allowed. new SuperClassName(arguments) { //class body } new interfacename { // methods } Anonymous classes do not have constructors. Arguments are passed to super class constructor, are optional. These are considered as subclass of object. Use: Java does not supports operator overloading. But it actually implements this with +, which is used with arithmetic and string operators. Overriding is defining the function with same name, arguments, return type but only difference that this is hierarchical issue. Overloading is done within same class, and overriding is done down the hierarchy. Both, overriding and overloading, are forms of polymorphism. Overloading is always static while overriding can be static as well as dynamic. The overriding method and overridden method must have exactly same signature. If only return type differs, else there will be run-time conflict. Also the modifier of the both methods must be same or overriding method should not have more restrictive access modifier. The exceptions thrown by overriding method should be same or sub-class of exception thrown by overridden method. If overridden method was public, then overriding method also should be public. If previous was protected then current should be at least protected, can be public, but

cannot be private. Since private methods are not inherited, there will not be issue about it. Threads in Java: Process is a operating system object that is created when a program is executed. Threads are not completely a new process, they are just a piece of code that is in the same program but executing concurrently. Threads share the resources of the parent process. The object class supports multithreading, through notify(), notifyAll(), and wait() methods, ThreadGroup class. Multithreading is done in Java by 2 methods, 1st override run() method in an extended class from Thread class, or implementing run() method in a class which is implementing the Runnable interface. A thread is started by calling start() method. Thread States are Running, waiting, stopped. Thread priority is an integer value between MIN_PRIORITY and MAX_PRIORITY, ( from 10 to 0). Normally, a thread is assigned to default value NORM_PRIORITY (5). Windows, Mac implementations of java, use Time Slicing, while UNIX, Solaris follow preemptive method, for scheduling. The simplest way to put a thread in ready state is to invoke yield() method. It is static method in Thread class. A thread can enter in waiting state by invoking sleep() method. It returns when either time is expired or interrupt() method called by another thread. Class lock is lock that is acquired by classs Class object. When an object is accessed under synchronized clause, then system tries to acquire lock before it is accessed and also automatically lock is released when object exits synchronized block, or wait() method is called. While acquiring a lock the object goes in temporary waiting state until gets lock permission. These lock are generally exclusive locks. Java.lang: Object, Class, and Package classes. Java fallows first-class method. Object class, default super class of all classes. It does not provide any variables, but some methods such as equals(), hashcode(), clone(), getClass(), toString(), finalize(), wait(), notify(), etc. Class class: Provides over 30 methods. It does not have constructor. Objects of this class are called as class descriptors, automatically created by JVM. getName(), getSuperClass(), isInterface(), getInterfaces(), newInstance(), getClassLoader(), etc. Package class: helps to retrieve information about the packages. Static getPackage(), getAllPackages(), isCompatibleWith(). System Class: implements stdin, stdout, stderr and supplies methods for it. SetIn(), setout(), setErr().

Wrapped classes: These are the classes those have furnished primitive data types, to provide more methods to work around them, such as data conversion, value testing, hash codes, etc. These are Boolean, Character, Byte, Short, Integer, Long, Double, Float, Number. Java.util: It is collection of classes as, Vector, Stack, BitSet, Dictionary, HashTable, Properties, and Enumeration interface. Vector: Grow able array implementation. Dictionary, Hash-Table, Properties classes three generations of classes that implement the capability to provide key-based data storage and retrieval. Abstract Toolkit Windowing: Event Model: The events can be handled in 2 ways: directly over-riding handleEvent() method or using propagated event methods. Over-riding the method handleEvent(), needs to check the event constants that are provided by event models. These are Window Events, Keyboard Events, Mouse Events, Scrollbar events, List Events, and Action Events. In the propagated events, over-riding the methods of specific events can be done. The event modifiers give the additional information about the events. For example, which mouse button, or key triggered the event. The Event Constants: Window Event Constants WINDOW_DESTROY WINDOW_EXPOSE WINDOW_ICONIFY WINDOW_DEICONIFY WINDOW_MOVED. Keyboard Event Constants KEY_PRESS KEY_RELEASE KEY_ACTION KEY_ACTION_RELEASE. Mouse Event Constants MOUSE_DOWN MOUSE_UP MOUSE_MOVE MOUSE_ENTER MOUSE_EXIT MOUSE_DRAG. Scrollbar Events Constants - SCROLL_LINE_UP

SCROLL_LINE_DOWN SCROLL_PAGE_UP SCROLL_PAGE_DOWN SCROLL_ABSOLUE

List Events Constants: - LIST_SELECT - LIST_DEESLECT Action Event Constants: - ACTION_EVENT - LOAD_FILE - SAVE_FILE - GOT_FOCUS - LOST_FOLUS Over-riding Propagated Event Handlers: The methods that handle a propagated event return a Boolean value, which indicates that the event has been completely handled or not. The true return value represents, that the event was handled properly, and no need to propagate to containers handler. While the false value indicates, that the event should be forwarded to containers event handler. The event is propagated from leaf object class to super object class. Using clickCount field in event class can sense the double click of mouse. The unique characteristic of the AWT components is that only button, check box, TextField, MenuItem and List components generate events that are routed through the ComponentAction method. The TextField generates action event only after a carriage return. An action event is generated when button, check box, choice, and menu are selected or clicked, while an action event is generated by double clicking an item in List. All applets involving the AWT are event Java has three kinds of variables namely, the instance variable, the local variable and the class variable. The following are the types of operators: Arithmetic operators, Assignment operators, Increment & Decrement operators, Logical operators, OR(|), AND(&), XOR(^) AND NOT(~). Bitwise operators, Comparison/Relational operators and Conditional operators . The conditional operator is otherwise known as the ternary operator.

Character literals are stored as unicode characters. 1) What are the programming constructs? Ans: a) Sequential b) Selection -- if and switch statements c) Iteration -- for loop, while loop and do-while loop Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method's signature is a combination of the first three parts mentioned above. getClass( ) method can be used to find out what class the belongs to. This class is defined in the object class and is available to all objects.

Thinking Java
Why has object-oriented programming had such a sweeping impact on the software development community? Object-oriented programming appeals at multiple levels. For managers, it promises faster and cheaper development and maintenance. For analysts and designers, the modeling process becomes simpler and produces a clear, manageable design. For programmers, the elegance and clarity of the object model and the power of object-oriented tools and libraries makes programming a much more pleasant task, and programmers experience an increase in productivity. Everybody wins, it would seem.

S-ar putea să vă placă și