core java

February 7, 2017 | Author: Brundaban Mohapatra | Category: N/A
Share Embed Donate


Short Description

Download core java...

Description

1

Contents

Chapter-1: Object Oriented Programming Fundamentals Chapter-2: Evolution of java programming language Chapter-3: Basic elements of java Chapter-4: Operators in java Chapter-5: Conditional statements and loops Chapter-6: Class fundamentals Chapter-7: Object reference Chapter-8: Array in java Chapter-9: Inheritance Chapter-10: Inner class Chapter-11: Exception Handling Chapter-12: Package Chapter-13: JAR File Chapter-14: String Chapter-15: StringBuffer Chapter-16: Wrapper class Chapter-17: Taking the input from keyboard Chapter-18: Java Native Interface Chapter-19: Multithreading Chapter-20: Generics

2

Chapter-21: Files and Streams Chapter-22: Exploring java.lang package Chapter-23: java.util package(part-I):Collection Framework Chapter-24: java.util package(part-II) Chapter-25:The Applets Chapter-26:The java.awt package Chapter-27:Java Foundation classes Chapter-28:The java.net package Chapter-29:The java.sql package Chapter-30:Brain Teasers

3

Chapter1:

Object oriented programming fundamentals While teaching new comers in java the first question that comes in my mind to ask is “What is object”. All most all the new comer in java knows C++. So the question is quite obvious & I expect to get a nice answer. The answer usually is: “OBJECT IS AN INSTANCE OF A CLASS” which is absolutely correct. Then, the next question from my side is “WHAT EXACTLY A CLASS IS & CAN YOU GIVE ME A REAL LIFE EXAMPLE OF AN OBJECT” & surprisingly most of the time no satisfactory answers. They know the definition, but they have not visualized concept of object. Before migrating from traditional programming world to OOP (Object Oriented Programming) world, one has to have a strong fundamental concept of object. Object is the instance of a class. Class is a template, i.e. it contains various characteristics or attributes which were satisfied by the object belonging to it, e.g. if human is a class, then SAM KOOL (Obliviously Name of a MAN!!) is an object of human class.

4

Object is the entity which communicates with the environment. Class is an abstract concept. It is merely a collection of attributes & characteristics. Object gives life to those characteristics present in the class, & that is why object can communicate with the surrounding. Since class is a template it doesn‟t have memory but, the object has. Class template combines data and functions or methods to manipulate those data. The data present in an object can only be manipulated by the methods or functions belonging to that object.

Overview of Object Oriented Programming Way back in 1960s OOP gives its first hint of birth. In traditional language like C, FORTRAN logic pays the highest priority. One question I would like to ask reader whether the logic should have highest priority in every aspect of programming. My answer is no, because logic always whirls around data. Data should always enjoy highest priority. Programmer should concentrate on data security & integrity while developing the software. Procedural programming language does not have the tools to encapsulate the data to prevent it to be accessed by any random methods. Along with this fact code reusability is another issue that is not achieved by procedural programming language. With the increase of complexity of software, security of data, code reusability, polymorphic behavior of programs & communication among various entities has to be addressed perfectly, but traditional programming language has no answer at all. Then it comes Simula, the first OOP language has answers to these issues. It introduces the concept of class, object, method, virtual methods, inheritance & polymorphism. Object Oriented Programming is simply a collection of objects where objects interact with each other through the methods that have been embedded in them. You can think of a object as a self sufficient machine. What I mean to convey here is that like a machine object has concretely defined way to take input, it has separate component to process the input & has completely unique component to produce the output. Each object has unique identification & existence. In Object oriented Programming the data & the operations to access & manipulate the data are closely entangled to each other.

5

Quarks of OOP Class: class is an abstract concept. It is simply a template. When a class is instantiated object is created. Class contains data & methods to manipulate the data. Class is simply a blueprint of a thing. In programming prospective class encapsulate various primitive data types as well as user defined data types.

6

Object Object is the instance of a class. It is a bundle of variables and related methods. The basic idea behind an object is the simulation of data & methods to manipulate them. Method Methods are the entities through which objects interacts with the external environment. Whatever object is going do, can only be done through the methods. Methods are concretely entangled with a particular object. Let me explain it through an example. Assume that MyClass is a user defined class Example-1 Class MyClass { Data_1; Data_2; Method_to_manipulate_data_1() { Required codes } }; If o1 & o2 are the two objects of MyClass. o2 cannot manipulate its Data_1 through the use of Method_to_manipulat_data_1() of o1 just like you cannot eat for yourself through your friends mouth.

7

Message passing The process by which objects communicate with each Obliviously communication can only be done through methods.

other.

Abstraction Abstraction means simplification complex reality of a problem. In lay man language abstraction means, “HIDING THE DETAILS”. Programmer hides the complexity of the program from the end user. End users only have the methods or functions to interact with the data without knowing how the manipulation is done. Consider the case of a cell phone. Cell phone users know only about various functionalities available in the phone without knowing how they are implemented. Encapsulation: Encapsulation means binding both code and data together. Code implies the methods or functions that manipulate the data. This technique protects the data from outside interference & behaves as protective wrapper. User can interact with the data through the methods that are available in the specific object. Apart from those available methods it is not possible for user to manipulate the data. But, in case of structured programming language like C data can be manipulated by any function which decreases the security & integrity of data e.g.

8

Example-2

struct xxx { int a; }; main( ) { struct xxx x; void fun1(struct xxx*); x.a=9; fun1(&x); printf(“%d”,x.a); } void fun1(struct xxx *ptr) { ptr->a=10; } The output is 10. Structured programming language gives a mean to handle the real world data. But, any function can manipulate the data belonging to any structure variable as shown in the above example. Encapsulation prevents these entire unsecured mean to modify & access the data. Each method has well defined task & they are strongly entangled with the corresponding object. Encapsulation also abstracts the complexity involve in a class from the end user. Inheritance: Inheritance is a technique by which an object acquires the feature of other object along with its own features. The object from which

9

property is acquired is known as parent object & the object which acquires the property is known as child object. It depends upon the programmer to decide what the properties are that has to be inherited from parent to child. In java the parent class is known as super class & the child class is known as sub class. Sub class can add new feature to it along with the inherited properties. Inheritance facilitates code reusability.

Why inheritance is required? Suppose you are developing software for market complex whose task is to show the viewer what are the various items available. If you are developing this project in C then you are going to declare a structure

Example-3: struct xxx{

10

char item1_name[20]; char item2_name[20]; char item3_name[20]; char item4_name[20]; char item5_name[20]; };

You have designed the functions to show these items to the customers. In latter stage if some new item is introduced than you have to again change the structure template. But, in case of OOP just you have to create the sub class or child class, then all the existing attributes are inherited to the sub class & you just add the new items to it. Great!! Job is over & quite simple also. By creating the base class you can add new items in future to the existing class. In this way you can also add new methods to the sub-class to improve functionality & accessibility.

Polymorphism: Polymorphism in OOP is the technique through which when a method is called invocation of appropriate method is performed by the appropriate type specification. Only name is not enough, argument type is important along with the contents of the invoking object. In lay man language polymorphism means one name many forms. In OOP terminology polymorphism implies one method performing many tasks. A novice object oriented programmer definitely going to ask “Do the programmers really have scarcity of name?”, again lets go through an example. In the early version of cell phones one can only send text message. For sending the messages assume the function is send which has the following signature. return_acknowledgement send(text_data,receiver_name); All the cell-phone users are quite comfortable with send function. But when multimedia messaging technique is discovered, send function need to be

11

redefined. In traditional programming technique one can not have same named two or more function. One solution is that provide another function a totally new one to send mms. Again this is awful because one function to send text message and another one for mms. So the best solution to this situation is the use of polymorphism through which we can have another send function to send mms. In OOP a method is recognized through its entire signature. Entire signature includes name of the function along with the parameters it is taking. return_acknowledgement send (mms_data,receiver_name); These two functions are entirely different, see the signature. Great solution!!!.Finally Novice Object Oriented programmer got the reason for the birth Object Oriented Programming. Conclusion: Logic is highly important for programming. But for which we have to program & answer is data. Procedural language helps you to develop logic but remain silent when it comes for the security & integrity of data. With the evolution of distributed application, data is not stationary. What do you think when sends some thing in internet how it goes? Not in raw data format but in the form of objects. OOP provides a wrapper to the data which is almost impossible to penetrate.

12

Chapter: 2

Evolution of java programming language. Way back in 1991 James Gosling who took his first step in the development of Java programming language. Previously java was called as Oak, (yes! Name of a tree). Then the name Green comes finally ended with Java. Java is developed by SUN Microsystem. Most of its syntax has been derived from C/C++. SUN released the 1st JDK1.0 in 1995. It promises to the programmer as a platform independent language. The language is syntactically similar to C and C++ but works on a higher abstraction level as compared to them. First Java 1.0 was released by Sun Microsystem in 1995. "Write Once, Run Anywhere" (WORA) was the tagline for java 1.0.It was secure and allowed network and file-access restrictions. Very soon java got popular due to which java 1.2 is released in December 1998.After the success of java 1.2 sun launched the new and different versions of java for different purposes,e.g J2EE is for enterprise applications i.e for server side programming , J2ME for mobile applications , J2SE is for Standard Edition. Finally java evolved as: A simple and object oriented language. A robust and secure language. A architecture neutral and portable language. A language with high performance rate. A language which is interpreted, multi threaded, and dynamic. Portability is one of the most important characteristics , it means the compile byte-codes i.e. the class file written in the Java language runs similarly independent of the system hardware and operating system i.e write a code once, compile it once, and run it anywhere. The platform independent feature of java is achieved by compiling the java source code not to a machine code but to a intermediate code called byte codes. Byte codes are collection of instructions for java virtual machine which are later interpreted to native codes. Java provides a reach set library functions for graphics designing, applet programs, GUI design through swing, remote method invocation & for multi threading applications. Some virtual machine implements techniques for the conversion java source code to native machine codes. In Linux gcj compiler converts java source code to native machine codes resulting faster execution of java programs. When java file is compiled class file is created. Class file is merely a collection of byte-codes. Byte codes are then interpreted by JVM. Interpretation is quite slow. Therefore the execution of java program is slow as compared to executable native codes. This is great performance issue for java program. Over the years effort has given for the increase the execution of java program. Just In Time compiler is a solution to improve the performance. By the implementation of JIT compiler when for the first time the byte codes are translated to native codes, it caches it. There is another technique in which java source code is directly converted to machine readable native codes. This is done by AOT (Ahead Of Time) compiler. This technique increases the performance because native code executes faster than byte codes. GCJ compiler available in Linux is a AOT compiler. AOT compilation disables the most important feature in java, i.e. the platform independence feature. I have seen most of the new comers in java, treat it as a language having more functionality, abstraction & a lot of similarity with C/C++. This because of large set

13 of keywords & operators are matched with keywords & operators of C/C++. But, this is not true at all. Java survives & grows in this world because of its own unique identity. Let me address on those issues.  Java has neither preprocessor directive nor header files. Predefined methods & classes are available to java through the packages. Packages are collection of class files.  All the methods, variables & all sorts of codes always reside within the class template.  Through wrapper class java provides an object oriented view of primitive data type like integer, float, byte, char, boolean etc. This wrapper class package has enabled java as a complete object oriented programming language.  Java does not support global variables. In C++ global variables does not belong to a particular class & can be modified by any function. This is the unsecure mean of data manipulation. Java has restricted this controversial issue by not supporting the global variable.  Memory management is not provided to the programmer. Unused data is deleted from memory by the invocation of the demon thread named garbage collector. Memory leak problem is quite optimized in java.  Non existence of memory pointers. Memory pointers are always threat to any automated system. These are used to break the security & can crash a system. Not having these memory pointers is an advantage to java.  During any assignment operation java strictly follows type checking. Due to this feature precession loss or data loss is minimal in java.  Java strictly follows type safety. Programmer can not arbitrarily cast on datatype to another one.  Local variables in side a method can be declared when they are needed.  Implementation of floating point variables is platform dependent. There fore java provides the keyword strictfp to maintain its platform independent property.  Union provides memory over lapping feature which is discarded in java.  No typdef to create alias of data-type.  Array index out of bound is checked in java to prevent the unauthorized manipulation of memory. WHY JAVA ?  Platform Independence The Write-Once-Run-Anywhere (Java Virtual Machine for different platforms usually required), concept is strictly followed.  Introduction of wrapper class makes java a complete object oriented programming language.  When a java source file is compiled, class file is generated which is collection of byte-codes. These byte-codes are latter interpreted to native codes by JVM. Byte-codes are portable.  Byte codes are least affected by virus as compared to executable files. If it is affected, then JVM recognize then & never allow them to be executed.  Built in support for exception handling.  Built in support for multi threading application development.

14    

Java provides communication with C/C++ source codes through Java Native Interface. By the use of Compiler class java source code can be compiled to native machine codes. Package like java.lang.SecurityManager provides permission to the object to have an access on variables, files & other resources. Built in support for networking.

Virtual Machine When you read the java language, java virtual machine is quite a familiar term. But, what is a virtual machine? The philosophy behind virtual machine is to abstract the system hardware of a single computer in to several different virtual systems such that it makes the user to feel that different environment or platform is implemented on a single system.

15 Diagram:

Diagram-2

16

System that implement the virtual machine. Each virtual machine provides different environment or platform to the user. According to the platform provided, only a particular set of processes can be executed in a particular virtual machine. Processes those are executed in Virtual Machine-1 cannot be executed in Virtual Machine-2. Implicitly these virtual machine perform appropriate system call for the execution of different processes. When different processes are running, virtual machine makes the end user to feel that different processes are running not only in different platform, but also in different CPUs. This illusion is created by the implementation of different CPU scheduling algorithm by the underlying OS.

17 The Java Virtual Machine. JVM consists of following components shown in the diagram.

These components are abstract in nature. It completely depend upon the designer to develop these components. Class loader Sub System: when a java file is compiled class file is generated. When we invoke the class file for execution class loader subsystem is called by Java Virtual Machine to load the class file into JVM memory space. The task of Class loader sub system is to load the classes & interfaces in the memory. In Java Virtual Machine there are two types of loader is available. A boot strap loader & other one is user defined class loader. The job of the class loader sub-system is not only to load the class file but also it checks correctness of the loaded class, allocates required memory to static variables (static variables are explained in class fundamental). The class loader sub-system performs its task in sequential way 1st: Loading of class file. 2nd: Checks the correctness of class file. If you have read the class file by notepad or word-pad in a windows system, then that class file cannot be executed. For this behavior class

18 loader sub-system is responsible. 3rd: allocates memory to static variables. Static variables are otherwise known as class variables. They are the property of classes rather than the property of objects. 4th: transformation of symbolic reference into direct reference. 5th: sets default value of all static variables. Method Area: it is a logical memory component of JVM. This logical section of memory holds the information about classes & interfaces. Static variables are treated as class variable, because they take memory from method area. The size of the method area is not fixed. It shrinks & expands according to the size of the application. Heap: In java when an object or array is created, memory is allocated to them from heap. The Java virtual machine through the use of new operator allocates memory from the heap for a new object. Java does not provide any technique to the programmer to free the memory that has been allocated by new operator. Once memory is allocated from heap to an object or array, programmer cannot free the memory. The JVM has demon thread known as Garbage Collector whose task is to free those objects from heap whose reference is not alive in stack. Java stacks: Method codes are stored inside method area. When method starts execution, it needs memory because of the local variables & the arguments it has taken. For this purpose java stack is there. All the local variables & the arguments method have taken acquires memory from stack. PC registers: It keeps track of the sequence of execution of the program. PC registers or Program Counter registers holds the address of the instruction to be executed next. Native method stacks: When a java application invokes a native method, that application is not going to use Java stack only, rather it uses the native method stack also for the execution of native methods. Native methods are generally in C/C++ & executed in side native method stack. The libraries required for the execution of native methods are available to the Java Virtual Machine through Java Native Interface. Execution Engine: Execution engine is there to generate & execute the java byte code. It contains an interpreter & Just In Time Compiler. Java Run-time Environment Byte-Codes Byte code is the unique characteristic property of java programming language. It is something like a normal text file. That‟s why it cannot be affected by virus. You can say that it is a intermediate human readable source & machine readable source. Byte codes are plat form independent & that‟s why JVM is plat form dependent to make the java programming as platform independent. Just like C source codes are portable, byte codes are portable. The cost of platform independence behavior of byte codes is paid by its slower execution speed when it is compared with execution of native codes even in just in time compiler. How to Construct the FAMOUS Hello, World!!! Program in JAVA Don‟t get surprised with the name it‟s just our first program in java that we are going to write. Example public class hello { public static void main(String ag[]) { System.out.println(“Hello, World!!!”);

19

}

}

Output: Hello, World!!!

file.

1: Now in the above program we have declared the class containing the main method as public so we have to save it in a file which has the same name as that of class name. e.g. hello.java 2: after the file is saved we have to compile the hello.java file using the javac command. e.g. javac hello.java 3: After compilation hello.class file will be generated. Then to get the output we have to run the .class file using java command. e.g.: java hello note : if we are not declaring the class containing the main method as public , then we can save the file in any name. But when we will compile the .java file then the name of the class file generated will be same to the name of the class containing the main method. To get the output we have to run the program using the name of the .class

Example-2 xyz.java class hello { public static void main (String ag []) { System.out.println(“Hello”); } } Output: Hello To get the output: 1: javac xyz.java 2: the class file will be generated in name of hello.class. Now run it with the java command to get the output. 3: java hello Restrictions:- 1:-In java top level class is declared either through public or no access modifier. 2:-When the class is declared through public access modifier class name must be same as the file name. 3:-When the class is declared through no access modifier class name and file name may same or may not

20

CHAPTER 3:

Basic Elements of JAVA 1. IDENTIFIERS Identifier are the set of rules for giving the names of the variables of primitive data types, methods, user defined classes, interfaces and reference variables of classes. Java is said to be strongly typed language, means you must declare the identifier & initialize it before it is used. Identifiers should not begin with a number and an identifier should not contain these following characters ; {} () // [] * \ + , ; “” „‟ # % ! ^.

21

Like C/C++ (dollar)$ &(underscore) _ is allowed in java.

KEYWORDS

The table below lists the keywords, or reserved words, as of Java 5.0. We will discuss the meaning and function of most of them during this course.

KEYWORDS abstract

assert

boolean

break byte case

DESCRIPTION it is used to declare a class or method to be abstract. An abstract method does not contain its body. Abstarct methods only have the declaration, but their body is defined else where. In interface the methods are by default public & abstract which has to be defined concretely where these interfaces are implemented. This keyword was introduced in J2SE 1.4. This keyword is used in the program to check whether a specified condition is true or not. If the condition is true then the program execute in a normal way otherwise an AssertionError is thrown. Boolean is a primitive data type in java. It can have either true or false value. Internally Boolean is represented as integral value in JVM. When Boolean variable is use as instance or static variable its default vaue is false. When ever a condition checking is done in java, Boolean value is returned by the condition checking operator. Size of a Boolean variable is 8 bit. Break keyword is used in loops & switch case. It is particularly used to break the normal flow of the program. Byte is a primitive data type in java. Its size is 1byte or 8 bit. Default vale of byte variable when it is used as instance variable or static variable is zero. The case keyword is used to create individual cases in a switch statement. Case clause preceded with integral constant & enum members. In place integer constant you can have character constants and bytes since they are auto converted to integer.

22

catch

char class const continue

default

do

This is a component of exception handling mechanism. Always follows the try block to catch the exception object thrown from catch block. It is a primitive data type in java. Unlike c/c++ it is of 16 bit used to hold the Unicode character. Class is the key word through which programmer defines the user defined class template. const keyword is not available to the programmer. When continue keyword is encountered the control jumps to the condition checking part of do, do-while loop & the increment part of for loop . Continue statement can be followed with a level name to resume execution from the specified level name. The default is an optional component of switch case. When no condition is satisfied default case is executed in switch case. Solely do has no existence. It always entangled with while o form the do-while loop. It is a primitive data type in java of 64 bit used to store real numbers.

double else

enum extends false final

finally

float

It is used along with if statement following the if block. Used for condition checking. When if part is not executed control jumps to else part. Solely else has no existance. In an if-else statement else part is optional. JDK 1.5 has introduces this key word used to create constant. Enum is a class in java. Extend key word is used to support inheritance in java A boolean constant.. Final keyword is used in case of variables to create constants. Where used in case of class, that class cannot be inherited. When used in case of methods, that method cannot be overridden. It is a component of exception handling in java. whenever try block is executed , it is mandatory that the codes inside the catch block has to be executed. This keyword is used to store real numbers. Its size is 32 bit.

23

for Goto If implements import instanceof int

interface

long native new null package private

protected public return short static

It is used to create looping statement. This keyword is not available to the java programmer. It is used for condition checking purpose It is used to inherit multiple number of interfaces It is used to import existing packages. Packages are the collection of class files. It is a binary operator used to determine the parent child relationship between two objects. It is used to store the natural numbers. It‟s size is 4 bytes

Interface is used to support multiple inheritance in java. By default all the methods declared are public and abstract. To use the methods declared inside a interface u have to override it in the child class. It is used to store integral values . it‟s size is 8 bytes Like abstract method the body of native method is defined elsewhere in foreign language. Used to create an object. It is a operator. A reference literal value. Package is a collection of class files. Package keyword is used to declare a package. It is a access modifier. When an entity inside a class is declared as private it cannot be inherited to it‟s child class. Private variables are only accessed inside the class. It is a access specifier. Protected entities are accessed out side the package through inheritance. It is an access specifier. Public variables can be accessed from anywhere. Used to return control from method along with a value. Primitive data type in java. It is of 8 bit size. Static keyword is associate with method and constructor. Static variables are treated as class variable. Static entities are accessed through class name.

24

strictfp super

Floating point numbers are stored in the memory depending upon the platforms to have a platform independent representation of real numbers strictfp is used Used to acess the parent class element.

switch Switch case is used for condition checking. synchronized Synchronized keyword is used to avoid dead lock in thread. Synchronized keyword can be used for block or method. this This keyword is used by object to refer to itself. throw It is a component of java exception handling mechanism. Used throw an exception object.

throws transient true try void volatile

while

Throws keyword Is used along with the method signature. It used by the called method to throw the UnhandledException to the calling method. Transient keyword is used for those variables if programmer does not want to strew the variable persistently. A boolean constant. A component of exception handling mechanism of java. All the exception generated codes are embedded inside try block If a method does not return anything then void is used to denote its return type during the definition of method. Volatile is used along with a variable name. volatile variable changes their value without informing the JVM. System clock values are stored in volatile variable. While is a key word in java used for creating a loop.

25

Java Primitive Data Types Type

Values

Default

Size

Range

byte

Natural numbers

0

8 bits

-128 to 127

short

Natural numbers

0

16 bits

-32768 to 32767

int

Natural numbers

0

32 bits

-2147483648 to 2147483647

long

Natural numbers

0

64 bits

-9223372036854775808 to 9223372036854775807

32 bits

+/-1.4E-45 to +/3.4028235E+38, +/-infinity, +/-0, NAN

64 bits

+/-4.9E-324 to +/1.7976931348623157E+308, +/-infinity, +/-0, NaN

float

double

char

boolean

Real numbers

Real numbers

0.0

0.0

Unicode character \u0000 16 bits

true, false

false

1 bit used in 32 bit integer

\u0000 to \uFFFF

NA

26 Chapter-4

Operator

Since java maintains most of the syntactical similarity with C/C++ there fore most of the operators those are available in C/C++ are also available in java. In C++ operators can be overloaded by the programmer, but that is not possible in java. Java provides user a large set of operators to the programmers. Operators acts upon operand to provide desired output. e.g. a=b+c a,b,c are operand where as + and = are operators. There is an important aspect that has to be understood by the reader before getting in to the depth of the operators i.e. how the positive & negative integers are stored in memory. int x=12. x will be stored in the memory in the form of binary as 00000000 00000000 00000000 00001100 but things are became twisted when it comes for negative numbers. Negative numbers are stored in the form of two‟s complement & left most bit is treated as sign bit. When the value of sign bit is one, the number is a negative number. Let‟s have an example to clear the idea. Int x=-12. How to have two‟s complement form 1: convert the no. into binary leaving the negative sign. The binary form of 12 is 00000000 00000000 00000000 00001100 2: reverse the polarity of each bit to one‟s complement of the number 11111111 11111111 11111111 11110011 3: add 1 to have the final result that is two‟s complement 11111111 11111111 11111111 11110100 in this format -12 is stored in memory.

27

Operators available to the java programmer Type:1 (Unary Operators) +

Unary plus

-

Unary minus

++

Postfix increment increment

--

Postfix decrement

()

Casting operator

~

Bitwise inversion

!

Boolean complement operator

&

prefix

Unary Plus Operator & minus operator Unary plus & minus operator is used to represent positive & negative number. Programs below will give you a clear picture. I don‟t think explanations are required. Output in each program is simple & straight forward. class Demo { public static void main(String []args) { int x=12; System.out.print(-x); } } Output: -12

28 class Demo { public static void main(String[]args) { int x=12; System.out.print(+x); } } Output: 12

class Demo { public static void main(String[]args) { int x=12; System.out.print(-+x); } } Output: -12

class Demo { public static void main(String[]args) { int x=12; System.out.print(-(-x)); } } Output: 12

29

The postfix operator: class Demo { public static void main(String args[]) { int i=6; int j=i++; System.out.println(i); System.out.println(j); } } Output: 7 6 Explanation: Variable i is initialized to 6. Incase post fix increment operation use of the variable enjoys the highest priority where as increment is done in second phase. In the statement j=i++ 1st value of i i.e. 6 is assigned to j & then i is incremented to 7. Now you can think of why the output is 7 & 6. See another interesting behavior of post fix operation class Demo { public static void main(String args[]){ int i=6; i=i++;

30 System.out.println(i);

} } Output 6 Foxed dear!!! See I have already said in post fix operation use of the variable enjoys highest priority. In the above piece of code since assignment & increment is done over one variable the increment part is rejected because of its lower privilege. It‟s a rule. Similarly you can try for postfix decrement operator. Prefix operation class Demo { public static void main(String args[]){ int i=6; int j=++i; System.out.println(i); System.out.println(j); } } Output 7 7 In the above code I have used the pre fix increment operator. In this case increment enjoys the highest priority. So first value of i is incremented to 7 & then it is assigned to j.

31 class Demo { public static void main(String args[]){ int i=6; i=++i; System.out.println(i);

} } Output 7 Since increment enjoys the highest priority output is straight forward.

Cast Operator: (type) Casting is used to convert the value of one type to another. In other words casting is used to explicitly convert the value of one type to another. The result of cast is a new reference or a value. In java not only data types are casted but also object is casted. In java casting is of two types:  

Casting of primitive data types Casting of object type

Casting primitive types: Casting between primitive types allows explicitly convert one primitive data type into another. In java boolean data type cannot be casted to any data type. If you want to cast a smaller data type to a larger one then implicit casting is done in java.

32

The larger type provides more precision than the smaller type and hence no information is lost when the value is cast. When the larger type is assign to the smaller type then explicit cast must be required. See the diagram if the flow of data moves from opposite direction then explicit conversion is required. Example: public class Cast1 { public static void main(String args[]) { int i=10; long l=1; double d=3.4; byte b; b=(byte)i; // type casting System.out.println(b); i=(int)l;

// type casting

System.out.println(i); l=(long)d; // type casting System.out.println(l); }

33 } Output:10 1 3

Casting Object Instance of one class can be casted to instance of another class. Restriction of this principle is that class that is being casted must be related by inheritance. An instance of the sub class is casted when the super class instance is assign to the sub class object as the sub class contains all the information that the super class contains.

Example: class Test1 { void show() { System.out.println("Super Class"); } } class Test2 extends Test1 { void display() { System.out.println("Sub Class"); }

34 } public class Test { public static void main(String args[]) { Test1 t1=new Test1(); Test2 t2=(Test2)t1; t2.show(); t2.display(); } } Output:The program compiles successfully but at the runtime the program is terminated by Exception in thread “main” java.lang.ClassCastException

Bit wise inversion operator: (~) class Demo{ public static void main(String args[]) { int x=12; System.out.println(~x); }} Output : -13 Lets have a deeper look. Binary representation of x is 00000000 00000000 00000000 00001100 . When „~‟ operator is operated on x then 0 turns to 1 & 1 turns to 0. Hence the value of x is now

35 11111111 11111111 11111111 11110011 . The left most bit is the sign bit, since it is turned to 1 because of „~‟ operator, therefore the number becomes a negative number. All the negative numbers are stored in memory in the form of two‟s complement. Two‟s complement= 1‟s complement+1 To get the final out put 1st determine the one‟s complement of 111111111 11111111 11111111 11110011 which is(by converting 0 to 1 & 1 to 0) 10000000 00000000 00000000 00001100 here sign bit never change its polarity. Finally add 1 & the output is 10000000 00000000 00000000 00001101 Sign bit says it‟s a negative number & rest other says the final output is -13. Lets have another example class Demo{ public static void main(String args[]) { int x=-12; System.out.println(~x); }} Output: 11 Here the number is a negative number. It will be stored in the memory in two complement form. 11111111 11111111 11111111 11110100 When ~ is operated on these bits then the output will be 0000000 0000000 00000000 00001011. This is the binary form of 11 got it! Boolean complement operator As the name suggests this operator work only for Boolean data type, other wise compilation error will occour. class Demo {

36 public static void main(String[]args) { boolean x=true; System.out.print(!x); } } Output: false This operator just inverse the value of Boolean variable. Type 2 (Binary Operators) Arithmetic operators

+ ,-, *, /, %

Assignment operators

= ,+=,-=,*=,/=,%=,&=,^=,|=

Conditional operator

==,>=,,<

Bitwise operator

&,|,^

Shift operator

>>,>

instanceof operator

Short circuit operator

&&,||

37 Arithmetic operators Arithmetic operators are used to evaluate mathematical expressions. All the operators are simple & their behavior is straight forward. A novice programmer may be confused about the %, the modulus operator. This operator is used to determine the remainder when a division is performed. See the example class Demo { public static void main(String[]args) { int x=12; int y=5; x=x%y; System.out.print(x); } } Output: 2

Assignment operators An interesting fact about assignment operator: class Thread1 { public static void main(String args[]){ byte i=10; byte j=9; i=j+i; System.out.println(i); } }

38 Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to byte at demo.Thread1.main(Thread1.java:9) see the output is compilation error. Why ? because = operator accepts an integer variable in the left hand side when arithmetic operation is done. But, check the codes below class Thread1 { public static void main(String args[]){ byte i=10; byte j=9; i+=j; System.out.println(i); } } Output 19 The reason here is that += is overloaded to return appropriate type. Similarly other assignment operators like -=,*=,/=,%=,^=,&=,|= is over loaded. Remember that in assignment operator the left hand side value is assigned to right hand side only if the right hand side is a similar or bigger data-type with respect to left hand side. class Demo { public static void main(String[]args) { int x; byte y=5; x=y; System.out.print(x); }

39 } Output=5. Right hand side is an integer variable where as left hand side is a byte variable. Hence there is no problem in assignment. But, if the situation is reversed then compilation error will be generated. See the codes below.

class Demo { public static void main(String[]args) { byte x; int y=5; x=y; System.out.print(x); } } Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to byte at demo.Demo.main(Demo.java:9) Conditional Operators == equals to operator != Not equal to >Greater than <

Smaller than

>=greater than equals to j) System.out.println("equall"); else System.out.println("not equall");

if(i=j) System.out.println("equall"); else System.out.println("not equall");

if(i> >> Bitwise Unsigned Right Shift Lets have logic table of first four bit wise operators to have a primary idea, then we will go for codes. x

y

~x

~y

x&y x|y

x^y

0 0 1 1

0 1 0 1

1 1 0 0

1 0 1 0

0 0 0 1

0 1 1 0

0 1 1 1

Bitwise inversion operator is explained earlier in unary operator. Bitwise and operator ( & ) :

class Demo{ public static void main(String args[]) { int x=12; int y= 13; x=x&y; System.out.println(x); }}

43 Output : 12

Let‟s see what actually happens. See the truth table above, in case of AND (&) operation only 1 & 1 gives 1 else in all other cases results 0. In the above example x =12 will be stored in the memory as 00000000 00000000 00000000 00001100 y = 13 will be stored in the memory as 00000000 00000000 00000000 00001101 x =x&ywill be stored in the memory as 00000000 00000000 00000000 00001100 from above we can see that only in the 3rd bit and 4th bit of both 12 and 13 is 1 so by the & operation the value of 3rd and 4th bit will remain 1 else will remain 0. The result is the binary form of 12 & so is the output. Let‟s see what happens when the AND (&) operation is performed between a negative and a positive number class demo { public static void main(String ar[]) { int x = -12; int y = 13;

x= x & y;

System.out.println(x);

} } Output :

44 4 Here x is a negative number hence it will be stored in the memory in the form of twos complement. x =-12 will be stored in the memory as 11111111 11111111 11111111 11110100 y = 13will be stored in the memory as 00000000 00000000 00000000 00001101 x=x&y will be stored in the memory as 00000000 00000000 00000000 00000100 The sign bit of the resultant is 0, hence it is a positive number which is 4.

Bitwise OR(|)operator class Demo { public static void main(String[]args) { int x=12; int y=13; x=x|y; System.out.print(x); } } Output:13 The bit wise OR (|) operator checks individual bits of two different operand, if any bit of any of the operand is 1 then output is 1. X=12 its binary form is 00000000 00000000 00000000 00001100 Y=13 its binary form is 00000000 00000000 00000000 00001101 X=x|y out put is

00000000 00000000 00000000 00001101

The right most bit of 12 is 0 whwre as that of 13 is 1, hence the right most bit of result is 1 as shown above. The resultant is the binary form of 13 which is the desired output.

45 Lets have another example class Demo { public static void main(String[]args) { int x=-12; int y=13; x=x|y; System.out.print(x); } } Output: -3 Here x is a negative number hence it will be stored in the memory in the form of twos complement. X=-12 will be stored in the memory as 11111111 11111111 11111111 11110100 Y=13 will be stored in the memory as 00000000 00000000 00000000 00001101 X=x|y will be stored in the memory as 11111111 11111111 11111111 11111101 Clearly the resultant is a negative number since its sign bit is on. To get the final out put 1st determine the one‟s complement of 11111111 11111111 11111111 11111101which is (by converting 0 to 1 & 1 to 0) 10000000 00000000 00000000 00000010 here sign bit never change its polarity. Finally add 1 & the output is 10000000 00000000 00000000 00000011. So it is -3.

BITWISE XOR OPERATOR( ^ ): class demo1 { public static void main(String ar[]) {

46 int x = 12; int y = 13;

x= x ^ y;

System.out.println(x);

} } Output : 1 In XOR ( ^) operation when ever the value of a operand is equall to the value of the same bit of another operand then the the result will contain 0 in that bit else it will contain 0. In the above program x = 12 is stored in the memory as

00000000 00000000 00000000 00001100

x = 13 is stored in the memory as

00000000 00000000 00000000 00001101

x = x ^ y the output is

00000000 00000000 00000000 00000001

now we can see that all the bits in 12 and 13 contains same values except the right most bit which contains 0 incase of 12 and 1 incaze of 13. So the output will only have 1 in it‟s rightmost place all other bits will have the value 0.

Let‟s see what happens when one of the operands I positive and the other is negative class demo1 { public static void main(String ar[]) {

47 int x = -12; int y = 13;

x= x ^ y;

System.out.println(x);

} } Output : -7 In the above example x = -12 is stored in the memory as

11111111 11111111 11111111 11110100

y = 13

00000000 00000000 00000000 00001101

is stored in the memory as

x = x ^ y the output is

11111111 11111111 11111111 11111001

so we can see that -12 is stored in memory in it‟s two‟s complement form and 13 in it‟s usuall form. All the bits of the operands except the 2nd and the 3rd bit contain same value so the output will have all the values 1 except 2nd and 3rd bit ,which will contain 0. Because we have 1 in the highest bit so it is a negative number so to get the result we have to convert it into two‟s complement form which will be -7.



Below program shows how to swap two variables without using third variable through XOR ( ^ ) operator

class demo1 { public static void main(String ar[]) {

48 int x = 12 ; int y = 13 ;

System.out.println("value of x = "+x); System.out.println("value of y = "+y);

x=x^y; y=x^y; x=x^y;

System.out.println(" AFTER SWAPPING ");

System.out.println("value of x = "+x); System.out.println("value of y = "+y); } } Output :

value of x = 12 value of y = 13 AFTER SWAPPING value of x = 13 value of y = 12

Bitwise Shift Operator The bitwise Right Shift operator

49 The syntax for bitwise right shift opearator is given below. Variable

>> no.of shifts

Here variable represents the variable on which we want to carry out the shift operation., and no.of shifts represents the number of bits the value of the variable should be shifted. e.g

x >> 2 ;

Bitwise right shift operator shifts the bits of a number to a specified number of bits towars right preserving the signed bit. We can say that the empty bits are filled with the value of the highest order bit i.e for a positive number it is filled by 0 and for a negative number it is filled by 1.

class demo1 { public static void main(String ar[]) { int i = 5; i = i >> 2; System.out.println(i);

i = -5; i = i >> 2; System.out.println(i);

} }

50

Output : 1 -2

Let‟s see what happens in the above example. What actually happens in memory. i = 5 is stored in the memory as 00000000 00000000 00000101

00000000

i >> 2 value after the shift of two bits towards right 00000000 00000001

00000000 00000000

So after shifting we get the value of I as 1. But in case of negative numbers there is some difference. We all know that negative numbers are stored in memory in two‟s complement form and when we want to see the value it is again converted to two‟s complement and the original value is shown to us. Now let‟s see i = -5 is stored in the memory as 11111011

11111111 11111111 11111111

I >> 2 value after the shift of two bits towards right 11111111 11111110

11111111

11111111

so after shifting we get the value of i as -2.

*note : when we use the shift operators on byte and short variables then the values are shifted to int and the result after evaluation is also int so we should properly typecast it to get the correct result.

Bitwise Left Shift Operator ( >> )

The syntax for bitwise right shift opearator is given below. Variable

>>> no.of shifts

Here variable represents the variable on which we want to carry out the shift operation., and no.of shifts represents the number of bits the value of the variable should be shifted. e.g

x >>> 2 ;

53 Bitwise unsigned right shift operator shifts the bits of a number to a specified number of bits towars right without preserving the signed bit. We can say that the empty bits are filled with 0 .

class demo1 { public static void main(String ar[]) { int i = 64; i = i >>> 4 ; System.out.println(i);

i = - 64; i = i >>> 4 ; System.out.println(i);

} }

Output : 4 268435452

Let‟s see what happens in the above example. What actually happens in memory. i =64 is stored in the memory as 01000000

00000000 00000000 00000000

54 i >>> 4 value after the shift of two bits towards right 00000000 00000100

00000000

00000000

So after shifting we get the value of i as 4 . here in case of negative numbers also the empty bits are filled with o. We all know that negative numbers are stored in memory in two‟s complement form and when we want to see the value it is again converted to two‟s complement and the original value is shown to us. Now let‟s see i = -64 is stored in the memory as 11111011

11111111 11111111 11111111

i>>> 4 value after the shift of two bits towards right 11111111 11111111

00001111 11111111

so after shifting we get the value of i as 268435452.

*note : when we use the shift operators on byte and short variables then the values are shifted to int and the result after evaluation is also int so we should properly typecast it to get the correct result.

Short circuit operators && ,|| These operators are used particularly in control statement & loops. The && operator

If(condition_1 && condition_2) { Codes } In && operator both condition_1 & condition_2 is checked, if both the parts are true then codes with in block followed by is executed. If condition_1 is checked as false then condition_2 is never evaluated. class Demo {

55 public static void main(String[]args) { int x=9; int y=0; if((++x)==10 && (++y)==1) {

} System.out.println(x); System.out.println(y);

} } Output: 10 1

In the above piece of code, see the if statement both sides are evaluated because of && operator. But if first statement is evaluated as false then control never goes to the second one. class Demo { public static void main(String[]args) { int x=9; int y=0; if(++x==1&& ++y==1) {

}

56 System.out.println(x); System.out.println(y);

} } Output: 10 0

See the output first condition is evaluated as false there fore control does not go to the second condition.

The || operator If(condition_1 || condition_2) { Codes } In this case first condition_1 is evaluated & control goes to the second condition only if condition_1 is false. class Demo { public static void main(String[]args) { int x=9; int y=0; if(++x==10||++y==1) {

57 } System.out.println(x); System.out.println(y);

} } Output: 10 0 See the output. It clearly shows that since 1st condition is evaluated as true control does not go to the second condition. class Demo { public static void main(String[]args) { int x=9; int y=0; if(++x==1||++y==1) {

} System.out.println(x); System.out.println(y);

} } Output:

58 10 1 Here 1st condition is evaluated as false, there control goes to the second condition.

Ternary if-then-else operator ( ?: )

We can say that we can execute a if else statement using ternary if-then-else operator ( ?: ). Syntax is given below Evaluation_Part ? codes_of_section_1 :codes_section_2 First Evaluation_Part is evaluated if it is true then codes_of_section_1 is excuted else codes_section_2 is executed. e.g. class demo1 { public static void main(String ar[]) { int i = 64; int k=0;

k =(i>k)? 10 : 5; System.out.println(k);

k= (i >>> < >=

60

== != === !== & ^ | && || ?: = += -= *= /= %= = >>>= &= ^= |=

Lowest

If there are more than one operators in an expression then they are evaluated according to their precedence.

61

CHAPTER 5:

CONDITIONAL STATEMENTS AND LOOPS Decision making and branching: When a program makes a sequential control code and joins another part of code. Then it is called branching. 

Conditional branching: It based on particular condition.



Unconditional branching: decision.

This

takes

place

without

any

Control statement: 1. If statement. 2. Switch case statement. 3. Conditional operator. If statement: It's a two-way decision making statement, which use in construction with an expression. a. b. c. d.

Simple if. if ... Else. Nested if. else.... if ladder.

 if statement - of Java will take only the logical value true or false, Java not allow the integer value as condition, (0 as false and any non-zero value as true like C and C++).  If statement – of java will allow only the statement which return true or false, rather than the statement which return any integral value.

62

Simple if: if (expression) { statement(s); } statement (x);

if false

Test ? true Statement of body of if

Exit

if ...else: Syntax: If (test Expression) { statement(s); } else{ statement(s); }

63

if Test Expression

False

Block of if

Block of else

True Exit

Nested if ... else: Syntax: if (test expression) { if(test expression) { statement(s); } else { statement(s); } } else statement(s);

64

If True Test Expression If False Test

Block 3

Expression

True

Block 1

Block 2

Statement x

Exit

else ... if ... ladder Syntax:

False

65

if (test expression) { statement(s); } else if (test expression) { statement(s); } else statement(s); statement(x); //THIS IS A else-if ladder statement for setting-up a multi-way condition checking

If true

false Test Expression

If false Test

true

Expression

If B1

B2

false

true Test Expression

B3

Exit

B4

66

switch ... case statement: 

Java has a build in multi-way design statement called a switch.



The switch statement test the value of given variable or expression against the list of case value when a match is found a block of statement associated with that case is executed. The expression inside the switch case may be an integer or character.





Value 1, 2, 3, 4, n are constant or constant expression.



Each of these values should be unique in a switch block otherwise, it will hang the computer.



Each case must end with a colon.



If there is no match with any case specified in the switch case than the default statement is executed.



Each case must be terminated with a break statement.

Syntax: switch (expression/variable) { case Val 1: statement(s); break; case Val 2: statement(s); break; case Val 3: statement(s); break; default: statement(s) break; } Another of the decision making constructs is the switch-case construct which is ideally suited for making multiple choice application, like, for example, user menus. Typically, in situations where we have one value or expression

67

that has to be exactly matched with a list of pre-defined values or options the switch … case is the construct of choice. The switch statement is a multiway – decision making construct based upon the evaluated expression. It gives you a faster way to make a decision from a multiple number choice, the break statement is require after each case because if the switch expression contain default then this statement will execute by default and as well the after finding the require condition it will go for checking other cases which is a drawback, so it is better to use break after each case. Switch(exp) Entry Break

Case Y Val 1

B-1

N Break Case

Y Val 2

B-2

N Break Case

Y Val n

B-n N

Default

Statement x

Exit

68

Conditional operator: Syntax: Exp1? Exp 2:Exp 3; e.g. : ((X!= A)?((X>A)?(4X+100):(X+30)):(3X+50)); A program to show compute the net amount paid by the costumer if he purchased Rs. X from mill clothes and Rs. Y from handloom clothes Looping:      

Entry controlled. Exit controlled. While loop. Do loop. For loop. Jump statement.  Break.  Continue.

Looping: The process of repeatedly executing a block of statement is called as looping; the statement in the block may be executed any no. Of time from 0 – n times.

If loop continues forever then it is called as infinite loop. In looping a sequence of statement executed until some condition for termination of the loop is satisfied. A program will consist of two parts.  

Control statement. Body of the loop.

69

The control statement tests certain condition and then directs repeated execution of statement. Contain in the body of the loop. Depending upon the position of the condition or the control statement it may be of two types. 

Entry control: Here control condition is test before the start of the loop execution. It will not execute the block of statement for once also if the specified condition is false. e.g., while (test expression)....



Exit control: Here test is performing at the end of the body of the loop and before that, the body is executed unconditionally for the first time. It must run the body of the loop at least once whether the condition is true or false this will not hamper the first execution of the block. E.g. do...while (test expression).

For loop is the easiest to understand of the loop in Java. The for loop is execute the block of loop for the fixed no. Of time. It's generally used when you know, before entering the loop, how many time the loop will execute the code. Here is an example to show the use of for loop in Java. This is the sample program to show the use of for loop and as well as find out the whether a no is odd or even from a given set of no.

Entry if True

False True

Test Expr

n

Block - 1

Increment/ Decrement

Exit

70

Entry Control Loop These are the control statement or control condition tested before the body start of loop execution. The example of this type of loop is: e.g. While (condition) { statement(S); } This loop is run only when the condition is true other wise the will not be executed. This loop is never execute the statement if the condition is false.

Entry

Block - 1

If True Test n expr

False

Exit

71

Exit control loop These are the control statement or control condition is placed at the end of the body of the loop and before that the body is executed un-conditionally at least for one time, which is not possible in the case of Entry control loop. do { statement(s); } while (condition); Step in looping process: 1. 2. 3. 4.

Setting and initialization of a counter. Execution of statement in the loop. Test for a specified condition for execution of loop. Incrementing or decrementing the counter.

while loop (Entry control loop)

Initialization

If N Test expr

n

Y Statement(s)

Exit

72

while loop: initialization; while (test condition) { Loop body; }   

Here when the test condition is fails control is transfer out of the loop otherwise loop will be continue or repeated. Here the body of the loop may be executed at all if the condition doesn't satisfy for 1st time. Here also the expression (Test condition) should return only the true and false rather than any integer value as we have in C and C++.

e.g.: sum = 0; add = 1; while(n
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF