decision making and branching - web viewthe key word public is the access specifier that declares...

227
JAVA INTRODUCTION Java is a popular third generation language. Java was developed by Sun Microsystems Company of U.S.A. in 1991. Java is a simple, object oriented, distributed, interpreted, robust, secure, and portable, highly performance, multithreaded and dynamic language. Java is both a programming language and a platform. Like any other language we can develop application by java so it is a programming language. Java is a Platform because a palate form is the combination of system software and hardware e.g. operating system, windows XP, NT etc. Java provides the facilities like an operating system that’s why it is known as a platform. Its platform is designed to deliver and run highly interactive, dynamic and secure applications on networked computer system. History of Java In 1990 Patric Naughton and Gems Goslin with his co-workers started a secrete project called “Green” in Sun Microsystem Company. This project was started to develop a plateform for development of software for consumer electronic devices like cable, TV, switch boxes, microwave, Oven and remote control etc. Goslin give the name to this language “OAK” (named after the OAK tree outside the Gosling’s office). It was later discovered that there already was a computer language by that name.When a group of Sun people visited a local coffee shop, the name Java was suggested, and it stuck. In 1992 by the help of Java they develop a remote control known as “*7”. It was an extremely integrated remote control. In 1993 by the development of WORLD WIDE WEB, Green project team decides to develop tiny java Applet Graphical programs to make the Internet rich with graphics. Java Applets were the tinny java programs that can run on any Computer connected to the Internet. In 1994 this team develops a web browser known as “HOT JAVA” to run Applet program on Internet. In 1995 “OAK” was renamed as “JAVA” because “OAK” was the name of another language already. Many Companies like MICROSOF, NETSCAP etc. supported this name. At 1996 java established itself as master of internet programming language and Sun releases its first version of java known as jdk1.0 in 1996. VERSION OF JAVA

Upload: vuhuong

Post on 04-Feb-2018

228 views

Category:

Documents


11 download

TRANSCRIPT

Page 1: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

JAVA INTRODUCTION

Java is a popular third generation language. Java was developed by Sun Microsystems Company of U.S.A. in 1991. Java is a simple, object oriented, distributed, interpreted, robust, secure, and portable, highly performance, multithreaded and dynamic language.

Java is both a programming language and a platform. Like any other language we can develop application by java so it is a programming language. Java is a Platform because a palate form is the combination of system software and hardware e.g. operating system, windows XP, NT etc. Java provides the facilities like an operating system that’s why it is known as a platform. Its platform is designed to deliver and run highly interactive, dynamic and secure applications on networked computer system.

History of JavaIn 1990 Patric Naughton and Gems Goslin with his co-workers started a secrete project called “Green” in Sun Microsystem Company. This project was started to develop a plateform for development of software for consumer electronic devices like cable, TV, switch boxes, microwave, Oven and remote control etc. Goslin give the name to this language “OAK” (named after the OAK tree outside the Gosling’s office). It was later discovered that there already was a computer language by that name.When a group of Sun people visited a local coffee shop, the name Java was suggested, and it stuck. In 1992 by the help of Java they develop a remote control known as “*7”. It was an extremely integrated remote control. In 1993 by the development of WORLD WIDE WEB, Green project team decides to develop tiny java Applet Graphical programs to make the Internet rich with graphics. Java Applets were the tinny java programs that can run on any Computer connected to the Internet. In 1994 this team develops a web browser known as “HOT JAVA” to run Applet program on Internet. In 1995 “OAK” was renamed as “JAVA” because “OAK” was the name of another language already. Many Companies like MICROSOF, NETSCAP etc. supported this name. At 1996 java established itself as master of internet programming language and Sun releases its first version of java known as jdk1.0 in 1996.VERSION OF JAVA

Jdk 1.0 (1996), Jdk 1.1(1997), Jdk 1.2(1998), Jdk 1.3(2000), Jdk 1.4(2002) Jdk 1.5.0(2004), Jdk 1.6.0

What is byte code?When java compilar compile source code then it converts it to a special code known as byte code. This is an assembly language code which is neither readable for human nor of machine. It is also known as .class file. Java bytecode is a low level representation of a java soruce code programe. It can be executed using the java interpreter. The bytecode might be transaported across the web prior to begin executed by a java interpreter that is part of a web browser.

What is JVM?A JVM (Java Virtual Machine) is a program that behaves like a computer. Such a program is called an interpreter. JVM translats bytecode into machine language as they are called just in time compilation (JIT)

What is BlueJ?Bluej is an integrated Development Environment for the java programming language, developed mainly for educational purpose, but also suitable for small scale softare development.

Page 2: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

What is java library?A java library contains useful code that implements many common programming tasks. When we write new java programs, we usually combine our own new code with code extracted from these libraries. To facilitate the process of execution, the java compilar and the JVM must access the libraries.

JDK (JAVA DEVELOPMENT KIT):- java development kit contains many tools that are used for developing and running java programs. Those are like this:

Javac (java compiler) -> it is use for compilation of java programs that convert the source code into byte code.

Java (java Interpreter) -> It is use for interpretation of java programs that convert the byte code into the machine code so that program may run on computer.

Appletviewer ->for view of Java Applets.

Javap (java Dissembler) -> It is used to convert byte code into the program description.

Jdb (java Debugger) -> It is used to helps us in finding errors in the program.

Javadoc (for creating HTML document) -> Convert java source code to HTML format document. (javadoc demo.java)

Javah (for C header files): It produced header files which is required by the native methods when we are using native method in our program.

J2ME (Java 2 Micro Edition): for small Software like Mobile Software

J2SE (Java 2 Standard Edition): for development of middle level software like Software of small companies.

J2EE (Java 2 Enterprises Edition): used for development higher level software

FEATURES OF JAVA

Compiled and Interpreted: java is compiled and interpreted Language. Java compiler first translates java source code into byte code instruction which is not machine readable form so they are not able to run on the computer. There for in second stage Java Interpreter generates machine code that run on the computer and can execute directly. Thus java is a compiled and interpreted language.

Platform Independent and Portable ->Plate form independent is the most striking feature of Java. Java program can move easily from one computer to another computer anywhere. Any change in the system configuration, Operating System, Processor will not affect the execution of the program. Due to this reason java became master of internet programming language. If we have written a source code in DOS then we can run this program on other platform like UNIX or LINEX without any change in the source code this is the reason java is a plate form and independent language.

Java portability is mainly due to the byte code (.class file).Because a program in byte code can be transfer to any system without any difficulty and then JVM at that system will convert it into the machine code by the help of Java Interpreter (Java). The second reason is the primitive data types that are machine independent.

Object Oriented: Object oriented programming is an approach to software development in which a program is defined by a set of objects that communicate and cooperate to accomplish tasks. Java is a pure object oriented language. Almost everything in java is class and object. All program code and data remain within classes and object.

Page 3: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Robust and Secure: It has strict run time and compiles time checking for data types. It represents the concept of exception handling due to which series of errors can be eliminated form the program and we can save our program from crashing.

Security is another important issue for java because it is an internet programming language that is place of viruses and abuse of resources. When dealing with java applet takes place java first ensure that this applet should be error free if here is error in the program it will not be communicate to the computer and any java program can not gain access into a system without proper authorization.

Distributed: Java is distributed because it allowed to multiple programs at multiple remote locations to collaborate and to work together on a single project. Beside this it has ability to share the data and programs. Java programs can open on internet as easy as they can run on local System.

Simple and Familiar : Java is a simple and familiar language because it is developed with the help of ‘C’ and ‘C++’. Programmers who have work on these languages can understand java very easily. To bring familiarity in java it was modeled on ‘C ‘and ‘C++’. Java code looks like a ‘C’ and ‘C++’ code.

Multithreaded: Multithreading means handling multiple threads at the same time or to perform more than one operation at a single time. It is one of the most striking feature of java that increase the performance of java .for example we can download a file at a time while we are playing a song at the same time.

High Performance: Java performance is very high mainly due to its feature of Interpretation beside this multithreading also help full in improvement of its performance. Its architecture is also designed in such a manner so that overheads may be reduced at run time from the program due to all these feature Java performance is very well.

Dynamic and Extensible : Java is a dynamic language. It is capable in adding new class, Objects, Methods at run time. Java also support function (native function) written in other language like ‘C’ and ‘C++’. These function can use by java at run time.

Easy Development: J2SE 5.0 (java two standard edition) is the development kit that provides many advance tool like autoboxing and unboxing, typesafe, enum and varargs etc, with the help of these tools programming become easier and the source code also is bug free and error free program develop in J2SE5.0 also reduced the memory space used so it is one of the good feature of java.

Difference of Java and C: The main difference of Java and C is that Java is pure Object Oriented Language (OOP) while C is a Procedure Oriented Language (POP).

1. Unique statement keywords like typedef and sizeof are eliminated from java while these are used in C.

2. Data types like structure and union are not included in Java.3. Storage classes like auto, extern, register etc. are not use in Java.4. Java does not support pointer.5. Java does not contain pre-processor directive like #define, # include etc.6. Function with no arguments in java are with empty parentheses they do not contain void key word

like C++.Difference of Java and C++

1. Java does not support operator overloading.2. Java does not contain template classes.3. Java does not support multiple inheritances.4. Java does not support global variable. Every variable and method is the part of object and class.5. There are no header files in java.6. Java has replaced destructor with finalize method.

Page 4: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Java and Internet: Java is known as master of internet programming language .first application program was written in java was HOTJAVA, which was a Web Browser to run Applets on Internet. these Java enabled web browser can use for downloading of java Applets form Computer that are link to the internet from different worldwide locations and can rum them locally .Infect Java Applet made the Internet a storage system for local computer. Due to all these features java is popular as internet programming language.

Java and World Wide Web: World Wide Web (www) or (w3) was introduced in 1993. It is an open ended information system designed in such a manner that anybody can retrieve information from Web Site. Web Sites contain Web Pages that provide both information and Controls. Web Site is open ended system .web pages are created with the help of a special language called HTML (Hypertext Markup Language). Each Web page contains HTML tags with the help of which we can retrieve, manipulate and display these documents throughout the word on Internet. java gives a new life to the web in the field of text and graphics .with the help of java it become possible for web to support Animation, Graphics, Games and many other special effects. With the help of Java Web become more attractive and usable that is the reason the user of Web is increasing day by day. The process of communication between Java and Web involve the following steps:

1. When user logon a web site he send a request for an HTML document to the remote computer’s web server. Web server is a program that can accept request, process it and send the required document to the server of requesting computer.

2. When HTML document returned to the user’s browser it contains applet tag (<APPLET>) that identified the applet.

3. In the same time byte code of this web document is also transferred to the user’s computer. This byte code is created by the Java Compiler by compilation of source code to transfer this code on to the internet because a program cannot transferred on the internet in source code only because it is not possible to run program without byte code on the internet.

4. Java enabled browser on the user’s computer interpret the byte code and convert it into machine code so that it can run on the local computer and will produce the output.

Web Browsers: Web browser is the collection web sites with the help of web Browser we can retrieve information from the Internet that is scattered on different websites throughout the world. There are mainly three java enabled web browser:

1. Hot Java 2. Netscape Navigator 3. Internet Explorer

Hot java -> when java was developing there was not any web browser on the Internet and it was totally textual and was not of more use. but java give a new life to the internet by introducing the first java enabled web browser know as Hot Java. This web browser was developing by Sun Microsystem Company. It is able to display interactive content on the Web using the java language. It was first web browser develop by the java. It is written purely in java language and thus represents that capability of java. Hot Java can run on Window XP, Window NT and Windows95. It makes the Web more dynamic and attractive.

Netscape Navigator -> It was introduced by Netscape Communication Corporation. It is a general purpose web browser that can run java applets successfully. It is one of the most widely used browsers these days. Its few latest versions are available for Window NT, Window95; Solaris. It has many useful features such as indication no of bytes downloaded and visual display of downloading process.

Internet Explorer -> It was developed by Microsoft for Window 95, NT and XP It is also widely used web browser today. Both Netscape and Internet explorer use the tool bars, controls, icons, menus and dialog boxes for easy navigation. Explorer uses the (JIT) just-in-time compiler which greatly increases the speed of the execution.

Java language is mainly use for internet programs we can develop following types of java programs.

Page 5: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

1. Application programs -> It is the form of character user interface (CUI). They are similar to other language programs written in ‘C’ or ‘C++’ .an application program is nothing but a program that runs on the computer under the operating system of the computer.

2. Applet programs -> It is mainly use for internet application these programs use on a web page and require java enabled web browser. An applet is loaded and executed when a user load a web page through a web browser. when the user view the web page in which applet is embedded, they interact with applet .These Applet program are use to make Animation, display Images, run the Sound as well as they can react the user input output and dynamically change.

3. Servelets -> Servelets is a mini server site Programs similar to an Applet define in the java. Servelets application programs enables to extend the functionality of Web Server it is particularly use for producing dynamic Web contains. Servelets provides a no of advantages over other approaches including portability, power effectively, safety, integration and extensible.

What is the difference between java applet and java application programe?A java applet is a java program that is executed using a web browser. Usually, the bytecode form of java applet is pulled across the internet from another computer and executed locally whereas a java application is a java program that can stand alone it does not require a web browser in order to execute. Beside this a java applet do not contain main method while application program must contain main method because execution of application program starts from main method so a java stand alone program without main can never execute.

Starting of Java programmingJava Character Set: character set is a set of valid characters that a language can recognize. A character represents any letter, digit or any other sign. Java supports Unicode character set. Which is a large pool of character contains around 65000 characters. Unicode is 16 bits character coding system. Its character is collected from 24 languages of the world these languages are English, Chinese, Malayalam, roman, Italian etc. first 128 character in the Unicode character set are identical to the common ASCII character set. We can refer to a particular Unicode character by using the escape sequence \u followed by a four digits hexadecimal number.

Java Tokens: Token is the smallest individual unit of a program. A java program basically is a collection of classes. A class is defined by a set of declaration statements and methods containing executable statements. Most statement contains expressions, which describe the actions carried out on data. The compiler recognized the tokens for building up expression and statements. Java contains five types of tokens.

1. Reserve words or key words or special words.2. Identifiers 2. Literals 3. Operators 4.Separators

1. Key Words: These are the words that convey a special meaning to the language compiler. These are reserved for special purpose and must not be used as normal identifier names. Java contains around fifty key words. Example are :- break, continue, if, else, for, while etc. java is a case sensitive language so upper and lower case are treated separately. Example break is the key word while Break is not a key word because its B is capital.

2. Identifiers: Identifiers are fundamental building blocks of a program and are used generally to give the name to different parts of the program viz. variable, objects, classes, functions and array etc. we have to follow some rules while declaring identifiers , these rules are as follow:1. Identifier can have alphabets, digits and underscore and dollar sign characters.2. They must begin with an alphabet but never by a number.3. They must not be a key word or Boolean literal or null literal.4. The can be of any length. 5. Java is case sensitive language so upper and lower case will be treated separately.

3. Literals: Literals often referred to as constants. These are the fixed data values. Java allows several kinds of literals. Example 1. integer literal 2. floating literals 3. boolean literals3. character literals 4. string literals 5. null literals.

Page 6: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

1. integer literals: Integer literals are whole numbers without any fractional part. There are three types of integer literals.

i. Decimal Integer Literals-> An integer literal consisting of a sequence of digits is taken to be decimal integer constant unless it begins with 0. Example 1234, 2011, -90, +250 etc.

ii. Octal Integer Literals -> A sequence of digits starting with 0 is taken to be an octal integer. Example 1 will be written as 01, 7 will be written as 07. Octal number system does not contain 8 and 9 digit.

Table of octal numbers1 012 02---- -----7 078 0109 01110 01215 017---- ------16 02017 02123 027---- ------24 030--- -----63 07764 010065 010166 010271 0107

iii. Hexadecimal Integer Literals: A sequence of digits preceded by 0x or 0X is taken to be an hexadecimal integer. For example 12 will be written as 0XC as hexadecimal Integer. With hexadecimal constants only 0-9 and A-F can be used. A is equivalent to 10 and F is equivalent to 15.

Table of Hexadecimal Number0 0x01 0x12 0x29 0x910 0xa11 0xb12 0xc13 0xd14 0xe15 0xf16 0x1017 0x1118 0x1219 0x1320 0x1432 0x2033 0x2134 0x2235 0x23

Page 7: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

41 0x2948 0x3049 0x3150 0x3251 0x3357 0x39144 0x90156 0x100257 0x101274 0x112278 0x116

2. Floating Literals: These are also called as real literals. Real literal are numbers having fractional parts. These may be written in one of the two forms called fractional form or the exponent form.1. A real literal in fractional form must have at least one digit before a decimal point and at least one digit after the decimal point. It may also have either + or – sign preceding it. A real literal with no sign is assumed to be positive. Following are the valid real literals in fractional form.0, 17.5, -13.2, -0.235, -12.0 etc.

2. A real literal in exponent form has two parts. A mantissa and an exponent. The mantissa must be either an integer or a proper real literal. The mantissa is followed by a letter E or e the exponent. The exponent must be an integer. The following are the valid real literals in exponent form.125e05, 1.56e07, 0.123e08, 124e+8, 120e04, -0.124e-3 etc.

3. Boolean Literals: The boolean type has two values, true and false. A boolean literal is always of type boolean.

4. Character Literals: A character literal is one character enclosed in single quotes. A character literal must contain one character, but not more than one. We can have some non-graphic character in character constants. Non-graphic character are those character that cannot be typed directly from key board e.g. backspace, tabs, enter , carriage return etc. these non-graphic character can be represented by using escape sequences. An escape sequence is represented by a backslash (\) followed by one or more characters.

Escape Sequences Non-graphic character Unicode values of character\a Audible bell (alert) 0x0007\b Backspace 0x0008\n New line 0x000A\r Carriage return 0x000D\t Horizontal tab 0x0009\v Vertical tab 0x000B\\ Back slash 0x005C\’ Single quote 0x0027\” Double quote 0x0022\? Question mark\0n Octal number\0xhn Hexadecimal number\0 Null 0x0000

Page 8: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

/**************escape sequences*************/class escape{public static void main(String arg[]){System.out.println("MOhammad\nArif"); //new line characterSystem.out.println("MOhammad\tArif"); //tab for spaces (6 space)System.out.println("MOhammad\bArif"); //for back spaceSystem.out.println("MOhammad\u0008Arif"); //back spaceSystem.out.println("MOhammad\'Arif\'"); //single quoteSystem.out.println("MOhammad \"Arif\" "); //double quoteSystem.out.println("MOhammad\rArif"); //carriage returnSystem.out.println("MOhammad\\Arif");System.out.println(07); //octal numberSystem.out.println(0x7); //haxadecimalSystem.out.println(0xa); //haxadecimalSystem.out.println(0xf); //haxadecimalSystem.out.println(7); //decimal number}}

5. String literals: Multiple characters constant are treated as string literals. A string literal is a sequence of zero or more characters surrounded by double quotes. Each character may be represented by an escape sequence. Example of string literals are as follow: “abc”, “2011”, “+*-/”, “1-jan-2011”, “10/2/201”, “mohamad\arif”, “\arif”, “seema\’s pen” etc.

6. The null literal: The null literal has one value, the null reference, represented by the literal null, which is formed from ASCII characters. A null literal is always of the null type.

4. Separators: Separators are the symbols used to indicate where groups of code are divided and arranged. They basically define the shape and function of our code. The following nine ASCII characters are the separators or punctuators. ( ) { } [ ] ; , .

5. Operators: An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. They usually from a part of mathematical or logical expression.Operator are of three types.1. Uniary operator: operator which require single operand for their working are known as

uniary operator.Example: ++, --, + ,

2. Binary operator: operator which require two operands for their working are known as binary operator.

3. Ternary operator

4. Arithmetic operatorsArithmetic Java+ +- -÷ /X *% %

Page 9: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

5. Relational operatorsArithmetic Java Relation< < Lesser than≤ <= Lesser than equals to> > Greater than≥ >= Greater than equals to = == Equals to ≠ != Not equals to

6. Unary operators or increment and decrement operators(++) (- -)

Increment decrement

Pre-increment post-increment Pre-decrement post-decrement

Let i=3 O/P O/PA=++i; a=4 b=- -i; a=2A=i++; a=3 b=i- -; a=3

7. Conditional operators&& Logical AND|| Logical OR! Logical NOT

Truth table for AND (&&)Expression1 && (AND) Expression2 ResultT && T TF && T FT && F FF && F F

Truth table for OR (||)Expression1

|| (OR) Expression2 Result

T || T TF || T TT || F TF || F F

Truth table for NOT (!)Expression ! (NOT) ResultT ! FF ! T

8. Bitwise operatorOperator

Meaning

& Bitwise AND| Bitwise OR~ Bitwise complement^ Bitwise exclusive OR<< Left shift operator

Page 10: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

>> Right shift operator>>> Right shift with zero fill

X=130000 0000 0000 1101Y=250000 0000 0001 1001

Z=X&YZ0000 0000 0000 1001

Z=X|YZ0000 0000 0001 1101

Z=X^YZ0000 0000 0001 1101

X 1001 0110 1100 1011~X0110 1001 0011 0100

/*shif operator*/class shiftoperator{public static void main(String args[]){int a=8, b=-8;System.out.println("a = "+a+" b = "+b);System.out.println("a >> 2 = "+(a>>2));System.out.println("a << 1 = "+(a<<1));System.out.println("a>>> 1 = "+(a>>>1));System.out.println("b >> 1 = "+(b>>1));System.out.println("b>>> 1 = "+(b>>>1));}}

/*bitwise operator demo*/class bitwise{public static void main(String args[]){int a=13, b=25;System.out.println("a = "+a);System.out.println("b = "+b);System.out.println("a & b = "+ (a&b));System.out.println("a | b = "+ (a|b));System.out.println("a ^ b = "+ (a^b));}}

9. Conditional Operator Ternary operator (:?) This operator required three operators for its so it is known ternary operator. This operator is used to construct condition expression. It is alternative to if – else.

Exp1 ? exp2 : expt3Condition ? True : falseIf- then- elseint a,b,c;

Page 11: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

a=10,b=20;c=a>b?a:b;

10. Special operators: There are some special operators like instanceof operator and member selection operators (.).

The instanceof operator is an object reference and returns true if the object on the left hand side is an instance/object of the class given on the right side. This operator allows us to determine whether the object belongs to a particular class or not.Example: person instanceof student

Dot operator (.) is used to access the instance variable and methods of class objects. Person1.age;Person1.salary ();

Arithmetic ExpressionsAn arithmetic expression is a combination of variable, constants, and operators arranged as per the syntax of the language.Example: 1. (m+n)(x+y) 2. Ab/c*d-e

Precedence of operatorsAn arithmetic expression without any parentheses will be evaluated from left to right using the rules of precedence of operators. Hierarchy of operatorsOperator Description Associativity Rank. Member selection Left to right 1( ) Function call Do 1[ ] Array elements reference Do 1

- Unary minus Right to left 2+ + Increment Do 2-- Decrement Do 2! Logical Negation (not) Do 2~ Once complement Do 2(type) Casting Do 2

* Multiplication Left to right 3/ Division Do 3% Modulus Do 3

+ Addition Left to right 4- Subtraction Do 4

<< Left shift Left to right 5>> Right shift Do 5>>> Right shift with zero fill Do 5

< Less than Left to right 6<= Less than equals to Do 6> Greater than Do 6>= Greater than equals to Do 6Instanceof Type comparison Do 6

== Equality Left to right 7!= Not equals to Do 7

Page 12: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

& bitwise AND Left to right 8| Bitwise OR Do 8^ Bitwise xor Do 8&& Logical AND Do 8|| Logical OR Do 8?: Conditional operator Do 8= Assignment operator Do 8+=, *=, /= etc.

Shorthand operator Do 8

1. A==c||b>a2. B>15 && c<0 ||a>0 (a=3,b=14, c=5)3. (a/20==0.0 && b/2.0!=0.0)||c<0.0 (a=3,b=14, c=5)4. (amount+qty*value)-bal5. Fin+qty*inter6. Inter-(qty*value)+fin7. Q(a+b-z/4) 8. √a2+b2+c2

9. 2-ye2y+4y10. P+q(r+s)4

11. Math.abs(Math.exp(x)-x)12. (Cos x/tan-1 x)+x13. A=mb*3/4+k/4+8-mb+5/8 (mb=5, k=19)14. (a+b)>c && (c+d)>a15. (x>y) && (!y<z) (x=3,y=7,z=9)16. X<=!y && z (x=3,y=7,z=9)17. F=(++a)*b-a (a=4, b=2)18. C=a-(b++)*(--a) (a=4, b=2)19. C=(a++)*d+a (a=4, d=2)20. Area=πr2+2πrh21. Result=2m1m2/m1+m2*g22. Side=√a2+b2-2ab cos(x)23. ((x-(y/5)+z)%8)+2524. (5/3)*3+5%325. 14%3+7%2

Data types: Data type specifies the size and values that can be stored in a variable. Data types in java can be classified in number of parts as follow:

Page 13: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Type Size Minimum value

Maximum value Type of value can hold

Byte 1 byte (8-bits) -128 127 Can hold complete number without decimal places

Short 2 byte (16-bits) -32768 32767 DoInt 4 byte (32-bits) -2,147,483,648 2,147,483,647 DoLong 8 byte (64-bits) -263 263-1 Do

float 4 bytes (32 bits) -3.4e-38 +3.4e+38 Precision up to 6 digitsdouble 8 bytes (64 bits) -1.7 e-308 +1.7 e+308 Precision up to 16

digits

Char 2 bytes (16 bits) Single character or 0

65,535 Unicode character must be enclosed in single quote.

Boolean 1 byte (8 bits) True or false Can hold only logical data i.e. true or false.

Reference Type: A reference data type is a data element whose value is an address. Arrays, classes, and interfaces are reference types. The value of reference type variable is an address of the value or set of values represented by the variable.

Variable: A variable is a named memory location which holds a data value of a particular data type, whose value is manipulated during the program run.

Declaration and initialization of variable-> Syntax data type variable name;Example:

int age;int age, salary, code;int age=25, salary=10000, code=1;float salary, bonus;salary=1000.00;

Data Type

Primitive(intrinsic)

numeric

Integer Floating point

Non-numeric

Charcter Boolean

Non-primitive(derived)

classes arrays

interface

Page 14: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

bonus=500.00;

Dynamic initialization:int a=10;int b=a;

Scope of variables: The program area where a variable is accessible is known as scope of that variable. On the basis of scope variable can be classified into three categories.

1. Instance variable. 2. Class variable or global variable. 3. Local variable.

Instance variable: Instance are declared inside a class. These are created when the objects are instantiated and therefore they are associated with the objects. They take different value for each object.

Class variable or global: These are global to a class and belongs to the entire set of objects that class creates. Only one memory location is created for such variable. To declare a variable globally we should use the key word static.

Local variable-> Variable declared inside a method are called local variables. They are called so because they are not available for use outside their method definition. Local variable can also be declared inside program blocks that are defined between an opening brace {and closing brace}. These variables are visible to the program only from the beginning of its program block to the end of the program block. When the program control leave a block, all the variables in the block will cease to exist.

Block 1Global variable

Local Variable

Local Variable

Variable life:

Whay java is known as strongly typed language:A variable in java is designed to hold only one particular type of data. It can legally hold that type of data and no other. The compiler will consider it to be a syntax error if we try to violate this rule. We say that java is a strongly typed language because it enforces this rule.

Type conversion: the process of converting one predefined type into another is called type conversion. Type conversion is of two types.

1. Implicit type conversion: It is automatic type conversion done by java itself. There is no any intervention (interface) of the programmer. Automatic conversion is done when different data types are intermixed in an expression, so as not to lose information. The java compiler converts all operands up to type of the largest operant. It is based on some rules:i. If either operand is of type double, the other is converted to double.

{int x=0;

Block 2

Block 3

{int m=5;

- --- --

}

{int n=10;

- - - - - -

}

Page 15: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

ii. If either operand is of type float, the other is converted to float.iii. If either operand is of type long, the other is converted to long.

The implicit type conversion where data types are promoted to higher type are known as type promotion or coercion. It is also known as widening of data type.

2. Explicit type conversion or Type Casting: The explicit type conversion is user defined that forces an expression to be of specific type. The explicit conversion of an operand to a specific type is called type casting. In type casting we cast (convert) the value to be stored by, proceeding it with the type name in parentheses. Casting is necessary in situations when a method returns a type different than our required type. It is also known narrowing of data or force conversion. Syntax-> (type) expression./************type casting demo******/class conversion{public static void main(String args[]){int a=2,result;result=(int)Math.pow(a,2);System.out.println(result);}}

Expression Evaluation: Expression can be pure and mixed expression. Pure expression have all operands of same data types, while impure expression have operands of mixed data types.

Boolean expression: The expression that results into false or true are called Boolean expressions. The Boolean expressions are combination of constants, variables and logical and relational operators.

Statement: A statement forms a complete unit of execution. It is similar to the sentence in natural language. Each statement in java is terminated by semicolon (;).

Block: A block is a group of zero or more statements between balanced braces and can be used anywhere.

Null or empty statement: The statement where only semicolon (;) is present on the name of statement and there is no any logic to apply is known as empty or null statement;It is required in the situations where a program requires the presence of statement only, but not logic of the program. It is generally used in loops and their bodies. Example: ; ------------- it is null statement

Types of java programs: 1. Stand alone program 2. Java applets1. Stand alone programs -> stand alone programs are like simple C and C++ programs. This

program can read and write files and perform certain operations that applets cannot do. Executing of these programs involves two steps. First compiling the source code into byte code using javac compiler. And second executing the byte code program using java interpreter.

2. Java Applets are small programs developed for internet application. These are graphical in nature. We can develop applets from simple animated graphics to highly complex games. Since applets are embedded in an HTML document and run inside a Web page, creating and running applets are more complex than creating an application.

Structure of a simple java programclass sample{Public static void main(String args[]){

Page 16: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println(“hello java”);}}

1. Class declaration -> the first line class sample declares a class, which is an object oriented construct. Java is true object oriented language and there for everything must be placed inside a class. Class is a key word and declares a new key word. Sample is the valid java identifier to indentify the class by this name.

2. Opening braces-> every class in java begins with an opening braces “{“ and ends with a closing braces “}”.

3. The main Line -> public static void main(String args[]) defines a method named main. This the main function of program that execute before execution of any function at the time of execution. Main is the starting program of a standalone program. A java application can a number of classes but only one class contain one main method. A java program can have only one main method. Java applet do not use the main method.

i. public : the key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class in a program.

ii. static : static is also a key word that makes the main method as one that belong to the entire class. The main must always be declared as static since the interpreter uses this method before any object is created. Static makes a variable or method as global.

iii. void : void is the key word that specifies that main does not return any value.iv. String : here string is the class. v. Args [] : args is an array of String class type that holds the command line argument,

given at the time of compilation.4. The output line: System.out.println(“hello java”) is the executable statement in the program. It is

similar to the printf() of C and cout<< of C++. Since java is true object oriented language, every method must be part of an object. The println() method is a member of the out object, which is a static data member of System class. The output of this line is as below:Output -> Hello java

Use of Math functions: Math is class present in java’s default package lang. most of the math function required in the java program will provided by Math class. To use the method from Math class we have to write the following statement at the top of the program. import java.lang.Maht; this statement is similar to the #include statement of C and C++.

How to open Java Editor?Start->run->type cmd->cd\->enterC:\>cd jdk1.6.0->enter or (c:\>cd j*\b*->enter)C:\>jdk1.6.0>cd bin->enterC:\>jdk1.6.0\bin>edit->enterFull screen will display

Javac for compilationJava for run

Comments: java permits both single line and multiple line comment. The single line comments begin with // and end at the end of the line automatically and a multi line comment starts by /* and ends with */ symbol.

/*******************java simple program***************/class information{public static void main(String args[]){System.out.println("Name \t Mohammad Arif ");System.out.println("Address \t Dehradun ");

Page 17: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println("Mobile No \t 93585456767 ");}}

/**************java sum******************/class sum{public static void main(String args[]){int a,b;a=10;b=20;int c=a+b;System.out.println("Sum of two numbers is "+c);}}

What is BufferedReader?The class java.io.BufferedReader extends java.io.Reader class. This class is used to read text from an input stream. Java.io.BufferedReader class provides efficient way to read characters, array of characters and lines.

What is System class?The system class provides references for the standard input, output and error streams. They are given below:

1. InputStream: This is used to take the input stream. The system class provides references for the standard input by system.in.

2. OutputStream: This is used to show the output stream. The System class uses System.out stream to refer to the standard output.

3. ErrorStream: This is used to show the error as output stream. The System class provides references for the standard output by System.err.

/*****************simple integer input by keyboard*********/import java.io.*;class input1{public static void main(String args[]) throws IOException{int a, b;BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter value of a ");a=Integer.parseInt(br.readLine());System.out.println("Enter value of b ");b=Integer.parseInt(br.readLine());

System.out.println("value of a "+a);System.out.println("value of b "+b);}}

/***************use of DataInputSream Class*****/import java.io.*;class input2{public static void main(String args[]) throws IOException{int a, b;

Page 18: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

DataInputStream br=new DataInputStream(System.in);System.out.println("Enter value of a ");a=Integer.parseInt(br.readLine());System.out.println("Enter value of b ");b=Integer.parseInt(br.readLine());

System.out.println("value of a "+a);System.out.println("value of b "+b);}}

/*Reading different data type from keyboard*/import java.io.*;class input{public static void main(String args[]) throws IOException{DataInputStream br=new DataInputStream(System.in);System.out.println("Enter an integer ");int a=Integer.parseInt(br.readLine());

System.out.println("Enter a doube ");double d=Double.parseDouble(br.readLine());

System.out.println("Enter a string");String s=br.readLine();

System.out.println("Enter a boolean ");boolean bool=Boolean.parseBoolean(br.readLine());

System.out.println("Enter a character");char ch=(char)br.read();

System.out.println("Value of integer "+a);System.out.println("Value of double "+d);System.out.println("Value of string "+s);System.out.println("Value of character "+ch);System.out.println("Value of boolean "+bool);}}

1. pq√3+0.02√r2. (0.05-2y3)/(x-y)3. b+√b2+4ac/2a4. 3/4a3-2/7b4

5. A3+b4+c5

6. 3/8√b2-c3

7. Enter two numbers and swap them by the help of third variable.8. Enter two numbers and swap them without the help of third variable.9. Ramesh’s basic salary is input through the keyboard. His DA is 40% and HRA is 20% of basic

salary. Calculate his gross salary.10. The distance between two cities (in KM.) is input through keyboard and converts it into metter, feet,

inches and centimeters.

Page 19: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

11. If the marks obtained by a student in five different subjects are input through the keyboard, find out the total marks and percentage marks obtained by the student. Assume that the maximum marks obtained by student in each subject are 100.

12. Temprature of a city in Fahrenheit degree is input through the keyboard and convert this temperature into centigrade degrees.Fahrenheit=9/5*c+32Celcius=5/9*(f-32)

13. The length and breadth of a rectangle and radius of a circle are input through the keyboard. Write a program to calculate the area and perimeter of the rectangle, and the area and circumference of the circle.

Area of circle=πr2

Area of rectangle=length*breadthPerimeter of rectangle=2*(length+breadth)

Circumference of circle=2πr

Control structureControl structure or control statements are the statements which control the flow of program execution. These are basically of four types.

1. Decision making statement. Ex:==if, if else, nested if else, conditional operator2. Selection statement Ex:==else if ladder, switch, nested switch3. Iteration Ex:==for, while, do-while, for each loop4. Jump statement Ex: ==break, continue, return, exit.

Decision Making and BranchingDecision Making Statements or conditional statementsDecision statement means the execution of statements depends on a conditional test. If a condition evaluates to true, a course of action is followed otherwise another course of action is performed. This procedure is known as decision making procedure because it helps in making decision about which set of statements is to be executed.Example: if, if-else, conditional operatorif statement Syntex if (codition)

Statement

Or if (condition){ Statement1Statement1

}If else statementSyntax if(condition)

StatementelseStatement

Orif(condition){Statement1Statement2}Else

Page 20: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{Statement1Statement2}

Example:#include<iostream.h>#include<conio.h>void main(){int a,b;clrscr();cout<<”\n enter value of a and b”;cin>>a>>b;if(a>b)cout<<”a is greater”;elsecout<<”b is greater “;getch();}

1. WAP to find whether a number is even or odd?2. WAP to enter a temperature in celcius and convert it into Fahrenheit and if the temperature is 98.6 F

or more than display fever otherwise normal. F=9*c/5+32;3. WAP to find whether a number is positive or negative.4. WAP to find whether a year is leap or not.

/* input selling price and cost price of an item and print whether seller has made profit or loss and how much*/import java.io.*;class profit_loss{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int sp, cp, diff;System.out.println("Enter salling price and cost price of an item ");sp=Integer.parseInt(br.readLine());cp=Integer.parseInt(br.readLine());diff=sp-cp;if(diff>0)System.out.println("He made profit "+ diff);elseSystem.out.println("He made loss "+ diff);}}

Nested if else -> a nested if is an if that has another if in its if’s body or in its else’s body. The nested if can have one of the following three forms:

if (condition){

if(condition)Statementelse

Page 21: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Statement}else{

if(condition)StatementelseStatement

}

Example:/******Nested if else demo***/import java.io.*;class nestedifelse{public static void main(String args[]) throws IOException{DataInputStream br=new DataInputStream(System.in);int a,b,c;System.out.println("Enter values of a, b, and c ");a=Integer.parseInt(br.readLine());b=Integer.parseInt(br.readLine());c=Integer.parseInt(br.readLine());

if(a>b){ if(a>c) System.out.println("A is greatest "); else System.out.println("C is greatest ");}else{ if(b>c) System.out.println("B is greatest "); else System.out.println("C is greatest ");}}}

/*Enter a character and find whether it is vowel or consonant and find its case also*/import java.io.*;class characters{public static void main(String arg[]) throws IOException{DataInputStream br=new DataInputStream(System.in);char ch;System.out.println("Enter a character ");ch=(char)br.read();if(ch>='a' && ch<='z'){ if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u') System.out.println("It is lower case vowal");

Page 22: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

else System.out.println("It is a lower case consonant");}}}

The conditional operator: this operator is alternative to if –else statement. It concept is if-then-else. It is also known as ternary operator because it requires three operands for its working. Its general form is this:Condition?expression1:expression2;If condition is true then expression one will execute otherwise expression2 will execute.Example:#include<iostream.h>#include<conio.h>void main(){int a,b,c,d;cout<<”\n enter value of a,b and c”;cin>>a>>b>>c;d=a>b?(a>c?a:c):(b>c?b:c);cout<<”The greatest element is “<<d;getch();}

import java.io.*;class leapyear{public static void main(String args[]){int year=2012;System.out.println(year%4==0?"Leap":"Not Leap");}}

The else if ladder: it is also known as if-else-if staircase because of its appearance. It is used to handle multiple conditions one by one. Syntax:

if(condition)Statement

else if(condition)Statement

else if(condition)Statement

elsestatement

example:import java.io.*;class result{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int phy,che,math;int total;double pct;System.out.println("Enter marks of phy, chemisty and math ");phy=Integer.parseInt(br.readLine());

Page 23: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

che=Integer.parseInt(br.readLine());math=Integer.parseInt(br.readLine());total=phy+che+math;pct=(total*100)/300;if(pct>=60)System.out.println("First division ");else if(pct>=50 && pct<60)System.out.println("Second division ");else if(pct>=40 && pct<50)System.out.println("Third division ");elseSystem.out.println("Faile ");}}

1. Enter three sides of a triangle and find whether it is a equilateral(three sides are equal) or isosceles (two sides are equal) or a scalene (no side is equal) triangle.

2. Enter three sides of a triangle and find whether the triangle is possible or not. If sum of any two sides is greater than third, then triangle is possible otherwise not. (a+b>c) && (b+c>a) && (c+a>b)

3. Find out the total cost that will be paid by the customerTotal Cost Discount (in Percentage)Less than Rs. 2000 5%Rs. 2001 to Rs. 5000 25%Rs. 5001 to Rs. 10000 35%Above Rs. 10000 50%

4. Display grade accordingly.Marks Grades80% and above Distinction60% or more but less than 80% First Division45% or more but less than 60% Second Division40% or more but less than 45% PassLess than 40% Promotion not granted

5.Units Consumed Chanrges

Up to 100 units 80 paise/unit>100 and up to 200 unit Re 1/unit>200 units Rs. 1.25/unit

6. root=b2-4ac , calculate root for two equaltion and find:If d>=0 Roots are real and UnequalIf d=0 Roots are real and equalId d<0 Roots are imaginary

7. Calculate charges for parsal:Weight Charge

Up to 10 kg. Rs. 20 per kg.For the next 20 kg. Rs. 10 per kg.For the next 20 kg. Rs. 8 per kg.More than 50 kg. Rs 5 per kg.

Page 24: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

8. Calculate simple interest:Time RateT=1 year R=10%T=2 years R=11%T=3 years on more R=12%

9. Find out the gross salary of an employee:Dearness Allowance (DA) 25% of Basic payHous Rent Allowance 15% of Basic payProvident Fund 8.33% of Basic payNet Pay Basic Pay+Dearnesss Allowance+House Rent AllowanceGross Pay Net pay-Provident Fund

10. Tax rate for water consumed by a consumer:Water Consumed (in Gallons) Tax Rate in Rs.More than 45 but 75 or less 475.00More than 75 but 125 or less 750.00More than 125 but 200 or less 1225.00More than 200 but 350 or less 1650.00More than 350 2000.00

11. Calculate Income tax:Annual Salary Rate of income taxUp to Rs. 1,00,000 No taxRs. 1,00,001 to Rs. 1,50,000 10% of the amount exceeding Rs. 1,00,000Rs. 1,50,001 to Rs. 2,50,000 Rs. 5000+20% of the amount exceeding Rs. 1,50,000Above Rs. 2,50,000 Rs. 25,000+30% of the amount exceeding Rs. 2,50,000

The Switch StatementSwitch is a multiple branch selection statement. This statement tests the value of an expression or condition against a list of constants (integers or character or strings constant but never floating point number). If a match is found, the statements associated with that constant are executed until the break statement or end of switch is reached. The default statement is executed when no match is found. The default statement is optional. If the control flow to the next case below the matching case in the absence of break, this is called fall through. (The fall of control to the following cases of matching case, is called fall through)Syntax:

switch(constant expression) // integer constant{ case 1:

Statement;Break;

case 2:Statement;Break;Default :Statement; }

switch(constant expression) // character constant{ case ‘A’:

Statement;Break;

case ‘B’:Statement;Break;Default :

Statement; }switch(constant expression) //fall through

Page 25: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{case 1:case 2:case 3:Statement;Break;case 4:case 5:case 6:Statement;Break;Default :Statement; }

import java.io.*;class switchdemo{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);System.out.println(" a or A for arif ");System.out.println(" l or L for Laxmi ");System.out.println(" e for exit ");System.out.println("Enter your choice ");char ch=(char)in.read();switch(ch){case 'a':case 'A': System.out.println("Name \t Mohammad Arif "); System.out.println("Address \t Dehradun "); break;case 'l':case 'L': System.out.println("Name \t Laxmi "); System.out.println("Address \t Agra "); break;case 'e':case 'E': System.exit(0);}}}

1. Enter a character and print whether this character is vowal or consonant.2. WAP to find area, perimeter or diagonal of a rectangle according to the choice taking length and

breadth as input. (perimeter =2*(L+B), diagonal=(a2+b2), area=a*b )

The Nested Switch -> when a switch is a part of the statement sequence of another switch then is known as nested switch statement.Syntax:

switch(expression){

case 1:switch(expression)

Page 26: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{case 0:

Statement:break;case 1;

Statement;break;

}break;case 2:

Statement;break;

}

Some points about switch: 1. A switch can only work for equality comparison.2. No two case labels in the same switch can have identical value. 3. Switch can work only constant values like int, byte, short, char, long but never with real values like

double, float.4. A switch statement execute only once when a match is found and never again in the program.

/*a cloth showroom has announced the following seasonal discount on purchasing of items*/Amount mill cloths handlooms items 0 to 100 --> 5.0% 5.0% 101 to 200 -> 7.5% , 7.5% 201 to 300--> 7.5% , 10.0% above 300 --> 10.0% , 15.0%write a program using switch and if statements to compute the amount to be paid ? */import java.io.DataInputStream;class purchase{public static void main(String args[]){DataInputStream in=new DataInputStream(System.in);int amount=0,i=0;float discount,total;char cloth='m';try{System.out.println("Enter the amount ");amount=Integer.parseInt(in.readLine());System.out.println("Enter the Cloth (M/H) ");cloth=(char)System.in.read();}catch(Exception e){}if(amount>=0 && amount<=100)i=1;else if(amount>=101 && amount<=200)i=2;else if(amount>=201 && amount<=300)i=3;else if(amount>300)i=4;switch(i) {

Page 27: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

case 1: if(cloth=='m' || cloth=='M') { discount=0; total=amount-discount; System.out.println("Total Amout of bill is "+ total); } else if(cloth=='h' || cloth=='H') { discount=5.0f; discount=amount*5/100; total=amount-discount; System.out.println("Total Amount of bill is "+total); } break; case 2:

if(cloth=='m' || cloth=='M') { discount=amount*5/100; total=amount-discount; System.out.println("Total Amout of bill is "+ total); } else if(cloth=='h' || cloth=='H') { discount=7.5f; discount=amount*5/100; total=amount-discount; System.out.println("Total Amount of bill is "+total); } break; case 3: if(cloth=='m' || cloth=='M') { discount=amount*7.5f/100; total=amount-discount; System.out.println("Total Amout of bill is "+ total); } else if(cloth=='h' || cloth=='H') { discount=amount*10/100; total=amount-discount; System.out.println("Total Amount of bill is "+total); } break; case 4: if(cloth=='m' || cloth=='M') { discount=amount*10/100; total=amount-discount; System.out.println("Total Amout of bill is "+ total); } else if(cloth=='h' || cloth=='H') {

Page 28: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

discount=amount*15/100; total=amount-discount; System.out.println("Total Amount of bill is "+total); } break; }}}

/****************Buzz number and GCD****************/import java.io.*;class Menu_Driver3{public static void main()throws IOException{int ct=0,i;DataInputStream br=new DataInputStream(System.in);System.out.println("[M-E-N-U]");System.out.println("Enter 1 for checking for BUZZ NUMBER");System.out.println("Enter 2 for checking for GCD");int ch=Integer.parseInt(br.readLine());switch(ch){ case 1: System.out.println("Enter the number for verification="); int n=Integer.parseInt(br.readLine()); if((n/10==7) && (n%7==0)) System.out.println("***BUZZ NUMBER***"); else System.out.println("NOT A buzz number!!!"); break; case 2: System.out.println("Enter two numbers to find there GCD=>"); int n1=Integer.parseInt(br.readLine()); int n2=Integer.parseInt(br.readLine()); for(i=n1<n2?n1:n2;i>=1;i--) { if((n1 % i==0) && (n2 % i==0)) { ct++; break; } } if(ct>0) System.out.println("GCD="+i); else System.out.println("NO FACTOR!!!"); } }}

Iteration or LoopingThe statements that allow a set of instruction to be performed repeatedly until a certain condition is fulfilled are known as iteration or looping. Java provides four kinds of loop

Page 29: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

For, while, do-while, for-each loop. All the loops repeat a set of statement as long as a specified condition remains true. This specified condition is generally referred to as loop control.Elements and parts of loopGenerally a loop has four parts.

1. Initialization expression-> Before entering in a loop , its control variable must be initialized. The initialization of control variable takes palace under initialization expression. The initialization expression gives the loop control a starting point and this expression is executed only once in the beginning of the loop.

2. Test Expression-> this is the expression whose truth value decides whether the loop body will be executed or not. If the test expression evaluates to true the loop body gets executed otherwise the loop is terminated.

3. Update Expression-> the update expression change the value of loop variable . the update expression is executed at the end of the loop after the loop body is executed.

4. The body of the loop-> The statement that are executed repeatedly (as long as the test expression is true) form the body of the loop.

Types of loopGenerally loops are to two types.

1. entry control or pre-tested or top-tested loop-> the loop in which first the test expression is evaluated first of all and if it returns true then the loop body will executed otherwise loop will be terminated, is known as entry control loop.

Example-> for , while , for each.

2. Exit control or post-tested or bottom tested loop-> when loop body is executed first and then the test expression is evaluated, if it evaluates to true then the loop is repeated otherwise terminated. Such type of loop is known as exit control loop. Because testing takes place at the last of loop so in exit control loop, body of the loop will execute at least once whether the testing condition returns true of false.

Example-> do-whileThe for loop ()

Syntax ---------------- for(initialization; testing ; updation)Loop body

Example---1 2 3 4 5 6 7----------10For(int i=1;i<=10;i++)System.out.println (i);Example:1 2 3 4 5-------------------------------------102 4 6 8 10------------------------------------201 4 9 16 25------------------------------------1002 5 10 17 26------------------------------------1010 3 8 15 24-------------------------------------992 4 8 16 32-------------------------------------10241/1 1/ 2 1/3 1/ 4 1/5------------------------------------1/101/1 2/2 3/3 4/4 5/5------------------------------------10/101/2 2/3 3/ 4 4/5 5/6------------------------------------10/111+1/1*1 2+2/2*2 3+3/3*3 4+4/4*4------10+10/10*10x/1 x/2 x/3 x/4 x/5 x/6-----------------------------x/10

(1*2)+(2*3)+(3*4)+(4*5)+(5*6)+(6*7)--------------------(10*11)(1)+(1+2)+(1+2+3)+(1+2+3+4)+(1+2+3+4+5)1+(1*2)+2+(1*2*3)+3+(1*2*3*4)+4+(1*2*3*4*5)

Page 30: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

1/ 2-1/3+1/4-1/5+------------------------------------------------------1/101/1! +1/2!+1/3!+1/4!+1/5!-------------------------------------------------1/10!2-4+6-8+10-12+12-14+14-16----------------------------------------20 a+a/2+a/3+a/4+a/5+---------------------------------------------------a/10 a+a2/2+ a3/3+ a4/4+a5 / 5--------------------------- a10/10a/1!+a/2!+a/3!+a/4!+a/5!+---------------------------------------------a/10!(a+1)+(a+2)+(a+3)+(a+4)+(a+5)-----------------------------+(a+10)1-a/2+a/3-a/4+a/5-a/6+a/7--------------------------------------a/20A+1/3+ a+2/5+ a+3/7+ ---------------------------------------a+10/131/a + 2/a2 + 3/a3 + 4/a4 + 5/a5 -------------------------10/a10

a-a3/5+ a5/9+ a7/13+a9 / 17--------------------------- n-termsThe for loop variations

Java offers several variation of for loop that increase the flexibility and applicability of for loop.1. Multiple initialization and updation-> a for loop can contain multiple initialization and update

expression and these expression are separated by comma.Example->>>>int i,j;

for(i=1,j=1; i<=10 && j<=10; i++,j++){

System.out.println(i);System.out.println(j);

}

Optional expression-> all the expression of a for loop are optional, we can skip any of the expression.Example->>>>>>>int i=1;for(;i<=10;){System.out.println(i);i++;}Ori=1;for(; ; ) //infinite loop{System.out.println(i);i++;}Orfor(;;) //infinite loopSystem.out.println(“hello”);Orfor(i=1; i; i++); //empty loopOrlong i;For(i=1;i<=10000000000;i++); // delay loop

/*prime number*/import java.io.*;

Page 31: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

class prime{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int num;System.out.println("Enter a number ");num=Integer.parseInt(br.readLine());int i,c=0;for(i=1;i<=num;i++){if(num%i==0){c++;}}if(c==2)System.out.println("Number is prime ");elseSystem.out.println("Number is not prime ");}}

/*fibonacci series*/import java.io.*;class fibonacci{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int limit,i,a,b,s=0;System.out.println("Enter the limit ");limit=Integer.parseInt(br.readLine());a=0;b=1;System.out.print(a+" "+b+" ");s=a+b;for(i=0;i<=limit;i++){System.out.print(s+" ");a=b;b=s;s=a+b;}}}

Nested for LoopA loop may contain another loop in its body. This form of loop is called nested loop. But in a nested loop , the inner loop must terminate before the outer loop.Example:for(int i=1;i<=3;i++){

Page 32: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

for(j=1;j<=i;j++)System.out.print(j);System.out.println();}Output:

11 21 2 3

/***************Floayed Triangle **********************/class fload{public static void main(String args[]){int i,j,k=1;for(i=1;i<=13;i++){for(j=1;j<=i;j++){System.out.print(k+" ");k++;}System.out.println();}}}Output :

/***************Floayed Triangle **********************/class fload{public static void main(String args[]){int i,j,k=1;for(i=1;i<=13;i++){for(j=i;j>=1;j--){k=j%2;System.out.print(k+" ");}System.out.println();}}

Output :

Page 33: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

//**************************shape*****************************//class shape{public static void main(String args[]){int i,j,k;for(i=1;i<=5;i++){for(k=5;k>i;k--){System.out.print(" ");}for(j=i;j>=1;j--){System.out.print(i);System.out.print(" ");}System.out.println();}}}

/*Find out the factor of a number*/While loopSyntax->>>>>>>>

while(test expression) // for single statementLoop bodyOr

while(test expression) // for multiple statement{Loop body}

/********a program to calculate factorial of a number*****/class factorial{public static void main(String args[]){int num, f=1,i;i=1;while(i<=num){f=f*i;}System.out.println(“Factorial is “+f);}}

Page 34: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

variations of while loopWhile loop may also have variations. It can be empty or infinite loop.

Example:long wait=0;while(++wait<100000) //time delay loop;;;;;;

int i=1;while(i<=10) //infinite loopSystem.out.println(“hello”);

while(true)System.out.println(“hello”); //infinite loop

while(false)System.out.println(“hello”); //this loop will not work , because test expression is falseQuestion: Reverse a number./*reverse a multidigit number*/import java.io.*;class reverse{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);int num;System.out.println("Enter a multidit number ");num=Integer.parseInt(in.readLine());int r,s=0;while(num>0){r=num%10;s=s*10+r;num/=10;}System.out.println(s);}}

Question: Do the sum of all digits of a number.Question: Do the sum of first and last digit of a number.Question: Sunny Number.Question: Armstrong number.Question: Palindrome Number.Question: Perfect Number.Question: Buzz Number.Question: Automorphic Number.import java.io.*;class automorphic{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int num;

Page 35: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println("Ente a number ");num=Integer.parseInt(br.readLine());

int sq=num*num;

while(num>0){if(num%10 != sq%10)break;

num/=10;sq/=10;}

if(num==0)System.out.println("Automorphic number ");elseSystem.out.println("Not automorphic number ");}}

Question: Special Number.Question: Magic Number./*******magic number*/import java.io.*;class magic{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);int num;System.out.println("Enter a number ");num=Integer.parseInt(in.readLine());int s;while(true){ s=0;while(num>0){int r=num%10;s=s+r;num/=10;}if(s>=1 && s<=9)break;elsenum=s;}

if(s==1)System.out.println("Number is magic ");elseSystem.out.println("number is not magic ");}}

Page 36: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Do-While loopUnlike for and while loop, the do-while loop evaluates its test expression at the end to the loop after executing its loop body statements. This means that a do-while loop always executes at least once.Syntax:do { statement} while(text expression);

Example:char ch=’a’;do {System.out.println(ch);ch++;}while(ch<=’z’);

/*odd looping*/import java.io.*;class oddlooping{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);int num,s=0,ch=1;do{System.out.println("Enter a number ");num=Integer.parseInt(in.readLine());s=s+num;System.out.println("Do you want to enter more numbers (1: for yes ) ");ch=Integer.parseInt(in.readLine());}while(ch==1);System.out.println("Sum of your entered number is "+s);}}

/*odd looping to find max number*/import java.io.*;class maxnum{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);int num,max,ch=1;System.out.println("Enter a number ");num=Integer.parseInt(in.readLine());max=num;do{System.out.println("Enter a number ");num=Integer.parseInt(in.readLine());

Page 37: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

if(max<num)max=num;System.out.println("Do you want to enter more numbers (1 for yes )");ch=Integer.parseInt(in.readLine());}while(ch==1);System.out.println("Maximum number is "+max);}}

/********HCF (Highes Commna Factor)****/class HCF{public static void main(String args[]){int n1=50, n2=100;int r=1, q=0, h=0;if(n1>n2){while(r!=0){h=n2;r=n1%n2;n2=r;}}else{while(r!=0){h=n1;r=n2%n1;n1=r;}}System.out.println(h);}}

/*enhace for or for each loop with command line argument*/class enhance_for{public static void main(String args[]){for(String s:args){System.out.println(s);}}}

Comparison of loopsThought you can use all loops in almost all situations yet there are some situations where one loop fits better then the other.

Page 38: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

The for loop is appropriate when you know in advance how many times the loop will be executed. The other two loops while and do-while loops are more suitable in the situations where it is not known before hand when the loop will terminates. The while should be preferred when you may not want to execute the loop body even once and the do-while loop would be preferred when you are sure you want to execute the loop body at least once.

Jump StatementsThe jump statements unconditionally transfer program control within a function. Java has three statements that perform an unconditional branch i.e. jump statements. return, break, continue. return statement we can use anywhere in the program whereas break and continue are used inside smallest enclosing like loops etc. beside these statements java also provide a standard library function System.exit(1) that helps you break out of a program. The return statement is used to return from a function.

break statementsthe break statements enables a program to skip over part of the code. A break statement terminates the smallest enclosing while, do-while, for or switch statement. Execution resumes at the statement immediately following the body of the terminated statement. If a break statement appears in a nested loop, then it causes an exit from only then inner loop.import java.io.*;class break_demo{ public static void main(String args[]) throws IOException{ DataInputStream in=new DataInputStream(System.in);double area,r;int i=1;while(i<=10){ System.out.println(“Enter the radius “);r=Double.parseDouble(in.readLine());if(r>0){area=3.14*r*r;System.out.println(“The area is “+ area);}elsebreak;i++;}}}The continue statementThis statement forces the next iteration of the loop to take place, skipping any code in between.Example:import java.io.*;class break_demo{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);double area,r;int i=1;while(i<=10){System.out.println(“Enter the radius “);r=Double.parseDouble(in.readLine());if(r>0){area=3.14*r*r;

Page 39: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println(“The area is “+ area); }elsecontinue;i++;}}}

Labels and Branching statementsLabel statement in java is just similar to the goto-label statement of c and c++. Here we can use break and continue statement with labels, and by the combination of jump statement and label we can create labeled jump statements. these statements are generally Applied in block and nested loops. Label in these statement can be any valid java identifier , generally label is placed before the statement or loop or block ended with colon like this:-Lable :Statement-----------------Example:outer:for(i=0;i<n;i++){inner:

for(j=0;j<m;j++){

If(i>j){

System.out.println(i+”>”+j);break outer;

}else if(i==j)break inner;

}}

ArrayAn array is a collection of constants of similar data type which are reference by a common name i.e. the array name.Array contains continuous memory location. The lowest address corresponds to the first element and the highest address to the last element. Array can be of any data type but it will store the elements of its own type, i.e. array of integer type will store integers only not a event a single float a char it can store. We need array mainly store multiple value of similar type for which multiple declaration of variable is not possible. Like if we want to store marks of fifty students then it is not possible to declare fifty variables for then but we will simple use an array of integer for it.Array index always starts from 0, so to visit the last element’s position will be one less than the total size of array.Subscript: subscript is the variable that we use to visit the elements of array. It can be any valid character or identifier.Types of array-> Array are of two types.

1. Single dimension array

Page 40: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

2. Multidimensional array or two dimensional array

Single Dimension Array-> An array with single row of elements is known as single dimension array. It represents its elements as a list and there is no tabular representation of elements.Declaration for array: datatype name_o_ array[]=new datatype [size or dimension]int marks[]=new int[10]initialization of array:int marks[]={10,20,30,40,50};

/*array simple program*/import java.io.*;class arraydemo{public static void main(String ags[]) throws IOException{DataInputStream in=new DataInputStream(System.in);int list[]=new int[5];int i;System.out.println("Enter elements of array ");for(i=0;i<5;i++)list[i]=Integer.parseInt(in.readLine());

System.out.println("Array elements are.....");for(i=0;i<5;i++)System.out.println(list[i]);}}

/********Array with for each loop *********/class foreach{public static void main(String args[]){int arr[]={1,2,3,4,5};System.out.println("Array elements by foreach loop ");for(int i:arr)System.out.println(i);}}

Two Dimensional Arrays:A 2-d array is a collection of elements placed in M rows and N columns. The syntax used to declare a 2-d array includes two subscripts, of which one specifies the number of rows and the other specifies the number of columns of an array. These two subscripts are used to reference an element in an array. For example array [3][4] in a 2-d array containing 3 rows and 4 columns and array[0][2] is an element placed at 0 th row and 2nd

column in the array. The two dimensional array is also called a matrix. Operations of array:

1. Traversal. 2. Search 3. Insertion 4. Deletion 5. Sorting6. Merging 7. Reversing.

Searching: Searching is the technique which finds the location of a given element in a list. The search is said to be successful or unsuccessful depending on whether the element that is to be searched is found or not. Searching are of two types.

Page 41: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Linear search and binary searchLinear search-> this is the simplest method of searching. In this method the element to be found is sequentially searched in the list. This method can be applied to a sorted or unsorted list. Searching is case of a sorted list starts form 0th element and continues until the element is found or an element whose value is greater than the value being searched is reached. As against this, searching in case of unsorted list starts from the 0th element and continues until the element is found or the end of list is reached.Example://*******************linear search ************//import java.io.*;class linear{public static void main(String args[]) throws IOException {BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int arr[]=new int[10];int i,no;System.out.println(“enter the element of array “);for(i=0;i<10;i++){arr[i]=Integer.parseInt(br.readLine());}int flage=0;System.out.println(“enter the no .you want to search “);no=Integer.parseInt(br.readLine());for(i=0;i<=10;i++){if(no==arr[i]){flage=1;break;} }

if(flage==1)System.out.println(“no is prsetn at the position “+ (i+1));elseSystem.out.println(“no is not present “);}}

Binary Search: This method is fast as compared to the linear searching technique. This method requires that the list of elements be in sorted order.

In this method to search an element we compare it with the element present at the center of the list. If it matches then the search is successful.Otherwise the list is divided into two halves (half): one from 0 th

element to the center element (first half), and another from center element to the last element (second half). As a result all the elements in first half are smaller than the center element, whereas all the elements in second half are greater than the center element. The searching now will proceed in either of the two halves depending upon where the element is greater or smaller than the center element. if the element is smaller than the center element than the searching will be done in the first half, otherwise in the second half.

Same process of comparing the required element with the center element and if not found then dividing the elements into two halves is repeated for the first half or second half. This procedure is repeated till the element is found or the division of half parts gives one element.Example://***********************Binary search ***************//import java.io.*;class binary{ public static void main(String args[]) throws IOException

Page 42: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int arr[]=new int[10];int i,u,l,m=0;int no;System.out.println(“enter the element of array in sorted form “);for(i=0;i<10;i++){ arr[i]=Integer.parseInt(br.readLine()); }int c=0;u=9;l=0;System.out.println(“enter the element you want to search “);no=Integer.parseInt(br.readLine());while(l<=u){ m=(l+u)/2;if(no>arr[m])l=m+1;else if(no<arr[m])u=m-1;else{ c=1;break;}}if(c==1)System.out.println(“no is present at the position “+(m+1));elseSystem.out.println(“no is not present “);}}

SortingSorting means arranging a set of data in some order. There are different methods that are used to sort the data in ascending or descending order. These methods can be divided into two categories. Internal Sorting: if all the data that is to be sorted can be placed at a time in memory then internal sorting methods are used.

1. Bubble sort. 2. Selection sort. 3. Quick sort4. Insertion sort 5. Binary Tree sort (BT-sort) 6. Heap Sort. 7. Merge Sort.

External Sorting: When the data is to be sorted is so large that some of the data is present in the memory and some is kept in auxiliary memory (hard disk, floppy, tape, etc.), then external sorting methods are used. In this technique data from the disk is loaded into memory part by part and each part that is loaded is sorted and the sorted data is stored into some intermediate file. Finally all the sorted parts present in different intermediate files are merged into one single file. Bubble Sort-> in this method to arrange elements in ascending order, to begin with the 0 th element is compared with the 1st element. If it is found to be greater than the 1st element then they are interchanged. Then the first element is compared with the second element, if it is found to be greater, then they are interchanged. In the same way all the elements are compared with their next element and are interchanged if required. This is the first iteration and on completing this iteration the largest element gets placed at the last position. Similarly in the second iteration the comparisons are made till the last but one element and this time the second largest element gets placed at the second last position in the list. As a result after all the iterations the list becomes a sorted list. Example: Bubble Sort import java.io.DataInputStream;class bubblesort{ public static void main(String args[]){ DataInputStream in=new DataInputStream(System.in);int a[]=new int[5];int i,j,t;

Page 43: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println(“enter the elements of array “);try { for(i=0;i<=4;i++){ a[i]=Integer.parseInt(in.readLine());}}catch(Exception e){}for(i=0;i<5;i++){ for(j=0;j<(5-i-1);j++){ if(a[j]>a[j+1]){ t=a[j];a[j]=a[j+1];a[j+1]=t;}}}System.out.println(“this is sorted array “);for(i=0;i<5;i++){ System.out.println(a[i]);}}}

Selection Sortthis is the simplest method of sorting. In this method, to sort the data in ascending order, the 0 th element is compared with all other elements. If the 0the elements found to be greater than the compared element, then they are interchanged. So after the first iteration the smallest element is placed at the 0 th position. The same procedure is repeated for the 1st element and so on. Example:import java.io.DataInputStream;class selection{public static void main(String args[]){DataInputStream in=new DataInputStream(System.in);try{int n;System.out.println(“enter the size of array “);n=Integer.parseInt(in.readLine());int i,arr[];arr=new int[n];System.out.println(“enter the elements of array list”);for(i=0;i<n;i++){arr[i]=Integer.parseInt(in.readLine());}int j,t;for(i=0;i<n-1;i++){for(j=i+1;j<n;j++){if(arr[i]>arr[j]){t=arr[i];arr[i]=arr[j];arr[j]=t;}}}System.out.println(“the sorted list is like this”);for(i=0;i<n;i++){System.out.println(arr[i]);}}catch(Exception e){}}

Page 44: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}

Insertion SortInsertion sort is implemented by inserting a particular element at the appropriate position. In this method, the first iteration starts with comparison of 1st element with the 0th element. In the second iteration 2nd element is compared with the 0th element and 1st element. In general, in every iteration an element is compared with all elements before it. During comparison if is found that the element in question can be inserted at a suitable position then space is created for it by shifting the other elements one position to the right and inserting the element at the suitable position. This procedure is repeated for all the elements in the array.Example: /****************insertion sort****************/import java.io.*;class insertion2{ public static void main(String args[]) throws IOException{ DataInputStream in=new DataInputStream(System.in);int list[]=new int[5];int i;System.out.println(“Enter elements of list “);for(i=0;i<list.length;i++)list[i]=Integer.parseInt(in.readLine());

for(i=1;i<list.length;i++){int key=list[i];int p=i;while(p>0 && list[p-1]>key){list[p]=list[p-1];p--;}list[p]=key; }System.out.println(“The sorted list is “);for(i=0;i<list.length;i++)System.out.println(list[i]+” “); }}

Merge SortMerging means combining two sorted lists into one sorted list. For this the elements from both the sorted lists are compared. The smaller of both the elements is then stored in the third array. The sorting is complete when all the elements from both the list are placed in the third list.Example: /************************Merge sort*******************/import java.io.*;class mergesort{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);int a[]=new int[5];int b[]=new int[5];int c[]=new int[10];int i,j,k;System.out.println("Enter elements of fist array ");for(i=0;i<5;i++)a[i]=Integer.parseInt(in.readLine());

System.out.println("Enter elements of second array ");

Page 45: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

for(i=0;i<5;i++)b[i]=Integer.parseInt(in.readLine());

int t=0;for(i=0;i<4;i++){for(j=i+1;j<5;j++){if(a[i]>a[j]){t=a[i];a[i]=a[j];a[j]=t;}

if(b[i]>b[j]){t=b[i];b[i]=b[j];b[j]=t;}}}

for(i=j=k=0;i<=9;){if(a[i]<=b[j])c[k++]=a[i++];elsec[k++]=b[j++];

if(i==5 || j==5)break;}

for(;i<=4;)c[k++]=a[i++];

for(;j<=4;)c[k++]=b[j++];

for(i=0;i<10;i++)System.out.print(c[i]+" ");}}

/******frequency**********/import java.io.*;class frequency{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int list[]=new int[10];int i;

Page 46: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println("Enter elements of array ");for(i=0;i<list.length;i++)list[i]=Integer.parseInt(br.readLine());

int a,k;

for(i=0;i<list.length;i++){a=0;k=1;for(int j=0;j<list.length;j++){if(j>=i){if(list[i]==list[j] && (j!=i))k++;}else if(list[i]==list[j])a=1;}if(a!=1)System.out.println("Occurence of "+list[i]+" is "+ k );}}}

/***********copy array**************/class copyarray{public static void main(String args[]) {int list[]={1,2,3,4,5};int a[]=new int[5];a=list;System.out.println("Array elements are ");for(int i=0;i<a.length;i++)System.out.println(a[i]);}}

/********************copy array************/class copyarray2{public static void main(String args[]){char name[]={'m','o','h','a','m','m','a','d',' ','a','r','i','f'};char firstname[]=new char[20];System.arraycopy(name,0,firstname,0,8);System.out.println(new String (firstname));}}

Page 47: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Two-D-Array (Matrix) class matrix{public static void main(String args[]){int matrix[][]={{10,20,30},{40,50,60},{70,80,90}};int i,j;System.out.println("Elements of array ");for(i=0;i<3;i++){for(j=0;j<3;j++){System.out.print(matrix[i][j]+" ");}System.out.println();}}}

/*****************************************/import java.io.*;class matrix2{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

int matrix[][]=new int[3][3];int i,j;System.out.println("Enter elements of array ");for(i=0;i<3;i++){for(j=0;j<3;j++){matrix[i][j]=Integer.parseInt(br.readLine());}System.out.println();}

System.out.println("Elements of array ");for(i=0;i<3;i++){for(j=0;j<3;j++){System.out.print(matrix[i][j]+" ");}System.out.println();}}}

Page 48: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

/*diagonals or (alternative numbers of matrix)*//************diagonals print************/import java.io.*;class diagonals{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int matrix[][]=new int[3][3];int i,j;System.out.println("Enter elements of array ");for(i=0;i<3;i++){for(j=0;j<3;j++){matrix[i][j]=Integer.parseInt(br.readLine());}}

System.out.println("\n Diagnals are ");for(i=0;i<3;i++){for(j=0;j<3;j++){if(i+j==2 || i==j)System.out.print(matrix[i][j]);elseSystem.out.print(" ");}System.out.println();}}}

/******************rows sum****************//************diagnals print************/import java.io.*;class rowssum{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int matrix[][]=new int[3][3];int i,j,s=0;System.out.println("Enter elements of array ");for(i=0;i<3;i++){for(j=0;j<3;j++){matrix[i][j]=Integer.parseInt(br.readLine());}}

System.out.println("\n row sum is ");for(i=0;i<3;i++)

Page 49: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{s=0;for(j=0;j<3;j++){System.out.print(matrix[i][j]);s=s+matrix[i][j];}System.out.println("-->"+s);}}}

/****************Column sum***************//************column sum************/import java.io.*;class columnssum{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int matrix[][]=new int[3][3];int i,j,s=0;System.out.println("Enter elements of array ");for(i=0;i<3;i++){for(j=0;j<3;j++){matrix[i][j]=Integer.parseInt(br.readLine());}}

System.out.println("\n column sum is ");for(i=0;i<3;i++){for(j=0;j<3;j++){System.out.print(matrix[i][j]);}System.out.println();}

System.out.println("\n-------------------");for(i=0;i<3;i++){s=0;for(j=0;j<3;j++){s=s+matrix[j][i];}System.out.print(s+" ");}}}

Page 50: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

/************Symatric matrix************/1 2 32 4 53 5 6

import java.io.*;class symatric{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int matrix[][]=new int[3][3];int i,j,s=0;System.out.println("Enter elements of array ");for(i=0;i<3;i++){for(j=0;j<3;j++){matrix[i][j]=Integer.parseInt(br.readLine());}}

for(i=0;i<3;i++){for(j=0;j<3;j++){if(matrix[i][j]==matrix[j][i])s++;System.out.print(matrix[i][j]);}System.out.println();}

if(s==9)System.out.println("matrix is symatric");elseSystem.out.println("Matrix is not symatric ");

}}

/******half Matrix******/1 2 3

5 69

import java.io.*;class halfmatrix{public static void main(String args[]) throws IOException

Page 51: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int list[][]=new int[3][3];int i,j;System.out.println("Enter the element of matrix ");for(i=0;i<3;i++){for(j=0;j<3;j++)list[i][j]=Integer.parseInt(br.readLine());}

for(i=0;i<3;i++){for(j=0;j<3;j++){if(i<=j)//if(i>=j)//if(!(i<j))If(!(i+j==1 || i+j==0))System.out.print(list[i][j]);elseSystem.out.print(" ");}System.out.println();}}}

/*Matrix Multiplication program*/import java.io.*;class matrixmult{public static void main(String args[]) throws IOException{DataInputStream in =new DataInputStream(System.in);int m1[][]=new int[3][3];int m2[][]=new int[3][3];int m3[][]=new int[3][3];int i,j,k;System.out.println("Enter elements of first matrix ");for(i=0;i<3;i++){for(j=0;j<3;j++){m1[i][j]=Integer.parseInt(in.readLine());}}

System.out.println("Enter elements of second matrix ");for(i=0;i<3;i++){for(j=0;j<3;j++){m2[i][j]=Integer.parseInt(in.readLine());

Page 52: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}}

System.out.println(" elements of first matrix are ....");for(i=0;i<3;i++){for(j=0;j<3;j++){System.out.print(m1[i][j]);}System.out.println();}

System.out.println("Elements of second matrix ");for(i=0;i<3;i++){for(j=0;j<3;j++){System.out.print(m2[i][j]);}System.out.println();}

/*Matrix multiplication*/for(i=0;i<3;i++){for(j=0;j<3;j++){m3[i][j]=0;for(k=0;k<3;k++){//m3[i][j]+=m1[i][k]*m2[k][j];m3[i][j]=m3[i][j]+m1[i][k]*m2[k][j];}}}

System.out.println("matrix multiplication result is ");for(i=0;i<3;i++){for(j=0;j<3;j++){System.out.print(m3[i][j]);}System.out.println();}}}

Reverse Matrix???????

Page 53: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

StringString is the sequence of characters. Java offers three classes to work with character data i.e. string.

1. Character class-> this class object can hold single character. This class offers many methods to manipulate or inspect single character data.

2. String class-> this class object can hold unchanging string (immutable string) i.e. once initialized its contents cannot be modified.

3. StringBuffer class-> this class object can hold changeable (mutable) string that can be changed or modified. This class creates string of flexible length that can be modified in terms of both length and content. We can insert character and sub string in the middle of a string, or append another string to the end.

Character class functions1. Character.isLetter(variable or character) -> checks whether a character is a letter or not.2. Character.isDigit(variable or character) -> checks whether a character is a digit or not.3. Character.isUpperCase(variable or character) -> checks whether a character is in upper case or not4. Character.isLowerCase(variable or character) -> checks whether a character is in Lower case or not5. Character.toUpperCase(variable or character) -> convert a character to upper case6. Character.toLowerCase(variable or character) -> convert a character to Lower case

/***********character class class function*************/class charfunction{public static void main(String args[]){System.out.println(Character.isLetter('a'));System.out.println(Character.isDigit('1'));System.out.println(Character.isLowerCase('a'));System.out.println(Character.isUpperCase('A'));System.out.println(Character.toLowerCase('A'));System.out.println(Character.toUpperCase('a'));}}

String Functions1. Str.toLowerCase()-> converts all the character of string into lower case.2. Str.toUpperCase()->converts all the character of string into upper case.3. Str.replace(‘m’,’n’)-> replaces all the occurrence of character ‘m’ with ‘n’ in the string str .4. Str.trim(); -> Remove all the spaces from the beginning as well as the end of the string.5. Str.equals() -> checks whether two strings are equals or not.6. Str.Length() -> returns the length of string i. e number of character in that string.7. Str.charAt(n) -> returns a character of the string at nth position, as it starts counting from 0th position.8. Str.substring(n) -> returns substring starting from nth character of the string. It starts counting from

0th position.9. Str.substring(m,n) -> returns a substring out of nth character leaving first mth character of the string.

Example understanding substring(5,10) will return stand returns out of 10 characters, leaving first 5 characters of the string.

10. Str.concat(str2) -> concatenates str and str2. Str2 will be added after str.11. Str.indexOf(‘m’) -> Returns the position of the first occurrence of ‘m’ in the string str.12. Str.lastIndexOf(,m,) -> returns the position of the last occurrence of ‘m’ in the string str.13. Str.indexOf(‘m’,’n’) -> returns the position of ‘m’ in the string from nth position.14. Str.compareTo(str2) -> (Will return ASCII value difference )returns negative if str<str2

Page 54: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Positive if str>str2Zero if str=str2

15. Str.equalsIgnoreCase(str2) -> returns true if str and str2 are equal after ignoring cases of the strings and false, if they are unequal.

16. Str.endsWith(str2) -> returns true if the string str ends with the suffix that is present in str2. example str=”computer is application”Str2=”fun”Str.endsWith(str2)Result =false.

17. Str.startsWith(str2)-> returns true if the string str starts with the prefix that is present in str2. example str=”computer is application”Str2=”computer”Str.startsWith(str2)Result =true /*******String class function*******/class stringfunction{public static void main(String args[]){String str="MohammAMMAD ARIF";System.out.println(str.toLowerCase());System.out.println(str.toUpperCase());System.out.println(str.replace('R','S'));String s=" arif ";System.out.println(s.trim());System.out.println(s.equals(str));System.out.println(str.length());System.out.println(str.charAt(5));System.out.println(str.substring(9));System.out.println(str.substring(9,13));System.out.println(str.concat(s));System.out.println(str.indexOf('M'));System.out.println(str.lastIndexOf('M'));System.out.println(str.indexOf('A',2));

String st1,st2;st1="arif";st2="anif";System.out.println(st1.compareTo(st2));st1="arif";st2="ARIF";System.out.println(st1.equalsIgnoreCase(st2));System.out.println(st1.endsWith("if"));System.out.println(st1.startsWith("ar"));}}

String Buffer Function1. Str.append(str2) -> adds string str2 at the end of string str.2. Str.setCharAt(I,c) -> changes the character at the index i with character c.3. Str.insert(I,j) -> insert string p at ith index in the string str.4. Str.delete(I,j)-> deletes characters from ith index to jth index.5. Str.setLength(n) -> used to set the length of string buffer for n characters storage. If the stored string

in str is bigger than it is truncated otherwise contains garbage value in the empty space.6. Str.reverse() -> used to reverse the string.

Page 55: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

/****string buffere class function*******/class string_buffer{public static void main(String args[]){StringBuffer str=new StringBuffer("Hello java");System.out.println(str.append(" and c++"));System.out.println(str.insert(4,"abc"));System.out.println(str.delete(4,7));System.out.println(str.reverse());

StringBuffer s=new StringBuffer("Mohammad Arif");s.setCharAt(8,'_');System.out.println(s);

StringBuffer s2=new StringBuffer("Hello java");s2.setLength(4);System.out.println(s2);}}

Some operation on string:import java.io.*;class string_by_switch{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);int choice;String str;System.out.println("Enter a string ");str=in.readLine();int i,c=0;System.out.println("1 : count character ");System.out.println("2 : count a specifict character ");System.out.println("3 : count words ");System.out.println("4 : count vowals ");System.out.println("5 : count spaces ");System.out.println("6 : exit ");System.out.println( "Enter your choice ");choice=Integer.parseInt(in.readLine());

switch(choice) { case 1: for(i=0;i<str.length();i++) if(str.charAt(i)!=' ') c++; System.out.println("number of characters "+c); break; case 2: System.out.println("Enter a character that you want to count "); char ch=(char)in.read();

Page 56: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

for(i=0;i<str.length();i++) if(str.charAt(i)==ch) c++; System.out.println(ch +" comes "+ c +" times in this string "); break; case 3: str=" "+str; for(i=0;i<str.length();i++) if(str.charAt(i)==' ' && str.charAt(i+1)!=' ') c++; System.out.println("This String contain "+ c+" words"); break; case 4: for(i=0;i<str.length();i++) if(str.charAt(i)=='a' || str.charAt(i)=='e' || str.charAt(i)=='i' || str.charAt(i)=='o' || str.charAt(i)=='u' ) c++; System.out.println("Number of vowals in this string is "+c); break; case 5: for(i=0;i<str.length();i++) if(str.charAt(i)==' ') c++; System.out.println("Number of spaces in this string are "+c); break; case 6: System.exit(1); }}}Example: /***"Mohammad Arif Ansari" differenc opration on the string****/import java.io.*;class initials{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);System.out.println("Enter a string ");String str=in.readLine();System.out.println("1 : M.A.A. ");System.out.println("2 : M.A.Ansari ");System.out.println("3 : Ansari M.A.");System.out.println("4 : exit ");System.out.println("Enter your choice ");int choice=Integer.parseInt(in.readLine());int i,n,p=0;char ch;

switch(choice){case 1: n=str.charAt(0); if(n>=97 && n<=122) n=n-32;

Page 57: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

ch=(char)n; System.out.print(ch+"."); for(i=1;i<str.length();i++) { if(str.charAt(i)==' ' && str.charAt(i+1)!=' ') { n=str.charAt(i+1); if(n>=97 && n<=122) n=n-32; ch=(char)n; System.out.print(ch+"."); } } break;case 2: n=str.charAt(0); if(n>=97 && n<=122) n=n-32; ch=(char)n; System.out.print(ch); for(i=1;i<str.length();i++) { if(str.charAt(i)==' ' && str.charAt(i+1)!=' ') { System.out.print("."); p=i; n=str.charAt(i+1); if(n>=97 && n<=122) n=n-32; ch=(char)n; System.out.print(ch); } } for(i=p+2;i<str.length();i++) System.out.print(str.charAt(i)); break;

case 3: for(i=1;i<str.length();i++) { if(str.charAt(i)==' ' && str.charAt(i+1)!=' ') p=i; } n=str.charAt(p+1); if(n>=97 && n<=122) n=n-32; ch=(char)n; System.out.print(ch); for(i=p+2;i<str.length();i++) System.out.print(str.charAt(i)); System.out.print(" "); n=str.charAt(0); if(n>=97 && n<=122) n=n-32; ch=(char)n;

Page 58: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.print(ch+"."); for(i=1;i<=p;i++) { if(str.charAt(i)==' ' && str.charAt(i+1)!=' ') { n=str.charAt(i+1); if(n>=97 && n<=122) n=n-32; ch=(char)n; System.out.print(ch+"."); } } break;case 4: System.exit(1); } }

}

/*frequence of each word in a string*/import java.io.*;class frequence{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);System.out.println("Enter string ");String str=in.readLine();int i,j,k;int c,s,n;for(i=97, j=65; i<=122 && j<=90; i++, j--){c=0;s=0;for(k=0;k<str.length();k++){n=str.charAt(k);if(n==i)s++;if(n==j)c++;}if(s>0)System.out.println((char)i+" comes "+ s+" times ");if(c>0)System.out.println((char)j+" comes "+ c+" times ");}

}}

/**Count the frequency of each character in a string***/#include<iostream.h>#include<conio.h>#include<stdio.h>#include<string.h>

Page 59: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

void main(){clrscr();char a[30],c;int i,j,k,capital,small,n;cout<<"Enter string ";gets(a);int l=strlen(a);for(i=97, k=65 ;i<=122 && k<=90;i++,k++){capital=0;small=0;for(j=0;j<l;j++){n=a[j];if(n==i)capital++;if(n==k)small++;}if(capital>0){c=(char)i;cout<<c<<" comes "<<capital<<" times \n";}if(small>0){c=(char)k;cout<<c<<" comes "<<small<<" times \n";}}

getch();}

/***********consecutive or magic string*********/import java.io.*;class consecutives {public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);String str;System.out.println("Enter a string ");str=in.readLine();str=str.toLowerCase();int i;for(i=0;i<str.length()-1;i++){int n1=str.charAt(i);int n2=str.charAt(i+1);if(n1+1==n2)c=1;}if(c==1)System.out.println("It is consecutive string ");elseSystem.out.println("It is not consecutive string ");}}

Page 60: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

/***********piglatin form of string*********/import java.io.*;class piglatin{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);String str;

System.out.println("Enter a string ");str=in.readLine();int p=0,i;for(i=0;i<str.length();i++){if(str.charAt(i)=='a' || str.charAt(i)=='e' || str.charAt(i)=='i' || str.charAt(i)=='o' || str.charAt(i)=='u'){p=i;break;}}for(i=p;i<str.length();i++)System.out.print(str.charAt(i));

for(i=0;i<p;i++)System.out.print(str.charAt(i));}}

/********frequence of word in string*********/import java.io.*;class wordcount{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);String str,s="";System.out.println("Enter a string ");str=in.readLine();str=" "+str;str=str.toLowerCase();System.out.println("Enter the word that is to count ");String word=in.readLine();char ch;int c=0;for(int i=0;i<str.length();i++){if(str.charAt(i)!=' ')s=s+str.charAt(i);else{if(s.compareTo(word)==0)c++;s="";}

Page 61: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}System.out.println("Frequence of word " + word +" is "+ c);}}

/*************convert words****************/class converts{public static void main(String argsp[]) {String str="JANUARY 26 IS CELEBRATED AS REPUBLIC DAY OF INDIA";int i;str=str+" " ;String s="", cstr="";char ch;for(i=0;i<str.length();i++){ch=str.charAt(i);if(ch!=' ')s=s+ch; else{if(s.equals("JANUARY "))cstr+="AUGUST ";else if(s.equals("26"))cstr+="15 ";else if(s.equals("REPUBLIC"))cstr+="INDIPENDANCE ";elsecstr+=s+" ";s="";}}System.out.println(cstr);}}

/*cut a substring from a string and return it to the main after doing reverse*/import java.io.*;class cutreverse{String reverse(String str, int sp, int noc){String subs=str.substring(sp, sp+noc);System.out.println(subs);String rvstr="";for(int i=subs.length()-1;i>=0;i--)rvstr=rvstr+subs.charAt(i);return rvstr;}

Page 62: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

public static void main(String args[]){cutreverse obj=new cutreverse();String s=obj.reverse("Hello java and c++",6,4);System.out.println(s);}}

/***replace first occurance of a word************/import java.io.*;class replace{public static void main(String argsp[]) throws IOException{DataInputStream in=new DataInputStream(System.in);System.out.println("Enter a multiword string ");String str=in.readLine();int i,c=0;str=str+" " ;String s="", cstr="";char ch;System.out.println("enter the word to replace ");String rpt=in.readLine();System.out.println("Enter the word replac with ");String rpw=in.readLine();for(i=0;i<str.length();i++){ch=str.charAt(i);if(ch!=' ')s=s+ch; else{if(s.equals(rpt)){c++;if(c>1)cstr+=s+" ";elsecstr+=rpw+" ";}elsecstr+=s+" ";s="";}}System.out.println(cstr);}}

/*replace ginve word by given word**//*Hello how are you and where are you*//*Hello how were you and where were your*/

import java.io.*;

Page 63: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

class replace2{public static void main(String argsp[]) throws IOException{DataInputStream in=new DataInputStream(System.in);System.out.println("Enter a name ");String str=in.readLine();int i;str=str+" " ;String s="", cstr="";char ch;System.out.println("enter the word to replace ");String rpt=in.readLine();System.out.println("Enter the word replac with ");String rpw=in.readLine();for(i=0;i<str.length();i++){ch=str.charAt(i);if(ch!=' ')s=s+ch; else{if(s.equals(rpt)){cstr+=rpw+" ";}elsecstr+=s+" ";s="";}}System.out.println(cstr);}}

/*CUSTOMER VISITING SHOP & BUYING ARTICLES AS MUCH THEY WANT*/import java.io.*;class Stationary_STORE{public static void main()throws IOException{int cd,ct=0,noa,cost=0,tcost=0; String ch23="",ch="",co="";DataInputStream br =new DataInputStream(System.in);do{ct++;System.out.println("WELCOME TO WILLIAM PENN STORE");System.out.println("Press (IN) to enter and (OUT) to leave");ch=br.readLine();cost=0;if(ch.equalsIgnoreCase("IN") ){do

Page 64: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{System.out.println("Store provides you all your need");System.out.println("PRESS the code of the article you want to buy::");System.out.println("1-Parker Pen-Rs.150");System.out.println("2-Cello Pen-Rs 25");System.out.println("3-Folder-Rs 175");System.out.println("4-Note Book-rs-Rs 120");cd=Integer.parseInt(br.readLine());System.out.println("How Many you want to buy ?");noa=Integer.parseInt(br.readLine());if(cd==1)cost+=150*noa;if(cd==2)cost+=25*noa;if(cd==3)cost+=175*noa;if(cd==4)cost+=120*noa;System.out.println("Do you want to buy anything else Y or N ?");co=br.readLine();}while(co.equalsIgnoreCase("Y"));System.out.println("Total Amount::"+cost);System.out.println("Do u want to close the shop Y or N ?");ch23=br.readLine();tcost=tcost+ cost;}}while(ch23.equalsIgnoreCase("N"));System.out.println("SALE of the shop::"+ tcost);System.out.println("Total number of customer visits::"+ct);}}

/*CUSTOMER VISITING SHOP & BUYING TOYS AS MUCH THEY WANT*/import java.io.*;class TOY_STORE{public static void main()throws IOException{int cd,ct=0,cost=0,cost2=0,cost3=0,cost4=0,noa,tcost=0;double sale=0.0; String ch23="",ch="",co="";DataInputStream br =new DataInputStream(System.in);System.out.println("-------STOCK AVAILABLE------");System.out.println("ENTER the no. of DOLLS");int dolls=Integer.parseInt(br.readLine());System.out.println("ENTER the no. of CARS");int cars=Integer.parseInt(br.readLine());System.out.println("ENTER the no. of Bikes");int bikes=Integer.parseInt(br.readLine());System.out.println("ENTER the no. of Robot");int robot=Integer.parseInt(br.readLine());int total=dolls+robot+cars+bikes;

Page 65: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

do{ct++;System.out.println("WELCOME TO [International TOY STORE]");System.out.println("Press (IN) to enter and (OUT) to leave");ch=br.readLine();cost=0;if(ch.equalsIgnoreCase("IN") ){do{System.out.println("Store provides you all your need");System.out.println("PRESS the code of the article you want to buy::");System.out.println("1-Dolls");System.out.println("2-Cars");System.out.println("3-Bikes");System.out.println("4-Robots");cd=Integer.parseInt(br.readLine());System.out.println("How Many you want to buy ?");noa=Integer.parseInt(br.readLine());if(cd==1)cost+=noa;if(cd==2)cost+=noa;if(cd==3)cost+=noa;if(cd==4)cost+=noa;System.out.println("Do you want to buy anything else Y or N ?");co=br.readLine();tcost=tcost+ cost;}while(co.equalsIgnoreCase("Y"));System.out.println("Do u want to close the shop Y or N ?");ch23=br.readLine();}}while(ch23.equalsIgnoreCase("N"));sale=100*tcost/total;System.out.println("SALE of the shop::"+ sale);System.out.println("Total number of customer visits::"+ct);}}

/*India is great (aidni si taerg)*/import java.io.*;class wreverse{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);System.out.println("Enter a string ");String str=in.readLine();str=str+" ";String rstr="";

Page 66: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

int c=0;for(int i=0;i<str.length();i++){if(str.charAt(i)==' '){for(int j=i-1;j>=c;j--)rstr+=str.charAt(j);c=i+1;rstr+=" ";}}System.out.println(rstr);}}

/*word frequence*/import java.io.*;class wfrequence{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter a multiword string ");String str=br.readLine();System.out.println("Enter the word whose frequence is to count ");String word=br.readLine();str=" "+str;int j=0,c=0;for(int i=0;i<str.length();i++){if(str.charAt(i)==' '){if(str.substring(j,i).equals(word))c++;j=i+1;}}System.out.println("Frequence of word "+word.toUpperCase()+" is "+c);}}

/********Two D array of string********/import java.io.*;class twodstring{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);String name[]=new String[5];int i;System.out.println("Enter names ");for(i=0;i<5;i++)name[i]=in.readLine();

Page 67: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println("names are ");for(i=0;i<5;i++)System.out.println(name[i]);}}

/***************name sort*************/import java.io.*;class namesort{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);String name[]=new String[5];System.out.println("Enter five string ");int i,j;for(i=0;i<5;i++)name[i]=in.readLine();

for(i=0;i<4;i++){for(j=i+1;j<5;j++){if(name[i].compareTo(name[j])>0){String temp=name[i];name[i]=name[j];name[j]=temp;}}}

System.out.println("Sorted Names are.........");for(i=0;i<5;i++)System.out.println(name[i]);}}

Important questions1. Input 20 elements in an integer array find and print the frequency of each of the digits in all the

elements.2. Input price and quantity of 20 items purchase and then find the total amount to be paid.3. Input the coefficient of a quadratic equation and print whether the roots are imaginary, real and

distinct or real and equal4. Program for binary search in an integer array, string array.5. Define a class number with n1 and n2 as two integer variables and member methods to be input(), int

add(), int sub(), int div(), and long mul().6. Program to input 10 elements in an integer array and shift all even elements to the left and odd to the

right.7. Input two number and a character (mathematic operator +,-,*, /) and find a print the result depending

on the operator entered.8. Program to input elements to an integer array and find and print minimum, maximum, second

minimum and second maximum element of the array.9. Menu driven program using function and class for area of various shapes.

Page 68: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

10. Program to input a sentence and print it in reverse so that the words are printed in reverse order, but the words are not reversed.

11. Program for finding the LCM and HCF of two input numbers.12. Program to input a name and print the initials with last full name with all first alphabets in capital

and others in small.13. Program to input a date, month and year and print whether it is valid or not.14. Program to input the number of days the book in returned late to the library and print the fine to be

paid. Days fine / day (Rs)First 5 days 0.8/dayNext 5 days 1.2/dayNext 10 days 1.7/dayRemaining days 2.4/day

15. Program for printing 10 lines of Pascal triangle using 1-d array.16. Program to show constructor overloading.17. Program to input a number and find sum of the digit, armstrong, autmorphic, prime or not.18. A drilling machine can drill 20 feet in an hour, each hour it efficiency decreases by 8%. Program to

input the number of hour and find the depth drilled by the machine.19. Program to input a sentence and print each word separately along with the sum of the ASCII value of

the word.20. Program to input a sentence, a word to be searched in the sentence and another word which should

replace all the occurrence of the searched word.21. Program to input a number n and print all twin prime numbers from 2 to n.22. Program to input a number and print its binary equivalent number.23. Program to show call/pass by reference function.

Scanner Class/********scanner class demo************/import java.util.Scanner;class scanner1{public static void main(String args[]){Scanner inp=new Scanner(System.in);int a;double d;String word;String line;System.out.println("Enter int, double, a line ");a=inp.nextInt();d=inp.nextDouble();word=inp.next();line=inp.nextLine();System.out.println("The output of the input data is shown as : ");System.out.println(a);System.out.println(d);System.out.println(word);System.out.println(line);

Page 69: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}}

/**************print integer and words***********/import java.util.Scanner;class scanner2{public static void main(String args[]){String inp="1 january 23 january subhash january republic";Scanner s=new Scanner(inp).useDelimiter("January");System.out.println("The tokens of the string are ");System.out.println(s.nextInt());System.out.println(s.nextInt());System.out.println(s.next());System.out.println(s.next());}}

/**************will show Integer, float, string separately**************/import java.util.Scanner;class conversion{public static void main(String args[]){int n;float f;double d;Scanner in=new Scanner(System.in);System.out.println("Enter your data ");

if(in.hasNextInt()){f=(float)in.nextInt();System.out.println("The data expressed in float as "+f);}else if(in.hasNextFloat()){n=(int)in.nextFloat();System.out.println("The data expressed in integer as "+n);}else if(in.hasNextDouble()){n=(int)in.nextDouble();System.out.println("The data expressed in integer as "+n);}elseSystem.out.println("Token not an integer or a real value ");}}

/*********use of printwriter class*******/import java.io.*;class printout

Page 70: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{public static void main(String args[]){PrintWriter prn=new PrintWriter(System.out,true);prn.println("Printed value are :");int a=5;prn.println(a);double d=3.110012;prn.println(d);String str="Arif";prn.println(str);}}

/***********will print each word separately************/import java.util.Scanner;class scandisplay{public static void main(String args[]){Scanner in=new Scanner(System.in);String st;System.out.println("Enter line ending with a space & terminated with (.) ");while(true){st=in.next();if(st.equals("."))break;System.out.println(st);}}}

/****************Word Frequency**************/import java.util.Scanner;class wordfrequency{public static void main(String args[]){Scanner in=new Scanner(System.in);int c=0;String st;System.out.println("Enter the line ending with space and terminated with (.) ");while(true){st=in.next();if(st.equals("the"))c=c+1;if(st.equals("."))break;}System.out.println("Frequency of tokens 'the' is = "+c);}}

Page 71: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

/***********Will print middle token (Ajay Kumar Sharma)***********/import java.util.Scanner;class mtoken{public static void main(String args[]){Scanner in=new Scanner(System.in);String st;System.out.println("Enter name ending with a space and terminated with (.) ");while(true){st=in.next();if(st.equals("Kumar"))continue;System.out.print(st+" ");if(st.equals("."))break;}}}

/***To compare two tokens*****/import java.util.Scanner;class compare{public static void main(String args[]){Scanner in=new Scanner(System.in);String st1,st2;System.out.println("Enter two different tokens ");st1=in.next();st2=in.next();if(st1.compareTo(st2)>0)System.out.println(st1+" is greater than "+st2);if(st2.compareTo(st1)>0)System.out.println(st2+" is greater than "+st1);if(st1.compareTo(st2)==0)System.out.println(st1+" is equal to "+st2);}}

/**RED BOTTLE IS IN RED BAG ON RED CARPET**********/import java.util.Scanner;class rtoken{public static void main(String args[]){Scanner in=new Scanner(System.in);String st;System.out.println("Enter line ending with a space and terminated with (.) ");while(true){

Page 72: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

st=in.next();if(st.equals("RED")){st="GREEN";System.out.print(st+" ");continue;}System.out.print(st+" ");if(st.equals("."))break;}}}

/*************will print pattern*********/import java.util.Scanner;class patern{public static void main(String args[]){Scanner in=new Scanner(System.in);int i,j,p,k;char ch;String st;System.out.println("Enter a word as token for pattern printing ");st=in.next();p=st.length();System.out.println("Enter your choice ");k=in.nextInt();switch(k){case 1: System.out.println("The pattern : "); for(i=0;i<p;i++) { for(j=0;j<=i;j++) { ch=st.charAt(j); System.out.print(ch); } System.out.println(); } break;case 2: System.out.println("The Pattern : "); for(i=p;i>=1;i--) { for(j=0;j<i;j++) { ch=st.charAt(j); System.out.print(ch); } System.out.println(); } break;

Page 73: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

default: System.out.println("Wrong choice ");}}}/********Sum of numbers entered by user*******/import java.util.Scanner;class sumtoken{public static void main(String args[]){Scanner in=new Scanner(System.in);System.out.println("Enter any 10 numbers ");int i,n,s=0;for(i=1;i<=10;i++){n=in.nextInt();s=s+n;}System.out.println("The sum of numbers = "+s);}}

/*********greatest common divisor********/import java.util.Scanner;class GCD{public static void main(String args[]){Scanner in=new Scanner(System.in);int n,n1,n2,t=0;System.out.println("Enter two different numbers ");n1=in.nextInt();n2=in.nextInt();while(n1%n2!=0){t=n1%n2;n1=n2;n2=t;}System.out.println("GCD of two numbers "+n2);}}

/*****Sum of even odd numbers**********/import java.util.Scanner;class sumchoice{public static void main(String args[]){Scanner in=new Scanner(System.in);System.out.println("Enter integer to continue & an alphabet to terminate ");int n,s1=0,s2=0;

Page 74: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

while(in.hasNextInt()){n=in.nextInt();if(n%2==0)s1=s1+n;elses2=s2+n;}System.out.println("The program terminates ");System.out.println("The sum of even numbers "+s1);System.out.println("The of odd numbers "+s2);}}

/********vowal token print***/import java.util.Scanner;class VToken{public static void main(String args[]){Scanner in=new Scanner(System.in);int i,p;char ch1,ch2;String st[]=new String[10];System.out.println("Enter 10 words in lower case ");for(i=0;i<10;i++){st[i]=in.next();}System.out.println("The tokens which begin & end with a vowal are ");for(i=0;i<10;i++){p=st[i].length();ch1=st[i].charAt(0);ch2=st[i].charAt(p-1);if((ch1=='a' || ch1=='e' || ch1=='i' ||ch1=='o' || ch1=='u') && (ch2=='a' || ch2=='e' || ch2=='i' ||ch2=='o' || ch2=='u'))System.out.println(st[i]);}}}

/**********Will print number tokens**********/import java.util.Scanner;class numtoken{public static void main(String args[]){Scanner in=new Scanner(System.in);System.out.println("Enter line ending with a space & terminated with (.) ");while(true){if(in.hasNextInt())System.out.print(in.nextInt()+" ");if(in.next().equals(","))

Page 75: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

break;}}}

Conversion of numbers into one another

/*********Conversion from Decimal To binary******************/import java.io.*;class dec_2_binary{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int num;System.out.println("Enter a number ");num=Integer.parseInt(br.readLine());int digit[]=new int[50];int i=0,j=0;while(num>0){digit[i++]=num%2;num=num/2;}for(int k=i-1;k>=0;k--)System.out.print(digit[k]);}}

/**********Decimal to octal*********/import java.io.*;class dec_2_octal{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int num;System.out.println("Enter a number ");num=Integer.parseInt(br.readLine());int digit[]=new int[50];int i=0,j=0;while(num>0){digit[i++]=num%8;num=num/8;}System.out.print("0");for(int k=i-1;k>=0;k--)System.out.print(digit[k]);

Page 76: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}}

/********conversion from decimal to hexadecimal**************/import java.io.*;class hexadecimal{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int num;System.out.println("Enter a number ");num=Integer.parseInt(br.readLine());int c=0,a[]=new int[20];while(num>0){a[c++]=num%16;num=num/16;}System.out.println("Haxadecimal number is ");System.out.print("0X");for(int i=c-1;i>=0;i--){if(a[i]==10)System.out.print("A");else if(a[i]==11)System.out.print("B");else if(a[i]==12)System.out.print("C");else if(a[i]==13)System.out.print("D");else if(a[i]==14)System.out.print("E");else if(a[i]==15)System.out.print("F");elseSystem.out.print(a[i]);}}}

/**********Binary to Decimal*********/import java.io.*;class binary_2_deci{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int num;System.out.println("Enter a number ");num=Integer.parseInt(br.readLine());int digit[]=new int[50];int i=0,j=0;while(num>0)

Page 77: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{digit[i++]=num%10;num=num/10;}double sum=0.0;int x=0;for(int k=0;k<i;k++){double q=Math.pow(2,x);sum=sum+digit[k]*q;x++;}System.out.print("The Decimal value of binary number is "+sum);}}

/**********Ocatal to Decimal*********/import java.io.*;class octal_2_deci{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int num;System.out.println("Enter a number ");num=Integer.parseInt(br.readLine());int digit[]=new int[50];int i=0,j=0;while(num>0){digit[i++]=num%10;num=num/10;}double sum=0.0;int x=0;for(int k=0;k<i;k++){double q=Math.pow(8,x);sum=sum+digit[k]*q;x++;}System.out.print("The Decimal value of octal number is "+sum);}}

/************Hexadecimal to decimal*****************/import java.io.*;class hexa_2_deci{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int num;System.out.println("Enter a number ");

Page 78: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

num=Integer.parseInt(br.readLine());int c=0,temp=num,a[]=new int[20];while(temp>0){a[c++]=temp%10;temp=temp/10;}System.out.println("decimal number is ");/*for(int i=c-1;i>=0;i--){if(a[i]==10)System.out.print("A");else if(a[i]==11)System.out.print("B");else if(a[i]==12)System.out.print("C");else if(a[i]==13)System.out.print("D");else if(a[i]==14)System.out.print("E");else if(a[i]==15)System.out.print("F");elseSystem.out.print(a[i]);} */

int x=0;double sum=0.0;for(int i=0;i<c;i++){double q = Math.pow(16,x);sum=sum+a[i]*q;x++;}System.out.println("\n The decimal number = "+sum);}}

FunctionsMethods are known as functions in C and C++. A method (function) is set of instruction that perform a specific task. Method (Functions) can accept a set of values as arguments from the calling program and process them and pass the results back after execution of the method. When a program passes control to a method, the method does the task and returns control to the calling instruction of the program. Parts of function:

1. Function Prototype: this part contains return type, name and type of arguments of function. Prototype tells the program about the type of the value return by the function and the number and type of arguments.

Signature: a function signature basically refers to the number and types of arguments. It is a part of the function prototype. Function signature and return type make a function’s prototype. But sometime the term function signature is used to refer to a function prototype.Example:/************function signature and prototype********/

Page 79: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

void display(int a, int b) { System.out.println("value of a "+a); System.out.println("value of b "+b); }In this example (int a, int b) is the signature of function while void display (int a, int b) is the prototype of function.

Calling of function: this part contain name and values that we are passing as an argument to the function.

Example: sum(10,20);Function Definition: this part contain return type, name and arguments types and their values , beside this , this part also contain body block in which we can perform on the values that we getting as argument. This part is similar to parameter.

Example: int sum(int x, int y){ Body of function; }

Types of functions: 1. Library function 2. User define functionLibrary Functions: These are known as built in function which already remains in the library of the

language. There is no need to take prototype or declare definition for these functions because their prototype is present in the header file of C and C++ or in the Classes of Java, and definition in the library of language so we directly call them in our program and used the value return by them. /**************Mathematical Functions************/class mathfunction{public static void main(String args[]){System.out.println(Math.sqrt(144)); //will return square root of a numberSystem.out.println(Math.pow(2,8)); //will return power a number first number is base and second is

powerSystem.out.println(Math.min(2,4));// will return minimum number out of twoSystem.out.println(Math.max(2,4));// will return maximum number out of twoSystem.out.println(Math.abs(-25));//will return absolute value and minus sign will change by positive

//will return rounded value up to nearest integerSystem.out.println(Math.round(2.56));System.out.println(Math.round(2.44));

System.out.println(Math.floor(2.58));//returns the rounded value down to the nearest integerSystem.out.println(Math.ceil(2.21));//returns the whole number greater than or equal to the number

System.out.println(Math.rint(2.21));//returns the truncated value of the number, same as round functionSystem.out.println(Math.random());//return a random number between 0 and 1

}}

Users define Functions: these functions are defined by the user. So we are in need to declare prototype, to call them and need to give definition of them in our program to use them.

Example: #include<iostream.h>int sum(int, int ); //prototypevoid main(){int a,b;cout<<”\n enter value of a and b “;

Page 80: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

cin>>a>>b;int s=sum(10,20); //callcout<<”\n Sum is “<<s;int a=sum(a,b); //callcout<<”\n sum is “<<a;getch(); }int sum(int x, int y) //defination{ return x+y; }

Basic function programsQuestion: Write a function for swapping of two numbers without using third variable. (Without return type)Question: Enter temperature in degree Celsius and convert it into Fahrenheit. (With return type)Question: Find out the Area and Perimeter of a circle and Rectangle.

import java.io.*;class Areas{double radius, length, width;DataInputStream in=new DataInputStream(System.in);

void circle() throws IOException{System.out.println("Enter circle radius ");radius=Double.parseDouble(in.readLine());double area=3.14*radius*radius;double circumference=2*3.14*radius;System.out.println("Area of circle is "+area);System.out.println("Circumference of cicle is "+circumference);}void rect() throws IOException{System.out.println("Enter length and with of rectangle ");length=Double.parseDouble(in.readLine());width=Double.parseDouble(in.readLine());double area=length*width;double perimeter=2*(length+width);System.out.println("Area of rectangle is "+area);System.out.println("Perimeter of ractangle is "+perimeter);}

public static void main(String args[]) throws IOException{Areas obj=new Areas();obj.circle();System.out.println();obj.rect();}

}

Question: 1. Z=A2+B2-2AB 2. x=−b±√b2−4 ac2 a

Question: Enter the marks of five subjects of a student and calculate his total and average.Question: Enter the basic salary of an employee and give him 20% DA, 15%HRA and calculate his gross salary.Function with if-else

Page 81: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Question: Enter the Selling price and cost price of an item and find out whether sellar has made profit or loss and how much.Function with loopQuestion: Enter a number and reverse it.Function with arrayQuestion: Pass an array as an argument to a function and print it element.Function with two–D arrayQuestion: Pass a two-d array as an argument to a function and print it.Function with stringQuestion: Pass two srings as an argument and concatenate them.Question: Pass a string to a function as argument and check whether it is palindrome or not.Function with two-D array of stringQuestion: Enter a two-d array of string in a function as argument and sort them.User define functions are of two types.

1. Call by Value2. Call by Reference1. Call by Value: The call by value method copies the values of actual parameters into the formal

parameters, that the function creates its own copy of argument values and then uses them. Of if any change takes place to the formal parameter than it will not show any effect to the actual parameter, because function is working on copy of the original values. Thus in calls by value method changes are not reflected back to the original values.

Example:class swaping

{void swap(int x, int y) {int temp=x;

x=y;y=temp;System.out.println(“Value of x “+x);System.out.println(“Value of y “+y);

}

public static void main(String args[]) {int a,b;

a=10; b=20;swaping obj=new swaping();obj.swap(a,b);System.out.println(“Value of a after swaping “+a);System.out.println(“Value of b after swaping “+b); }}

2. Call by Reference: in call by reference method we pass a reference of the original variable to the function definition. When a function is called by reference then the formal parameters gets references of the actual parameters in the calling function. This means that in call by reference method, the called function does not create its own copy of original values, rather it refers to the original variable only by different names i.e. the references.

Example: in javaclass swapingr

{int x=10,y=20;void swap(swapingr obj)

{int temp=obj.x;obj.x=obj.y;obj.y=temp;System.out.println(“Value of x “+obj.x);

Page 82: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println(“Value of y “+obj.y); }

public static void main(String args[]) {swapingr obj=new swapingr();

obj.swap(obj);System.out.println(“Value of a after swaping “+obj.x);System.out.println(“Value of b after swaping “+obj.y); }}

Example: in c++/********call by reference *****/#include<iostream.h>#include<conio.h>void swaping(int &, int &);void main(){clrscr();int a,b;a=10;b=20;cout<<"\n value of a in main before swaping"<<a;cout<<"\n value of b in main before swaping "<<b;swaping(a,b);cout<<"\n value of a in main after swaping"<<a;cout<<"\n value of b in main after swaping "<<b;getch();}void swaping(int &a, int &b){int t=a;a=b;b=t;cout<<"\n value of a "<<a;cout<<"\n value of b "<<b;}

/******call by reference by pointer*******/#include<iostream.h>#include<conio.h>void swaping(int *, int *);void main(){clrscr();int a,b;a=10;b=20;cout<<"\n value of a in main before swaping"<<a;cout<<"\n value of b in main before swaping "<<b;swaping(&a,&b);cout<<"\n value of a in main after swaping"<<a;cout<<"\n value of b in main after swaping "<<b;getch();}void swaping(int *a, int *b){int t=*a;*a=*b;*b=t;cout<<"\n value of a "<<*a;cout<<"\n value of b "<<*b;}

Page 83: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

/*********call by reference in c#********/using System;namespace ConsoleApplication7{ class Program { static void Main(string[] args) { int a, b; a = 10; b = 20; Console.WriteLine("value of a in main befor swaping " + a); Console.WriteLine("value of b in main befor swaping " + b); byref(ref a, ref b); Console.WriteLine("value of a in main after swaping " + a); Console.WriteLine("value of b in main after swaping " + b); } static void byref(ref int a , ref int b) { int t = a; a = b; b = t; Console.WriteLine("value of a " + a); Console.WriteLine("value of b " + b); } }}

/*******return by reference*********/#include<iostream.h>#include<conio.h>int & returnbyref(int &, int &);void main(){clrscr();int a,b;a=10;b=20;int g=returnbyref(a,b);cout<<" greater number is "<<g;getch();}int & returnbyref(int &a, int &b){if(a>b)return a;elsereturn b;}

Actual and formal parameter: the parameters that appear in function call statement are called Actual Parameter. The parameters that pass to function definition as an argument are known as formal parameter. Example: /*************actual and formal parameter***/class abc{

Page 84: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

void display(int a, int b) //formal parameters { System.out.println("value of a "+a); System.out.println("value of b "+b); }

public static void main(String args[]) { int x=10,y=20; abc obj=new abc(); obj.display(x,y); //actual parameters }}

Return statement: The return statement is useful in two ways. First, an immediate exit from the function is caused as soon as a return statement is encountered and control pass back to the operating system which is main’s caller. Second use of return statement is that it is used to return a value to the calling code. A function can have several return statements. However only one of them gets executed because the execution of the function terminates as soon as return is encountered. The function declare as void do not return any value. On the basis of return statement function can be classified into three parts:1. Computational Function: The function that calculate or compute some value and return the

computed value. For example, Math.sqrt() and Math.pow() are computational functions.2. Manipulative functions: The function that manipulate information and return success or failure

code. Generally if value 0 is returned, it denotes successful operation; any other number denotes failure. Example -> System.exit(0)

3. Procedural Function: The function that perform an action and have no explicit return value. Example -> System.out.println() function is a procedural function.

Example: /*************program with multiple return statement***********/class returnstatement

{int a=10,b=5;int greater()

{if(a>b)return a;elsereturn b;

}public static void main(String args[])

{returnstatement obj=new returnstatement();System.out.println(obj.greater()); }}

Pure and Impure Functions: a pure function is the one that takes objects and primitives as arguments but does not modify the objects. The return value of a pure function is either a primitive or a new object created inside the method. On the other hand changes the state of receive object. Impure function is also called as modifier function because these change the state of argument received.

Example pure function:class Time

{int hour;Time()

{hour=0; }Time(int h)

{hour=h; }boolean compare(Time t1, Time t2)

Page 85: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{boolean result;result=t1.hour>t2.hour?true:false;return result; }

public static void main(String args[]) {Time obj1=new Time(10);

Time obj2=new Time(20);Time obj3=new Time();

System.out.println(“Object 1 hour are more then Object2 = “+obj3.compare(obj1, obj2)); }}

Example of Impure Function: (this function is changing the value of object one so it an impure function)

class Time2{int hour;

Time2() {hour=0; }

Time2(int h) {hour=h; }

void increment(Time2 t1, Time2 t2) {t1.hour=t1.hour+t2.hour;System.out.println(“The net hour “+t1.hour); }

public static void main(String args[]) {Time2 obj1=new Time2(10);Time2 obj2=new Time2(20);Time2 obj3=new Time2();obj3.increment(obj1, obj2); }}

Nesting of Function: A function can be called by using only its name by another method of same class. This is known as nesting of methods.

Example:class nestingmethods

{void india() {System.out.println(“I am in India”); }

void USA() {india();System.out.println(“I am in USA “); }

void Brazil() {USA();

System.out.println(“I am in Brazil”); }

public static void main(String args[]) {System.out.println(“I am in Main”);nestingmethods obj=new nestingmethods();obj.Brazil();System.out.println(“I am in back Main”); }}

Function overloading:Returning object:

Method can also return objects. To create such type of method we have to define the return type of method with the class name which type of object we want to return from a method.Example:

/********************programe to return an object*****/class Rectangle

{double distance;

Page 86: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Rectangle(double d) {

distance=d; }

Rectangle square(double s) {Rectangle r=new Rectangle(s);return r; //returning object }

public static void main(String args[]) {Rectangle rect1=new Rectangle(100);Rectangle rect2;rect2=rect1.square(10);System.out.println(rect2.distance); }}

Recursion:Recursion is the process in which a method calls itself. A recursive Method is a method that calls itself to perform a specific operation. Example://*************factorial in single line ******///class fact2{

int fact(int n) {

If(n==1)Return 1;

Elsereturn n*fact(n-1);

}

public static void main(String args[]){fact2 f=new fact2();System.out.println(f.fact(5));}}

/***********************Fibonacci series by Recursion********/import java.io.DataInputStream;class recursion{DataInputStream in=new DataInputStream(System.in);int a=0,b=0,c=0,limit=0;

recursion() { }void input()

{System.out.println(“enter the limit of series “);try

{limit=Integer.parseInt(in.readLine());

}

Page 87: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

catch(Exception e){} }

void fib(int x) {

for(int i=0;i<=limit;i++) {

if(i==0 ) {

System.out.print(0); }

else if(i==1 || i==2) {

System.out.print(1); }

else {

System.out.println(fib(i-2)+fib(i-1)); } } } }class fibnoci{public static void main(String args[]){recursion f=new recursion();f.input();f.fib(f.limit); } }

example: /*print 20 number in reverse order by recursive function*/class reverseseries{

void reverse(int limit) {

if(limit==1)System.out.println(limit);else

{System.out.println(limit);reverse(limit-1);

} }public static void main(String args[])

{reverseseries r=new reverseseries();r.reverse(10); }}

Example: /*********find power of a number by recursive method***/import java.io.*;class power_calc{

long fun(long base, long power) {

if(power==0)return 1;else if(power==1)return base;else

Page 88: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

return (base*fun(base,power-1)); }

public static void main(String args[]) throws IOException {power_calc obj=new power_calc();DataInputStream in=new DataInputStream(System.in);long base,power;System.out.println(“Enter base and power “);base=Long.parseLong(in.readLine());power=Long.parseLong(in.readLine());long lg=obj.fun(base,power);System.out.println(“The power is “+lg); }}Example://*********reverse string and check is palendrom or not ******//

import java.io.DataInputStream;class reversestring{String str=””;String revstr=””;

void getstring() {try {DataInputStream in=new DataInputStream(System.in);System.out.println(“Enter a string “);str=in.readLine();}catch(Exception e){} }

void recreverse(int i) {if(i==0)return ;else {revstr=revstr+str.charAt(i-1);recreverse(i-1); } }

void check() { System.out.println(“orignal String is = “+str);System.out.println(“reverse String is =”+revstr);if(str.equals(revstr))

System.out.println(“String “+str+” is a palindrom “);elseSystem.out.println(“String “+str+” is not a palindrom “); }public static void main(String args[])

{reversestring s=new reversestring();s.getstring();int l=s.str.length();s.recreverse(l);s.check(); }}

Example:/**multiplication of two number by recursive function***/import java.io.*;class number2{

int recadd(int p, int q){if(q==0)return 0;else if(q==1)return (p);elsereturn (p+recadd(p,q-1));

Page 89: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}

public static void main(String args[]) throws IOException {int m,n,res=0;number2 n1=new number2();BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println(“enter multiplicand “);m=Integer.parseInt(br.readLine());System.out.println(“enter multiplier “);n=Integer.parseInt(br.readLine());res=n1.recadd(m,n);System.out.println(“the product of multiplication is “+res);}}

constant arguments???Method with array and two D-ArrayWhen we pass array or two D-array to a function, we generally pass name of array as argument in function call./*****************function with array **********/class funwitharray{ void showarray(int list[]) { int i; System.out.println("Array elements are "); for(i=0;i<list.length;i++) System.out.println(list[i]); }

public static void main(String args[]) { int list1[]={1,2,3,4,5}; funwitharray obj=new funwitharray(); obj.showarray(list1); }}

Example: /*************function with array*********/import java.io.*;class funwitharray{DataInputStream in=new DataInputStream(System.in);

void fun(int list[]) throws IOException

Page 90: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{list=new int[10];System.out.println(“Enter an element “);int i;for(i=0;i<list.length;i++)list[i]=Integer.parseInt(in.readLine());System.out.println(“=====array===”);for(i=0;i<list.length;i++)System.out.println(list[i]); }

public static void main(String args[]) throws IOException {int list[]=new int[10];funwitharray obj=new funwitharray();obj.fun(list); }}

/***********Function with two D array********/class funwith_2_D_array{ void showarray(int list[][]) { int i,j; System.out.println("Array elements are "); for(i=0;i<3;i++) { for(j=0;j<3;j++) System.out.print(list[i][j]); System.out.println(); } }

public static void main(String args[]) { int list[][]={{1,2,3},{4,5,6},{7,8,9}}; funwith_2_D_array obj=new funwith_2_D_array(); obj.showarray(list); }}

Methods with Varargs: Varargs is the feature introduce by J2SE5.0. actually varargs is a type of argument, ellipsis(…) is the key to varargs and variable after ellipsis is the name of argument. Before the ellipsis we have to define the data type of object. Thus varargs allow us to declare a method with the unspecified number of parameters for a given argument. The varargs must be the final argument in the argument list of a method. Varargs is identified by the type of argument followed by ellipsis and the name of the variable. Varargs never returns any compile time error even if an empty argument is passed as a parameter a method.

Example:/************Method with Varargs with string*******/class varargs

{varargs(String...person) //elipses can not exceed three

{for(String name : person) //for each loopSystem.out.println(“Hello “+name); }

public static void main(String args[]) {

Page 91: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

varargs obj=new varargs(“john”,”roshan”,”suhel”,”amjad”,”Tahir”); }}

Example:/************Method with Varargs with number*******/class varargs1

{varargs1(int...num) //elipses can not exceed three

{for(int j : num) //for each loopSystem.out.println(j); }

public static void main(String args[]) {int list[]={10,20,30,40,50};varargs1 obj=new varargs1(list); }}

Example:/************Method with Varargs with two constructor*******/class varargs2

{varargs2(int...num) //elipses can not exceed three

{for(int j : num) //for each loopSystem.out.println(j); }

varargs2(String...name) {for(String s : name)System.out.println(s); }

public static void main(String args[]) {int list[]={10,20,30,40,50};String names[]={”arif”,”asif”,”kashif”};varargs2 obj1=new varargs2(list);varargs2 obj2=new varargs2(names); }}

Example : /********varargs as final argument***********/class varargs3

{

varargs3(int a, int b,String...name) {for(String s : name)System.out.println(s);System.out.println(“value of a “+a);System.out.println(“value of b “+b); }

public static void main(String args[]) {

Page 92: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

String names[]={”arif”,”asif”,”kashif”};varargs3 obj=new varargs3(10,20,names); }}

Example:/************varargs with function*******/class varargs4{void display(int a, int b,String...name) //varargs with function

{for(String s : name)System.out.println(s);System.out.println(“value of a “+a);System.out.println(“value of b “+b); }

public static void main(String args[]) {String names[]={”arif”,”asif”,”kashif”};varargs4 obj=new varargs4();obj.display(10,20,names); }}

Q. WAP to enter name, rollno, class, section, address, date of birth, father name of a student by varargs and print it.1. Method with simple statement (swaping, sum, precedence of operator)2. Method with decision making statement (if else)3. Method with selection statement (switch)4. Method with loop (revers a number, special, perfect, sunny , palindrome num and string, magic,

shapes, frequency)5. Method with array and two D-Array (separate even odd, found a specific number or character, find

max, min of list, sorting, searching’s etc.)6. Method with string (reverse, initial , shapes, capital to small, counting words, spaces, specific

character, vovals etc)7. Method with structure8. Method with method (overloading, nested of method, etc)

Page 93: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

ClassClass Definition: A class represents a set of objects that share common characteristic and behavior. A class is users define data type which holds both the data and methods. The variable (attribute) of a class is called data member or instance variable and the methods are called member methods. Once you have defined data type class, you can use this data type to create objects of that data type. Class Declaration -> the key word class is used to declare a class.Syntax :

class <class name>{

Data type variable 1Data type variable 2

Return type method1(parameter list){

Method body}}

Example:class sum{int a,b,c; //variable declaration

void getdata(int x, int y) //method declaration {

a=x;b=y;

}int sum() //method declaration

{c=a+b;return c;

}}

Object: An object is a programming structure that groups related methods and the data those methos use. Object is an instance of a class or Object is an entity that can store data and send and receive messages. The class of an object defines the data type and the structure or shape that an object can have.Object creation: Object in java is created using new operator. The new operator creates an object of the specified class and returns a reference to that object. Example:

sum obj=new sum();or

sum obj;obj=new sum();

Page 94: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

sum->name of the classobj->name of the objectnew ->operator to assign memory dynamically.Sum()->is the constructor of class sum .

What is an attribute?The variables which are declared in a class are called attributes.

What is a member?A member can be either data, known as data member or a function known as a member function. An attribute can also be called as data member.

Example of class:class sum{int a,b;int c;

void getdata(int x, int y) {

a=x;b=y;

}

int sum() {

c=a+b;return c;

}

public static void main(String args[]) {

sum obj=new sum();obj.getdata(10,20);int sum=obj.sum();System.out.println(“Sum is “+sum);

}}

Need for class: A class represents a set of objects that share common characteristic and behavior. Class also called as object factory because it contain all the statements needed to create an object, its attributes, as well as the statements to describe the operations that the object will be able to perform. Constructor : a member function with the same name as its class is called constructor and it is used to initialize the objects of that class type with a legal initial value. Constructor contain following features:

1. its name is same as class name2. its never returns a value3. its never preceded by any return type like float, int, byte ,short , char etc even void also.4. it may be with or without arguments.5. it automatically invoke when its class object is created.

Need for constructor: constructor main need is to create an instance of a class. This can be called creating an object, while the purpose of other method is generally to execute java code. In c++ constructor mainly need to initialized class variable because we can’t initialize class variable at the time of declaration.Declaration of constructor:class const_demo{

Page 95: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

int a,b,c;const_demo(int x, int y) //constructor declaration

{a=x;b=y;

}

void display() {

System.out.println(“value of a “+a);System.out.println(“value of b “+b);

}

public static void main(String args[]) {

const_demo obj=new const_demo(10,20); //invoking constructorobj.display();

}}

Types of constructor: Constructor is of two types: one those which receive parameters are known as parameterized constructor and the other which do not receive parameter are known as default constructor.

Example:/***********parameterized and default constructor******/class constructors{int a,b;

constructors() //default constructor {

a=0;b=0;

}constructors(int x, int y) //parameterized constructor

{a=x;b=y;

}void display()

{System.out.println(“value of a “+a);System.out.println(“value of b “+b);

}public static void main(String args[])

{ constructors obj1=new constructors(); //calling default constructor constructors obj2=new constructors(10,20); //calling parameterized constructor

obj1.display();obj2.display();

}}

Constructor overloading: declaration of multiple constructors with different number of argument in called constructor overloading.

Page 96: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Example:class interest{double amount,rate,time;

interest(double a, double r, double t) {

amount=a;rate=r;time=t;

}interest(double amt, double rt)

{amount=amt;rate=rt;time=5;

}interest(double am)

{amount=am;rate=2.5;time=3;

}void display()

{System.out.println(“Principal Amount “+amount);System.out.println(“Rate of Interest “+rate);System.out.println(“Time of Loan “+time); }

double calculate() {

double inst;inst=(amount*rate*time)/100;return inst;

}public static void main(String args[])

{interest s1=new interest(10000,4.25,10);interest s2=new interest(15000,2.50);interest s3=new interest(5000);System.out.println(“\n Firs call ====================”);s1.display();System.out.println(“Interest is =========>”+s1.calculate());System.out.println(“\n Second call ====================”);s2.display();System.out.println(“Interest is =========>”+s2.calculate());System.out.println(“\n Third call ====================”);s3.display();System.out.println(“Interest is=========> “+s3.calculate());

}}

Q. Calculate the area of Rectangle, Triangle, Circle with the help of constructor overloading.Q. Add two distance type object using constructor overloading. Ans: class distance

Page 97: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{int metter,centimetter;

distance() {

metter=0;centimetter=0;

}distance(int x, int y)

{ metter=x; centimetter=y;

}void show()

{System.out.println(metter+”\t\t\t”+centimetter);

}void calculate(distance d1, distance d2)

{metter=d1.metter+d2.metter;centimetter=d1.centimetter+d2.centimetter;while(centimetter>=100)

{centimetter-=100;++metter;

} }

public static void main(String args[]) {distance d1=new distance(5,70);

distance d2=new distance(8,50);distance d3=new distance();System.out.println(“Metter\t\t\tCentimetter\t\t”);d1.show();d2.show();d3.calculate(d1,d2);System.out.println(“----------------------------------“);d3.show();System.out.println(“----------------------------------“); }}

Q. Input two different times and add them by constructor overloading.Q. Input a distance into meter and centimeter and another distance into feet and inches and add them into any scale. (Meter, Centimeter, Inches).Nesting of Constructor: when we call a constructor in itself , then it is called nested constructor it is done by the help of this key word.Example:class abc{int a,b,c;

abc() {

a=0;b=0;c=0;

}abc(int x, int y, int z)

{a=x;

Page 98: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

b=y;c=z;

}abc(int x, int y) //nesting of constructor

{ this(x,y,x); //this will invoke the constructor- //or // //-that will takes three arguement

//this(x,y,33); }

void show() {

System.out.println(“Value of a “+a);System.out.println(“Value of b “+b);System.out.println(“Value of c “+c);

}public static void main(String args[])

{abc a1=new abc();abc a2=new abc(2,4,6);abc a3=new abc(11,22);a1.show();a2.show();a3.show(); }}

Temporary instance or object: Temporary object mean, an object without name. temporary object is short-lived. It is beneficial when an object is required for a very short time.this type of object remain in the memory as long as the statement defining it is getting executed, after the statement object is automatically destroyed and memory is released. This type of object is created for explicit call to the constructor. Example:class xyz{int x,y;

xyz(int x, int y) {

this.x=x;this.y=y;

}void show()

{System.out.println(x+”\t\t\t”+y);

}public static void main(String args[])

{New xyz(10,20).show(); }}

Page 99: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

This Keyword: this keyword mainly used for self referencing. this keyword can be used inside any method to refer to the current object. Another use of this keyword is in using redundant (duplicate) variable names. Example:/*******************use of this operator*******/class useofthis{int a,b; useofthis() { }

useofthis(int a, int b) { this.a=a; this.b=b; }

useofthis add(useofthis s1, useofthis s2) { useofthis s=new useofthis(); this.a=s1.a+s2.a; this.b=s1.b+s2.b; return this; //return self object }

public static void main(String args[]) { useofthis s1=new useofthis(10,20); useofthis s2=new useofthis(50,100); useofthis s3=new useofthis(); useofthis s4=new useofthis(); s4=s3.add(s1,s2); System.out.println(s4.a); System.out.println(s4.b); }}

copy constructor : a copy constructor takes a reference to an object of the same class as itself as an argument, or when we assign an object of a class to the another object of the same class then it is known as copy constructor.Example: /***********copy constructor*********/

class copy{int a,b;

copy() { }

Page 100: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

copy(int x, int y) { a=x; b=y; }

void show() { System.out.println("value of a "+a); System.out.println("value of b "+b); }

public static void main(String args[]) { copy c1=new copy(10,20); copy c2=new copy(50,100); copy c3=new copy(); c3=c1; c3.show(); c3=c2; c3.show(); }}

/*Time additon and substraction*/import java.io.*;class Time{int hr,min,sec,t1,t2;public void accept()throws IOException{DataInputStream br =new DataInputStream(System.in);System.out.println("ENTER THE TIME IN [hour:min:sec] FORMAT>>");hr=Integer.parseInt(br.readLine());System.out.print(":");min=Integer.parseInt(br.readLine());System.out.print(":");sec=Integer.parseInt(br.readLine());System.out.print(":");System.out.println("...........................................................................");}public void display(){System.out.println("\t \t \t TIME==>HOUR:MINUTES:SECONDS");System.out.println("\t \t \t \t "+hr+":"+min+":"+sec);}public void compute1(Time t1, Time t2){int t11=t1.hr*3600+t1.min*60+t1.sec;int t22=t2.hr*3600+t2.min*60+t2.sec;int it=(t22>t11)?t22-t11:t11-t22;int h=it/3600;int m=(it%3600)/60;

Page 101: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

int s=(it%3600)%60;System.out.println("INTERVAL==>"+h+":"+m+":"+s);}public void compute2(Time t1, Time t2){int t11=t1.hr*3600+t1.min*60+t1.sec;int t22=t2.hr*3600+t2.min*60+t2.sec;int it=t11+t22;int h=it/3600;h=h>24?0:h;int m=(it%3600)/60;int s=(it%3600)%60;System.out.println("SUM==>"+h+":"+m+":"+s);}public static void main()throws IOException{Time obj=new Time();Time obj1=new Time();Time obj2=new Time();obj1.accept();obj1.display();obj2.accept();obj.compute1(obj1,obj2);obj.compute2(obj1,obj2);}}

InheritanceThe mechanism of deriving a new class from an old one is called inheritance. The old class is known as the basic or super class or parent class and the new one is called the subclass or derived class or child class. Inheritance is the concept of reusability. The inheritance allows sub class to inherit all the variables and method of its parent class. Inheritance are of five types.

1. Single inheritance2. Multi level inheritance3. Multiple inheritance4. Hierarchical inheritance5. Hybrid inheritance

Use of inheritance: 1. Reusability of tested codes and software 2. Code sharing3. Consistency in using an interface4. It also save time of programmer.

Single inheritance: when there is only one master class and one child class in an inheritance, it is known as single inheritance.Example:/*********single (public inheritance)*******/import java.io.*;class student{DataInputStream in=new DataInputStream(System.in); //by default is publicString name;

Page 102: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

int rollno;

protected void getdata() throws IOException //by default is public { System.out.println("Enter name and rollno "); name=in.readLine(); rollno=Integer.parseInt(in.readLine()); }

protected void showdata() //by default is public { System.out.println("Name "+ name); System.out.println("Rollno "+ rollno); }}class study extends student //default inheritance is public{int phy,che,math;

void getstudy() throws IOException { System.out.println("Enter marks of three subject "); phy=Integer.parseInt(in.readLine()); che=Integer.parseInt(in.readLine()); math=Integer.parseInt(in.readLine()); }

void showstudy() { System.out.println("Physics "+phy); System.out.println("chemistry "+che); System.out.println("math "+math); }}class single{public static void main(String args[]) throws IOException{study obj=new study();obj.getdata();obj.getstudy();obj.showdata();obj.showstudy();}}

Multilevel inheritance: when a class A serves as a base class for the derived class B which in turn serves as a base class for the derived class C, then it is called as multilevel inheritance and the chain ABC is known as inheritance path.

Page 103: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Example: /**********multilevel inheritance**/import java.io.*;class student {DataInputStream in=new DataInputStream(System.in);

String name;int roll;

void getstudent() {

try {

System.out.println(“enter the name of the student “);name=in.readLine();System.out.println(“enter the roll no of the student “);roll=Integer.parseInt(in.readLine());

}catch(Exception e){}

}

void showstudent() {

System.out.println(“Name = “+name);System.out.println(“Roll no= “+roll);

}}

class study extends student{int phy,che,math;

void getstudy() throws IOException {

getstudent();System.out.println(“enter the marks of physics “);phy=Integer.parseInt(in.readLine());System.out.println(“enter the marks of chemistry “);che=Integer.parseInt(in.readLine());System.out.println(“enter the marks of math “);math=Integer.parseInt(in.readLine());

}void showstudy()

{showstudent();System.out.println(“ the marks of physics “+phy);System.out.println(“ the marks of chemistry “+che);System.out.println(“ the marks of math “+math);

}}class sports extends study{String team;int ranck;

void getsports() throws IOException {

getstudy();

Page 104: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println(“Enter name of team “);team=in.readLine();System.out.println(“Enter Ranck of team “);ranck=Integer.parseInt(in.readLine());

}

void showsports() {

showstudy();System.out.println(“Team = “+team);System.out.println(“Ranck = “+ranck);

}}class multilevel_inheritance{public static void main(String args[]) throws IOException{sports s=new sports();s.getsports();s.showsports();}}

Multiple inheritance: when a child class inherits two or more master classes than it is known as multiple inheritance i.e a child class having more one parent class is called multiple inheritance. Having two parents class for a single class is possible in c++ but java doesn’t allow it . so java provides Interface which is similar to a class but not actually a class. In java a class can’t contain more than one parent class but a class can have one class and one interface.Example: /********************Multiple inheritance****/import java.io.*;interface sports {public String team=”India”;public int ranck=1;

public void showsports();}

class study {DataInputStream in=new DataInputStream(System.in);int phy,che,math;

void getstudy() throws IOException {

System.out.println(“enter the marks of physics “);phy=Integer.parseInt(in.readLine());System.out.println(“enter the marks of chemistry “);che=Integer.parseInt(in.readLine());System.out.println(“enter the marks of math “);math=Integer.parseInt(in.readLine());

}void showstudy()

{System.out.println(“ the marks of physics “+phy);System.out.println(“ the marks of chemistry “+che);System.out.println(“ the marks of math “+math);

}

Page 105: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}

class student extends study implements sports {

String name;int roll;

void getstudent() {

try {

System.out.println(“enter the name of the student “);name=in.readLine();System.out.println(“enter the roll no of the student “);roll=Integer.parseInt(in.readLine());getstudy();

}catch(Exception e){}

}

void showstudent() {

System.out.println(“Name = “+name);System.out.println(“Roll no= “+roll);showstudy();

}

public void showsports() {

System.out.println(“Team = “+team);System.out.println(“Ranck = “+ranck);

}}class multiple_inheritance2{public static void main(String args[]) throws IOException{student s=new student();s.getstudent();s.showstudent();s.showsports();}}

Hierarchical Inheritance: when one master class contains multiple child class then it is known as Hierarchical inheritance. Hybrid inheritance: Hybrid inheritance is the combination of Hierarchical and multiple inheritances. When a class contain two or more child class and these child class further inherited by a child class then it is known as hybrid inheritance. In c++ it is direct possible but in java where a class cannot have two parents, we have to use interface to make a hybrid inheritance.Constructor inheritance: in c++:#include<iostream.h>#include<conio.h>class alpha{

Page 106: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

int a;public :alpha(int a1)

{a=a1;

}void showalpha()

{cout<<”\n value of a “<<a;

}};class beta{int b;public :beta(int b1)

{b=b1;

}void showbeta()

{cout<<”\n value of b “<<b;}};class gama : public alpha, public beta{int g;public :gama(int a1, int b1, int g1): alpha(a1), beta(b1)

{g=g1;

}void showgama()

{cout<<”\n value of g “<<g;

}};void main(){clrscr();gama g(5,7,9);g.showalpha();g.showbeta();g.showgama();getch();}Overriding: When a subclass of superclass implements a method that has the same name as well as the same set of arguments as the method in the superclass, it is called as method overriding.when such an method is called through a subclass’s object, then subclcass mehod would be invoked. However the superclass version of the method would remain hidden. So to call the super class version of the method we should use super key word.Example :/**************overriding******/class superclass{void print(){System.out.println(“I am method of super class”);}

Page 107: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}class subclass extends superclass{void print() {System.out.println(“I am method of sub class”); }void call() {print(); //will call to the sub class methodsuper.print(); //will call to the super class method }}class overriding{public static void main(String args[]) {subclass obj=new subclass();obj.call(); }}Use of Super Keyword: when a member in the superclass is declared as private member it is not available for use by the subclass. But java provides a solutiont to this problem also. When a subclass needs to refer to such varibles, they can do so by using the keyword super. The keyword super is used in the following three cases:1. To access the super class constructor2. To access a private member of the sueprclass3. one or more member names of the sub class that hide members(wth the same name) in the superclass.(Example Overriding)Exampe 1; /************call to the constructor of super class******/class employee{String ename;int ecode; employee(String name, int code) { ename=name; ecode=code; } void show() { System.out.println("Employee Name "+ename); System.out.println("Employee code "+ecode); }}class company extends employee{int salary; company(String name, int code, int sal) { super(name,code); salary=sal; } void display() { System.out.println("Salary of employee is "+salary); }}class bussiness{public static void main(String args[]){company obj=new company("David",012,15000);obj.display();obj.show();}}Example: /****execcesing private member of super class***********/class superclass{int i=10;}class subclass extends superclass{int i=100; void display() { System.out.println("Value of sub i is "+i); //will print sub's i value 100 System.out.println("value of super i is "+super.i); //will print super's i value 10 } public static void main(String args[])

Page 108: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{ subclass obj=new subclass(); obj.display(); }}

Garbage Collection:Garbage collection is an automatic function executed by JVM which deal locates the

memory occupied by objects that are no longer referenced by any variable. Memory is object is allocated for an object using the new operator. But when this object in no longer in used then we need to release the memory occupied by this object. So java uses a technique for it that is known as garbage collection. Garbage collection technique will remove the pointer from the reference to this object. Example: /*****************garbage collection*********************/

Finalize Methods: Before an object is garbage collected i.e. destroyed from memory, the finalize() method of corresponding class is executed. This process is known as finalization. We generally know that a constructor is used to initialize an object when it is declared. This process is known as initialization. Similarly java supports a concept of fFinalization, which is just opposite to initialization. So free the memory occupied by object we use finalize method in java which just similar to the destructor method of c++. This method can be added to any class and generally called by java whenever it is about to reclaim the space for that object. The finalize method should explicitly define the tasks to be performed.The protected key word is necessary before the name of finalize method.Syntax:Protected void finalize (){Code}

Example:/*************finalize method************/class show{ void display() { System.out.println("hello"); } protected void finalize() { System.out.println("it is going"); }

public static void main(String asergs[]) { show obj=new show(); show obj1=new show(); show obj2=new show(); show obj3=new show(); obj.display(); obj.finalize(); obj1.finalize(); }}

Abstract Method and Classes: we know that by making a method final we can’t redefined this mehod in a subclass. But java allow us to do something just opposite to it. java can make overriding compulsary. This is done by the modifier keyword abstract in the method defination. While using an abstract class then we have to follow the following rules:

1. We can not create an object of abstract class, it can be inherited only but not instantiated.2. The overriding of method of abstract class is must in subclass.

Page 109: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

3. We can not declare abstract constructor or abstract static methods.4. An abstract class must contain at least one abstract method.5. A class that contains one or more abstract mehods is also an abstract class.6. Although we can not create object of an abstract class but we can create reference variable of an

abstract class.7. An abstract class can’t implements method of another abstract class only a concrete class can

implements method of an abstract class.8. To make a class or method abstract we need to preceed their name by abstract key word.

Classes are of two types.1. Concrete class-> the class object creation of which is possible is known as concrete class.2. Abstract class-> the class object creation for which is not possible and those class are only can be

inherited are known as abstract class.Dynamic method dispatch : Dyanamic method dispatch is the mechanism by which a call to an overriden method is resoved when the code is executed, rather than at compile time. This technique is also known as dynamic binding. In below example we are assigning the object of class circle and trianagle to the reference variable to class shape. And this method is invoking the method of the class whose object is assigned to the reference variable abstract class. This process is known as dynamic method dispatch.Example: /**abstract class demo and dyanamic method dispatch demo***/abstract class shape{ abstract void draw(); }class circle extends shape{ void draw() { System.out.println("Drawing a circle"); }}class Triangle extends shape{ void draw() { System.out.println("Drawing a Triangle"); }}class drawshape{public static void main(String args[]){//shape s=new shape(); //this wrong, not possiblecircle c=new circle();Triangle t=new Triangle();shape s; //this is possible to create a reference variables=c;s.draw();s=t;s.draw();}}Static: when we want that a class member should be used independently of any object of that class, we have to precede that member’s declaration with the keyword static. When a member declared as static , it can be accessed without creating an object of the class and withou referring to the object. That is a static member belongs to a class as as whole and not to any one instance/object of that class. The static member is shared by all the objects of that class. Some points about static keyword:

1. All statements containing the static keyword are executed first.2. Member variables declared as static are global variable. That is , when objects of that class are

declared, no copy of the static member variable is made. Instead , all instances (objects) of that class share the same static variable.

3. Member method declared as static:1. Can only call other static methods only.2. Can only access static data directly3. Cannot use the keyword this and super.

Page 110: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Now we should understand why we should define the main() method as static. This is because, the main() method is called by JVM before any object of the class exist and therfore must be called independent of any objects. Henc main() method should be static.

Example: /********************static method demo**********/class arithmetic{ static float mul(float x, float y) { return x*y; } static float divide(float x, float y) { return x/y; }}class _Static{public static void main(String args[]){float a=arithmetic.mul(10,20);float b=arithmetic.divide(5,5);System.out.println("value of a "+a);System.out.println("value of b "+b); }}Example :/********static variable demo************/class Staticdemo{static int count; Staticdemo() { count++; } void show() { System.out.println("value of count "+count); } public static void main(String args[]) { Staticdemo s1=new Staticdemo(); s1.show(); Staticdemo s2=new Staticdemo(); s2.show(); Staticdemo s3=new Staticdemo(); s3.show(); }} Final Variable and Methods and Final Class: all the methods and variables can be overridden by default in subclasses. If we wish to prevent the subclass from overriding the numbers of the super class we can declare them as final using the keyword Final as a modifier. Making a method final ensures that the functionality defined in this method will never be altered in any way. Similarly the value of a final variable can never be changed. Final variable behaves like class variables and they do not take any space on individual objects of the class. When we want to prevent a class from being inherit then we can declare that class as final because a final class never inherited, if we try do so an error message will occur. A class declared as final when we may like to protect a class due to some security reasons.Example: /*************final class, variable, method ******/final class employee{final String name="ajay";final int rollno=1;

final void display() { System.out.println("name is "+name);

Page 111: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println("Rollno is "+rollno); }}class salary extends employee //error:can't inherit final class{float salary; void getsalary() { name="viajay"; //error:can't assign value to a final variable rollno=2; //error:can't assign value to a final variable salary=10000; display(); } public static void main(String args[]) { salary s=new salary(); s.getsalary(); }}

Visibility control or Access Modifiers or Access specifies: it is possible in java to restrict the access to certain variables and methods from outside the class. This is done in java by visibility control or access specifies. Java provides three types of access specifiers namely public, private and protected. This provides different level of protection which as follow:Public Access: if we want to make a variable or method of a class visible to all the classes outside its class in the same programme, then we can do this by declaring it as public. A variable declared as public has the widest possible visibility and accessible everywhere. Friendly Access: when we do not specifies any access specifier for a variable or method, then by default they have friendly access. The difference between public and friendly access is that, the public modifier makes fields visible in all classes, regardless of their packages while the friendly access makes fields visible only in the same package, but not in other packages. Protected Access: The visibility level of a protected field lies in between the public access and friendly access. That is, the protected modifier makes the field visible not only to all classes and subclasses in the same package

but also to subclasses in other package. But non-subclasses of other package can’t access the protected members.Private Access: Private Fields enjoys the highest degree of protection. They are accessible only within their own class. They cannot be inherited by subclasses and therefore not accessible in subclasses. A method declared as private behaves like a method declared as final. Such method cannot be overridden.Private Protected Access: a filed can be declared with two keywords private and protected together. This gives a visibility level in between the protected access and private access. This modifier makes the fields visible in all subclasses regardless of their package. These fields are not accessible by other classes in the same package.Rules of Thumb:

1. Use public if field is to be visible everywhere.2. Use protected if field is to be visible everywhere in the current package and also subclasses in other

packages.3. Use default if the field is to be visible everywhere in the current package only.4. User private protected if field is to be visible only in subclasses, regardless of packages.5. Use private if the field is not to be visible anywhere except in its own class.

Example: /***************use of all access specifier***********/class access{public String name;

Page 112: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

protected int id;private int code;private protected double salary; //wrong type not allowedString address;

access(String n, int i, int c, double s, String a){name=n;id=i;code=c;salary=s;address=a;}

public void displayname(){System.out.println("name is "+name);}

protected void displayid(){System.out.println("Id is "+id);}

private void displaycode(){System.out.println("Code is "+code);}

private protected void displaysalary(){System.out.println("Salary is "+salary);}

void displayaddress(){System.out.println("Address is "+address);}

}

class specifier{public static void main(String args[]){access obj=new access("amir",1,2,120.34,"dun");obj.displayname();obj.displayid();obj.displaycode();obj.displaysalary();obj.displayaddress();}}

Page 113: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

InterfaceAn interface is basically a kind of class. Like classes interface contain methods and variables. But interface define only abstract methods and final fields. This means that interface do not specify any code to implement these methods and data fields contain only constants. So it the responsibility of the class that implements an interface to define the code for implementation of these methods.Syntax:

interface <interface name>{Variable declaration and initializationMethods declaration}

Example:Interface sports{String team_name=”India”;int Rank=1;}To use an interface in a class we should use the keyword implements.Example:Class abc implements sports{}

/*interface example*/interface demo{int a=14;int b=20;public void add();}class xyz implements demo{public void add(){int c=a+b;System.out.println("Sum is "+c);}public static void main(String args[]){xyz obj=new xyz();obj.add();}}

/*interface inheritance*/interface first{int a=10;int b=20;

Page 114: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

public void show();}

interface second extends first{int x=40;int y=50;public void display();}

class xyz implements second{

public void show(){System.out.println("Value of a "+a);System.out.println("value of b "+b);}

public void display(){System.out.println("Value of x "+x);System.out.println("value of y "+y);}

public static void main(String args[]){xyz obj=new xyz();obj.show();obj.display();}

}/***********multiple interface implementation****/interface first{int a=10;int b=20; void show();}

interface second {int x=40;int y=50; void display();}

class abc implements first,second{

public void show(){System.out.println("Value of a "+a);System.out.println("value of b "+b);}

Page 115: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

public void display(){System.out.println("Value of x "+x);System.out.println("value of y "+y);}

public static void main(String args[]){abc obj=new abc();obj.show();obj.display();}

}

Packages(Putting Classes together or class libraries)

Packages of java are a way of grouping classes and interfaces together. This grouping usually done according to functionality. In fact packages act as containers for classes. Package name always starts form small latter while a library class name always starts form capital latter. Java.leng is the default package of java. Following are the benefits of packages.

1. The classes contained in the packages of other programs can be easily reused.2. In packages, classes can be unique compare with classes in other packages. That is two classes in

two different packages can have the same name. 3. Packages provide a way to hide classes thus preventing other programs or packages from accessing

classes that are meant for internal use only.4. Packages also provide a way for separating deign from coding. First we can design classes and

decide their relationships, and then we can implement the java code needed for the methods.Java packages can be classified into two categories.

1. Java API packages. 2. Defined packages.

Java API packages: java API is contain only the packages those are built-in i.e. provided by JDK, this group does not contain packages defined by the user. Java API provides a large number of classes grouped into a number of packages according to functionality. Java API packages group contain mainly 6 packages.

1. lang 2. util 3. io 4. awt 5. net 6. appletDefined packages: these are the packages defined by the user. These packages are the collection of user defined classes and interfaces, so these do not contain any library class or interface. These are to create own library by the user for his use.How to use a package: To use a package we use the keyword import. It is the first statement in the source code before any statement. There are two way to use the class stored in a package. The first approach is to use the fully qualified class name of the class that we want to use.Example: java.awt.Color; //fully qualified class nameJava->package, awt->package, Color->ClassSecond we can access a class from a package or hierarchy of packages by short form. Example:

Java.awt.*;This method will associate all the classes of awt package with our program. This is the best method of accessing package.Using a package:

Page 116: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

import java.io.*; class xyz{}

How to create a package: To create a package follows the following steps:package arif;public class xyz1{public static int add(int a, int b){return (a+b);}}Steps:1. Type package keyword before the name of the package.2. Type a valid identifier (name) of the package.3. Define class with public keyword that you want to put in the package.4. Declare methods with public keyword that you want to use in a class of the package.5. Save this program by class name, like this (arif.java).6. Compile this package by following method:

javac -d c:\jdk1.6.0\bin arif.java7. After this compilation a folder with name arif will be created in the bin folder.

Example: /************creating package for math operation***/package arithmatic; //this the method of creation a packagepublic class Math{public static int add(int a, int b){return a+b;}public static int substract(int x, int y){return x-y;}public static int divide(int a, int b){return a/b;}public static int multiply(int x, int y){return x*y;}}Example: /*******class to use the arithmetic package******/import arithmatic.*; //this is the method of using a user define package.class mathoperation{int a=10,b=20; void display() { System.out.println("Sum is "+ arithmatic.Math.add(a,b)); } public static void main(String args[])

Page 117: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{ mathoperation obj=new mathoperation(); obj.display(); }}Adding two class to a package: to add two or more class to a package perform the following steps:1. Add a single class to the package.

Example-> package pp;Public classA{}

Compile it :-> javac –d c:\jdk1.6.0\bin classA.java2. Now to add second class wirte the same package name at the top and then type class source code.

Example-> package pp;Public classB{}

Compile it :-> javac –d c:\jdk1.6.0\bin classB.java3. In the same way we can add a number of classes to the same package.Example:/*creating a package that contain two class of reverse, first to reverse a number and second to reverse string **********//******************adding ReverseNumber class to reverse package*/package reverse;public class ReverseNumber{ public static int reverse(int num) { int r,s=0; while(num>0) { r=num%10; s=s*10+r; num/=10; } return s; }}/*************adding ReverseString class to reverse package***/package reverse;public class ReverseString{ public static String reverse(String str) { int i; String rvstr=""; for(i=str.length()-1;i>=0;i--) rvstr=rvstr+str.charAt(i); return rvstr; }}/***********using reverse package to reverse anumber***/import reverse.ReverseNumber;class operation{public static void main(String args[])

Page 118: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{int num=1234;int rnum=ReverseNumber.reverse(num);System.out.println("Reverse Number is "+rnum);}}/*******using reverse package to reverse a string***/import reverse.ReverseString;class operations{public static void main(String args[]){String str="Mohammad Arif";String rvstr=ReverseString.reverse(str);System.out.println("Reverse String is "+rvstr);}}

Hiding a class in a package: when we import a package using asterisk (*), all public class are imported. However we may prefer to not import certain classes. That is we may like to hide these classes from accessing from outside of the package. Such class should be declared not public.Example:Package p1;Public class A //public, available outside{}Class b //not public, hidden{}Example:/**public class NumberOperations in number package , is visible to all**/package number;public class NumberOperations //public class, accessible{ public static boolean sunny(int num) { int r,t,s=0; t=num; r=num%10; s=r*r*r; if(t==s) return true; else return false; }

public static boolean armstrong(int num) { int t,r,s=0,c=0; t=num; while(num>0) { r=num%10; c=r*r*r; s=s+c; num/=10;

Page 119: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

} if(s==t) return true; else return false; } public static boolean perfect(int num) { int i,s=0; for(i=1;i<=num/2;i++) if(num%i==0) s+=i; if(s==num) return true; else return false; }}/*************non public class in number package***************/package number;class Display //non public class, hidden{public static void show(){System.out.println("Hello java");}}/* class to test operation in public class NumberOperations of package number*/import number.NumberOperations;class test{ void sunny() { int num=125; boolean b1=NumberOperations.sunny(num); if(b1==true) System.out.println("Number is sunny"); else System.out.println("Number is not sunny"); }

void armstrong() { int num2=153; boolean b2=NumberOperations.armstrong(num2); if(b2==true) System.out.println("number is armstrong"); else System.out.println("number is not armstrong"); }

void perfect() { int num3=6; boolean b3=NumberOperations.perfect(num3);

Page 120: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

if(b3==true) System.out.println("Number is perfect"); else System.out.println("Number is not perfect"); }

public static void main(String args[]) { test t=new test(); t.sunny(); t.armstrong(); t.perfect(); }}/*non public class show of package number*/import number.*;class show{ public void showdetail() { number.Display.show(); //display is not accessible due to non public declaration. }}/****************hiding class concept ends here*********************/

Static import : This is another important feature of J2SE 5.0 version. This feature eliminates the need of qualifying a static member with the class name. Static import is similar to that of normal import statement that we use in common programs. By static import we can import static members from classes and use them without qualifying the class name.Syntax: import static <package-name>.<sub package-name>.<class-name>.*;Or import static <package-name>.<sub-package-name>.<class-name>.<static-member-name>;example: /************static import********/import static java.lang.Math.*; //static import statementclass mathop{ void circle(double r) { double area=PI*r*r; //PI is the static variable of class Math. System.out.println("Area is "+area); }

public static void main(String args[]) { mathop obj=new mathop(); obj.circle(2); }}

Adding Static member to the package by class and by interface and using them.Example: /***************creating static variable in a class of a package*/package Static;public class Math{public static final double PI=3.14;}

Page 121: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Example: /**using static variable of a class present in a package named static**/import static Static.Math.*; //Static is the package name while Math is the class name class staticuse{public static void main(String args[]){System.out.println("value of PI in Static package is "+PI); //using static variable PI}}Example : /***adding an interface to a package along with a static variable**/package Static;public interface Salary{public static final double Manager=10000;public static final double clerk=5000;}Example: /******using static variable from interface of package named Static**/import static Static.Salary.*;class useofstatic{ void show() { System.out.println("Salary of Manager is "+Manager); System.out.println("Salary of clerk is "+clerk); } public static void main(String args[]) { useofstatic obj=new useofstatic(); obj.show(); }}

/*package with Inbuilt package */package withmain;import java.io.*;public class xyz{

public void show() throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter a number ");int num=Integer.parseInt(br.readLine());System.out.println("you entered "+num);}

}Javac –d c:\jdk1.7.0\bin xyz.java

/*Using above package*/import withmain.xyz;import java.io.*;class pqr{public static void main(String args[]) throws IOException{xyz obj=new xyz();

Page 122: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

obj.show();}}

Javc CollectionsThe collections framework which is contained in the java.util package is one of java’s most powerful sub-system. The collection framework defines a set of interfaces and their implementations to manipulate collections, which serve as a container for a group of objects. This framework alos allow us to store, retrieve and update a set of objects. It provods an API to work the data structures, such as list, trees, maps and sets.Interfaces: The collection framework contain many interfaces, such as Collection, Mpa, and iterator. The interfaces of the framework extend these interfaces i.e. they are sub interfaces of thses interface. Like ListIterator is sub interface of Iterator interface.Description of interfacesThe collection interface: All collection classes must implement the collection interface. The collection interface defines some methods, which enable us to access the objects of a collection. Which are add(object o), addAll(collection c), clear(), and contains(object o) etc.The set interface: The set interface extends the collection interface and it contains the methods that are inherited from the collection interface. The set interface does not allow the use of duplicate elements in a collection. Hence the add() method return false, if we add duplicate element to the collection.The list interface: The list interface contains an orderd sequence of elements available in a collection. It allow duplicate elements in the list. The list interface inherits the methods of the collection interface. Beside this it alos contain methods like add(int index, object o), adddAll(int index, collection c) etc.The SortedSet interface: The sortedset interface is used to sort the elements of a collection in ascending order. It extends the set interface, which in turn textends the collection interface. This interface does not allow duplicate elements in the list. This interface contan methods like comparator(), first(), headset(object totoelelment ) etc.The Queue interface: This interface extends collection interface and declares the behavior of a queue, which is often a firs-in, firs-out list. In a squeue, elements can only be removed from the head of the queue. It contains few methods like element(), offer(object o), peek(), poll() etc.The map interface: The map interface mpas unique key elements to their values. For example, in a mail server, each mail ID is mapped to unique password. The map interface allows us to view the elements of a collection as set of keys, collection of values, and the mappings of key value pairs.The SortedMap interface: The SortedMap interface extends the Map interface. It contain elements in ascending order. In this the sorting is based on keys. The functionaliry of sortedmape interface is analogous to the functionality of the sorted interface. It contains methods like comparator(), fistkey(), headMap(object start, object end) etc.The iterator interface: The iterator interface enables us to sequentially travers and access the elements contained in a collection. The elements of a collection can be accessed using the methods defined by the iterator interface. It contain methods like hasNext(), next() and remove().Overview of classes: The classes available in the collections framework implement the collection interface and the subinterfaces. Thse classes also implements the map and iterator interfaces. The AbstractCollection class: The abstractcollection class implements the collection interface. Therefor it contains all the methods available in the collection interface. We use this class to implement a collection, which cannot be modified. For example a collection containing the months of a year cannot be modified.The AbsractList class: This class extends the AbstractCollection class and implements the List interface. We use the this class to access the data randomly. For example, we can use the index values to access the elements of an array at random.

Page 123: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

The ArrayList class: This class extends the AbstractList class and implements the interfaces, such as List, Cloneable and Serialzable. Using this class, we can use dynamic array in java applications. The dynamic array is not fixed. So we can change the size of array at run time using the ArrayList class. Every object of ArrayList class is allowed to store a set of elements in the list. The capcity increases automatically as we add elements to the list. It’s contrcutor can be in three forms:

1. ArrayList(): Creates an empty list. The capacity of the list is ten.2. ArrayList(Collection c): creates a list to which the elements of the specified collection are added.3. ArrayList(int capcity): creates an empty list. This capcity of the list is initialized to the specified

value.

/*The ArrayList class*/import java.util.*;class arraylist{public static void main(String args[]){ArrayList list=new ArrayList();System.out.println("Initial size of array list "+ list.size());list.add("a");list.add("b");list.add("c");list.add("d");System.out.println("Size of array list after adding the element"+list.size());System.out.println("Contents of array list "+list);list.add(2,"E");System.out.println("Changed contents of array list by adding elements at the given index "+list);list.remove(3);list.remove("a");System.out.println(" change contenst of array list by removing element from the list "+list);}}

The LinkedList class: This class extends the AbstractSequential class and implements the List interface. This class supports methods like addFirst(object ob), addLast(object obj), getFirst(), getLast() etc. these method allow us to insert and remove elemnent in a list. We can use list as a stack, queue, and double linked list. It constructor are like this:LinkedList()LinkedList(Collection c)

/*using the method of LinkedList class*/import java.util.*;class MyStack{LinkedList list=new LinkedList();

public void push1(Object obj){list.addFirst(obj);}public void push2(Object obj){list.addLast(obj);}

public Object bottom()

Page 124: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{return list.getLast();}public Object pop(){return list.removeFirst();}public static void main(String args[]){Car mycar;Bird mybird;MyStack s=new MyStack();s.push1(new Car());s.push2(new Bird());mycar=(Car)s.pop();System.out.println("The first element in the list :"+mycar);mybird=(Bird)s.bottom();System.out.println("The last element in the list "+ mybird);}}Class Car{String car1, car2, car3, car4;

Car(){car1="Benz";car2="Toyoto";car3="Qualis";car4="Santro";}}

class Bird{String bird1, bird2, bird3;

Bird(){bird1="parrot";bird2="duck";bird3="raven";}}

The HashSet Class: This class extends the AbstractSet class and implements the Set interface. The AbstractSet class itself extends the AbstractCllection class. The HashSet class is used to create a collection nad store it in a hash table. Each collection refers to a unique value called has code. The has code is used as an index to associate with the object, which is stored in the hash table. This type of storing information in a hash table is called hashing. Constructor for this class are:HashSet(): constructor an empty HashSet.HashSet(Collecttion c): Initializes the HashSet using the element cHashSet(int capacity): Initializes the capacity of the has set.HashSet(int capcity, float fillratio): Initializes the capacity and the fill ratio of the HashSet.

Page 125: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

/*Hash Set Class*/import java.util.*;class hashtable{public static void main(String args[]){HashSet hs=new HashSet();hs.add("a");hs.add("b");hs.add("c");hs.add("d");System.out.println("Print the elements of hash set "+ hs);}}

TreeSet Class: The TreeSet Class implements the set interface. The sorted elements are stored in a tree structure. This class allows us to access and retrieved the elements from a tree in less time. The constructor for the TreeSet class can take the following forms. TreeSet(): Builds an empty tree set. This will sort the elements in ascending order.TreeSet(Comparator comp): This will build a tree set based on the specified comparator.TreeSet(Collection c): Builds a tree set, which contains a collection of elements.TreeSet(SortedSet s): Builds a tree set, which contains elements in the specified order.

import java.util.*;class treeset{public static void main(String args[]){TreeSet ts=new TreeSet();ts.add("b");ts.add("c");ts.add("a");ts.add("e");ts.add("d");System.out.println("The elements in the tree set are "+ ts);}}

Vector Class: Vector is the new feature of java introduce by J2SE 5.0 version. This feature can be achieved by Vector Class contained in the java.util package. This class can be used to create a generic dynamic array known as vector. A vector can hold objects of any type. Array can be implanted as vector. Vector are created as:Vector name of vector=new Vector();Vector name of vector=new Vector(5);Vector can be defined without specifying any size or with size. A vector with size can take an unknown number of items. But when size is specified, this can be overlooked and a different number of items may be put into vector.Advantages of vector over array1. It is convenient to use vectors, to store objects.2. A vector can be used to store a list of objects that may vary in size.3. We can add and delete objects from the list as and when required.Disadvanteage

Page 126: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

We cannot directly store simple data type in a vector. But we can only store objects. So we need to convert simple to object, that we can do by using wrapper classes.Syntax:Vector vect=new Vector(); //declaring without sizeVector list=new Vector(3); //declaring with sizeVector posses some advantages over arrays:1. It is convenient to use vectors to store objects.2. A vector can be used to store a list of objects that may vary in size.3. We can add and delete objects from the list as and when required.But major disadvantage of vector is this we can’t not store primitive values in a vector directly. Vector can store objects only so we need to convert primitive into object first after that we can store them.

/*vector program with multiple data type*/import java.util.*;class item{public static void main(String args[]){Vector list=new Vector();list.add("apple");list.add("mango");list.add("banana");list.add(13);list.add('a');list.add(12.23);

int length=list.size();

for(int i=0;i<length;i++)System.out.println(list.elementAt(i));}}

/*vector by command line argument*/import java.util.*;class vectorcmd{public static void main(String args[]){Vector list=new Vector();for(String s: args)list.add(s);for(int i=0;i<list.size();i++)System.out.println(list.elementAt(i));}}

/*Vector class various functions*/import java.util.*;class vectorfunctions{public static void main(String args[]){Vector list=new Vector();

Page 127: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

list.add(10); //will add an element at zeroth positionlist.insertElementAt("arif",0);list.insertElementAt(20,1);//insert element at 1 position

System.out.println(list.capacity()); //return the current capacity of the vector

System.out.println(list.contains("arif")); //will return true if element is present other wise false.System.out.println(list.remove("arif")); //will return true of if element is removed and if not present then will return falseSystem.out.println(list.get(0));//will return an element present the given index

String s=new String("Amir"); //making an string objectlist.setElementAt(s,0);//will insert an object at the given index

Integer j=new Integer(1000);//making integer objectlist.setElementAt(j,1); //inserting integer object

list.setSize(5);//will set the size of vector and blancs will be filled by null

System.out.println("\n================");for(int i=0;i<list.size();i++)System.out.println(list.elementAt(i));list.removeAllElements(); //will remove all the elements}}

/*use of iterator*/import java.util.*;class iteratordemo{public static void main(String args[]){Vector lst=new Vector();lst.add(10);lst.add(20);lst.add(30);lst.add(40);Iterator i=lst.iterator();while(i.hasNext())System.out.println(i.next());}}

/*conversion of vector into array*/import java.util.*;class vectorwitharray{public static void main(String args[]){Vector list=new Vector();int length=args.length;int i;for(i=0;i<length;i++)list.add(args[i]);

Page 128: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

int size=list.size();String arr[]=new String[size];list.copyInto(arr); //copying elements of vector into array

System.out.println("Vector elements after conversion in array ");for(i=0;i<arr.length;i++)System.out.println(arr[i]);}}/*conversion of vector object into array*/import java.util.*;class vectorexample{public static void main(String args[]){Vector<String> v=new Vector<String>(15);int i;System.out.println("Starting ");for(i=0;i<args.length;i++){v.add(args[i]);System.out.println(args[i]+"\t added to vector ");}System.out.println("Converting to array ");String [] list =new String [v.size()];v.copyInto(list);System.out.println("printing array ");for(i=0;i<v.size();i++)System.out.println("elements at "+i+" Location is "+list[i]);}}

The Stack Class: The stack class extends the Vector class. In addition to the inherited method from the vector class, this class contains some methods to perform operations, such as push, pop, peek and search. The stack class uses the First In Last Out (FILE) mechanism. The constructor of stack classs can be reprsended as:Stack(): Used to create an empty stack. the method of stak class are empty(), peek(), pop() , and push()./*use of Stack CLass*/import java.util.*;class stackdemo{public static void main(String args[]){Stack st=new Stack();st.push("java");st.push("latest");st.push("Edition");st.push("Fifth");System.out.println("The elements in the stack "+st);System.out.println("The elements at the top "+st.peek());System.out.println("The elements poped out from the stack "+st.pop());System.out.println("The elements in the stack after poping "+st);System.out.println("The result of searching "+st.search("r u"));}

Page 129: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}

Enumerated Types: J2SE 5.0 allows us to use the enumerated type in java using the enum keyword. Enum cannot be used with earlier versions of java. Enum data type gives us an opportunity to invent our own data type and define what values the variable of this data type can take. Enum is just similar to the structure of c++.Example:/**********working days**********/class workingdays{enum days{sunday,mondya,tuesday,wednesday,thrusday,friday,saturday}public static void main(String args[]){for(days d:days.values())if(d.equals(days.sunday))System.out.println(d+" is holiday");elseSystem.out.println(d+" is working day");}}

Hashtable Class: The hashtable class implements the interfaces, such as Map, Cloneable, and serializable. The hashtable is used to store values in the form of map key with value. The key should implement the hashcode and equals methods to store and retrieve values in a hashtable. The constructors of the hastable class are:Hashtable(): creates an empty hashtable with the default initial capacity as 11 and the loadFactor as 0.75.Hashtable(int initialcapacity): creates an empty hastable with the specified initial capacity and the default loadFactor.Hashtable(int initalcapacity, float loadfactor): creates an empty hashtable, which has the specified initial capacity and loadfactor.Hashtable(Map m): careasts a new hashtable with the specified map.

import java.util.Enumeration;import java.util.Hashtable;class heshtable{public static void main(String args[]){Hashtable ht=new Hashtable();ht.put("Item1", "Apple");ht.put("Item2", "Orange");ht.put("Item3", "Graphs");ht.put("Item4", "pine");Enumeration e= ht.keys();while(e.hasMoreElements()){String str=(String) e.nextElement();

Page 130: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println(ht.get(str));}}}

Overview of algorithm: The collection framework supports several algorithms that allow us to operate on collections. We can use these algorithms to sort, shuffle, manipulate, and search a set of elements in a collection. Some of the algorithms available in the collections framework are:Sorting.ShufflingManipulatingSearching.The sort algorithm: This algorithm enables us to arrange the elements of a list in a certain order. The ordering depends on the type of elements. It the list contains a set of strings, the sorting is done alphabetically. If the list contains a set of numeric elements, the elements are arranged in ascending order./*use of sorting alogrithm*/import java.util.*;class sorting{public static void main(String args[]){LinkedList lst=new LinkedList();lst.add(new String("java"));lst.add(new String("is"));lst.add(new String("platform"));lst.add(new String("Independent"));

Collections.sort(lst);

Iterator iter=lst.iterator();while(iter.hasNext())System.out.print(iter.next()+" ");}}

/*sort alogrithm with number*/import java.util.*;class sortings{public static void main(String args[]){LinkedList lst=new LinkedList();lst.add(2);lst.add(4);lst.add(1);lst.add(5);lst.add(3);System.out.println("Ascending order");Collections.sort(lst);Iterator i=lst.iterator();while(i.hasNext())System.out.println(i.next()+" ");

System.out.println("Reverse (Descending) Order ");Collections.sort(lst, Collections.reverseOrder());

Page 131: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Iterator it=lst.iterator();while(it.hasNext())System.out.println(it.next()+" ");

}}

The Shuffle algorithm: This algorithm shuffles the elements of a list such that the current order of the list is destroyed. This algorithm arranges the elements using all possible permutations. For example we can use this algoritm to shuffle objects in memory game./*use of shuffle alogrithm*/import java.util.*;class shuffle{public static void main(String args[]){LinkedList lst=new LinkedList();lst.add(new String("java"));lst.add(new String("is"));lst.add(new String("platform"));lst.add(new String("Independent"));

Collections.shuffle(lst);

Iterator iter=lst.iterator();while(iter.hasNext())System.out.print(iter.next()+" ");}}

Manipulate Algorithm: The collections class provides algorithms to perform operations, such as fill, reverse, copy, swap and add on a list of elements on a collection. The reverse opration reverses the order of elements in the list. The fill operation replaces the elements of a list with a specified elements. The copy operation copies the elements of one list to another. The swap operation swaps the specified elements in a list. The addAll operation adds the specified elements to a list.The search algorithm: The search algorithm allows us to search an element in a collection. Here we use the binary search algorithm. To find an element from a list, we need to traverse the entire list. The steps to find an element from a list using binary search alogirthm are.

1. Sort the elements in the collection.2. Find the middle element of the collection.3. Compare the specified element with the middle element of the collection.4. If the middle element is greater than the specified element, traverse the first half of the list. Else

traverse the second half of the list./*binary search*/class binarysearch{public static void main(String args[]){int first=0, last=args.length, i=0;String key="Hello";int mid=0;while(first<last){ mid=(first+last)/2;

Page 132: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

if(key.compareTo(args[mid])<0)last=mid;else if(key.compareTo(args[mid])>0)first=mid+1;else{i=1;break;}}if(i<0)System.out.println("not Found ");elseSystem.out.println("Found at "+mid+" location");}}/*use of iterator*/import java.util.*;class algorithm{public static void main(String args[]){LinkedList lst=new LinkedList();lst.add(new String("java"));lst.add(new String("is"));lst.add(new String("platform"));lst.add(new String("Independent"));

Iterator iter=lst.iterator();while(iter.hasNext())System.out.print(iter.next()+" ");

System.out.println("\n\n Minimum :"+Collections.min(lst));System.out.println(" Maximum :"+Collections.max(lst));}}

Wrapper ClassesAs we know vectors can’t handle primitive data types like int, float, long, char etc. so wrapper classes are the option by which we can convert primitive type value into object. These classes are present in java.lang package. Wrapper class always starts from capital letter. Following are the wrapper classes:boolean Booleanchar Characterdouble Doublefloat Float int Integerlong Longbyte Byteshort Short

The wrapper classes have a number of unique methods for handling primitive data type and objects.

Page 133: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Conversion from primitive value to object by wrapper classes1. Integer intvalue=new Integer(i);2. Float floatvalue =new Float(f);3. Double dbvalue=new Double(d);4. Long lgvalue=new Long(lg);

Here i, f, d, lg are the primitive value and these has been converted to intvalue, floatvalue, dbvalue, lgvalue by their respective classes.

Conversion from object to primitive valuesint i=intvalue.intValue();float f=floatvalue.floatValue();long l=lgvalue.longValue();double d=dbvalue.doubleValue();

Conversion from numbers to String str=Integer.toString(10);str=Float.toString(12.23f);str=Double.toString(12.35);str=Long.toString(123456789);

int value1=10;int value2=20;int sum=value1+value2;String s="Sum : "+String.valueOf(sum);Conversion from string to numeric valuesDbvalue=Double.ValueOf(str);Flvalue=Float.ValueOf(str);Lgvalue=Long.ValueOf(str);Intvalue=Integer.ValueOf(str);Orint i=Integer.parseInt(str);long lg=Long.parseLong(str);float fl=Float.parseFloat(str);byte bt=Byte.parseByte(str);

Dates and Times (Date and Calendar objects)A date object represent the current system date and time. Example: /***********use of data class*******/import java.util.*;class dateshow{public static void main(String args[]){Date d=new Date();System.out.println("The Date is : "+d);}}Output: The date is Thu Mar 03 22:59:52 PST 2011

Autoboxing and Unboxing: This is the feature of J2SE 5.0 version. It facilitates the handling of primitive data types in collections. We can use this feature to covert primitive data types to wrapper class types automatically. The compilar generates a code implicitly to convert primitive type to the corresponding wrapper class type and vice-versa.For example adding two elements from stack/*Stack sum program without Boxing technique*/

Page 134: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

import java.util.Stack;class autobox{public static void main(String args[]){Stack mystack=new Stack();mystack.push(new Integer(10));mystack.push(new Integer(20));

Integer n1=(Integer)mystack.pop();Integer n2=(Integer)mystack.pop();

int s=n1.intValue()+n2.intValue();System.out.println(s);}}

/*Stack sum program with Boxing technique*/import java.util.Stack;class autoboxing{public static void main(String args[]){Stack<Integer> mystack=new Stack<Integer>();

mystack.push(10); //autoboxmystack.push(20); //autobox

int s=mystack.pop()+mystack.pop(); //unboxingSystem.out.println("The sum is "+s);}}

Annotations: page(173)

Exceptions HandlingTesting and Debugging: Testing is the process of making sure that program performs the intended task, and debugging is the process of locating and eliminating errors. Boath these are different taks and we can differentiate them like this:

Testing DebuggingTesting is a process in which a program is validated

Debugging is a process in which the errors in the program are removed.

It is a positive activity that seeks to demonstrate that the program is correct.

It is negative activity in a sencse that it is centered around elemination of known errors or bugs.

Testing is complete when all desired verifications against spefifications have been performed.

Debugging is finshed when there are no errors and the program is ready for execution.

What are errors?

Page 135: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Errors are the wrongs that can make a program go wrong. An error may produce an incorrect output or may terminate the execution of the program abruptly or even may cause the system to crash. So it is important to detect and manage properly all the possible error conditions in the program so that the program will not terminate or crash during execution.

Types of Errors: There are two types of errors.1. Compile time errors.2. Run-time errors.

Compile Time Errors: All syntax error those can be detected at compile time by java compiler is known as compile time errors. Whenever the compiler displays an error, it will not create the .class file. It is therefore necessary that we fix all the errors before we can successfully compile and run the program. Java compiler dose a nice job of telling us where the errors are in the program. Example:Error1.java:7: ‘; expected System.out.println (“Hello java”)^1 errorThis message tells us the appropriate line where we are doing mistake. The most common problems are:

1. Missing semicolons.2. Missing brackets in classes and methods.3. Misspelling of identifiers and keywords.4. Missing double quotes in strings.5. Use of undeclared variables.6. Incompatible types in assignments/initialization7. Bad references to objects.8. Use of = in place of = = operator

Run time errors: When a program produced wrong result due to wrong logic or may terminate due to errors at run time, such errors are known as runtime errors. These errors may cause due to following reasons.

1. Dividing an integer by zero.2. Accessing an element that is out of the bounds of an array.3. Trying to store a value in an array of incompatible type.4. Trying to cast an instance of a class to one of its subclasses.5. Passing a parameter that is not in valid rang or value for a method.6. Trying to illegal change the state of a thread.7. Attempting to use a negative size of array8. Converting invalid string to a number.9. Accessing a character that is out of bound a string.

These errors does not cause any error at the time of compilation but these generate an error at run time and cause abnormal termination of the program or a wrong output.

Exceptions: An exception is the condition that is caused by run time error in the program. When java interpreter encounters a run time error, it creates an exception object and throws it i.e informs us that an error is encountered. If the exception is not caught and handled then interpreter will display and error message and will terminate the program execution. If we want to make our program run properly then we should try to catch this exception object thrown by the error condition and then display an appropriate message for talking corrective actions. This task is known as exception handling.

Exception Handling:The purpose of exception handling mechanism is to provide a means to detect and report an exception circumstance so that appropriate action can be taken. This mechanism suggests error handling code that performs the following task:

1. Find the problem (Hit the exception)2. Inform that an error has occurred (Throw the exception)

Page 136: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

3. Receive the error information (catch the exception)4. Take corrective actions (Handle the exception)

This mechanism basically consists of two segments, one to detect errors and to throw exception and the other two catch exception and to take appropriate actions.

Some common exceptionsArihmeticException -> caused by math errors such as division by zero

ArrayIndexOutOfBoundsException -> caused by bad array index.

ArrayStoreException -> Caused when a program try to store a wrong type value in an array.

FileNotFoundException -> caused by an attempt to access a nonexistent file.

IOException -> Caused by general input output failure.

NumberFormatException -> Caused when a conversion between string and number fails.

StringIndexOutOfBoundsException -> Caused when a program attempts to access a nonexistent character position in a string.

Syntax of Exception handling code:

Exception objectthrows Creatorexceptionobject

Exception handler

Java uses a key word try to prefer a block of code that is likely to cause an error condition and throw an exception. A catch block defined by the keyword catch, catches the exception thrown by the try block and handles it appropriately. The catch block is added immediately after the try block.Example: /*********try catch demo***********/class try_catch{public static void main(String args[]){int x; try { x=5/0; } catch(ArithmeticException e) { System.out.println("Division by zero"); }

Try block

Statement that causes an exception

Catch Block

Statement that handles the exception

Page 137: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}}

Multiple catch Statements: It is also possible to have more than one catch statement in the catch block.Try{Statement.

- - - - - - -

}Catch(Exception e){Statement.

- - -- - -

}Catch(Exception e){Statement

- - -- - -

}

Example: /********multiple catch blocks*/class excep1{public static void main(String args[]){try{int n=Integer.parseInt(args[0]);int n1=Integer.parseInt(args[1]);int n2=n+n1;System.out.println("Sum is = "+n2);}catch(ArithmeticException ex){System.out.println("Arithmetic Exception "+ex.getMessage());}catch(NumberFormatException ex){System.out.println("Number format Exception "+ex.getMessage());}catch(ArrayIndexOutOfBoundsException ex){System.out.println("Array index bound exception "+ex);}}}

Using finally statement: Finally block can be used to handle any exception generated within a try block. It may be added immediately after the try block or after the last catch block. When finally block is defined, this is guaranteed to execute, regardless of whether or not in exception is thrown. Example:/***********finally example*****/

Page 138: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

class exfinally{public static void main(String args[]){try{int n1=Integer.parseInt(args[0]);int n2=Integer.parseInt(args[1]);int n3=n1+n2;System.out.println("Sum is "+n3);}catch(ArithmeticException e1){System.out.println("Arithematic Exception Block 1");}catch(NumberFormatException e2){System.out.println("Number Format Exception Block 2 ");}catch(Exception e3) //default exception {System.out.println("Exception ");}finllay{System.out.println("It is finally block ");}}}}

Throw AND throws: The throws clause warns the compiler, the caller and the reader that the code in the method may throw an exception. In java signature can tell what abnormal things the method can do. The throws clause lists the types of exception that a method might throw. It is necessary for all the exception that a method can throw must be declared in the throws clause. If they are not, a compile time error will result.Example: this example is throwing an exception but neither it is catching to it nor throwing it out by throws clause so this program will not compile and will cause an error message. class throwsdemo{static void throwone(){System.out.println("Inside throwone");throw new IllegalAccessException("Demo");}public static void main(String args[]){throwone();}}But by doing two changes this program will work properly. First declare the throws clause with IllegalAccessException and second main() must define a try/catch statement that catches this exception.class throwsdemo{static void throwone() throws IllegalAccessException{System.out.println("Inside throwone");throw new IllegalAccessException("Demo");}public static void main(String args[])

Page 139: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{try{throwone();}catch(IllegalAccessException e){System.out.println("Caught "+e);}}}

Throw: By the help of throw method one can throw its own exception i.e one can generate its own exception in a program and can throw it, that works like normal java exception and needed to catch or throws from the program. When a user throws its own exception by throw, execution stops immediately after the throw statement and any subsequent statement are not executed. Then the nearest try block is inspected to see it as a catch statement that matches the type of the exception. if it does find a match than control is transferred to that statement. If not then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.

Syntax: Throw new throwable_subclass

(Note: To throw our own exception we should inherit Exception class in our program which is present in java.lang package.)

Example: /**this program throw an exception and a catch block catch it***/import java.io.*;import java.lang.Exception;class exception2 extends Exception{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int m=0;System.out.println("Enter the value of m ");m=Integer.parseInt(br.readLine());try{System.out.println("Entering try block");if(m>100){throw new Exception(m+"is too largs");}System.out.println("Exiting try block ");}catch(Exception e){System.out.println("Error :"+e.getMessage());}}}

Example: /************throwing our own exception*/class throw_exception{public static void main(String args[]){if(args[0]=="hello")System.out.println("String is right ");

Page 140: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

elsetry{throw new Exception("Invalid String ");}catch(Exception e){System.out.println(e.getMessage());}}}

/**********user define exception ******************/import java.lang.Exception;class negativeageException extends Exception{private int age;

public negativeageException(int age) { this.age=age; }

public String toString() { return "Age cannot be negative" +" "+age; }}class exceptiontest{public static void main(String args[]) throws Exception{int age=getage();if(age<0){throw new negativeageException(age);}else{System.out.println("Age entered is "+age);}}static int getage(){return -5;}}

/************user define exception *********/class negative extends exception{int age; negative(int age)

Page 141: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{ this.age=age; }

String toString() { return "Age cannot be negative" +" "+age; }}class exceptiontest{static void main(String args[]){int age=getage();if(age<0){throw new negative(age);}else{System.out.println("Age entered is "+age);}}static int getage(){return -10;}}

Example /*************use of throw and throws******/class throw_throws{public void throws_demo() throws ArithmeticException, ArrayIndexOutOfBoundsException{try { int a=10; a=a/0; } catch(ArithmeticException e) { throw e; }}public static void main(String args[]) throws ArithmeticException, ArrayIndexOutOfBoundsException{throw_throws obj=new throw_throws();obj.throws_demo();}}

Nested try statements: The try statement can be nested. i.e a try statement can be in the block of another try statement. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until the entire nested try statements are over. If no catch statement matches then java run time system will handle the exception.

Page 142: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

/*nested try*/class nestedtry{public static void main(String args[]){try{try{int arr[]={1};int x=arr[5];System.out.println(x);}catch(ArrayIndexOutOfBoundsException ex){System.out.println("Inner Exception ");}

int a=10;int b=a/0;

}catch(ArithmeticException e){System.out.println("Outer Exception ");}}}

/*************nested try statements***/class nestedtry{public static void main(String args[]){try { int a=args.length; int b=42/a; System.out.println("a = "+a);

try { if(a==1) a=a/(a-a);

if (a==2) { int c[]={1}; c[42]=99; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out of bound "+e);

Page 143: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

} } catch(ArithmeticException e) { System.out.println("Divide by 0 "+e); }}}

/*use of Exception class*/This class can hold every type of exception, which is not possible to hold by the other exceptional classes. It is master exception handling class. It will hold every type of exception. It is always last statement in case of multiple try-catch block, but will always come before finally block.

class exception_class{public static void main(String args[]){try{int a=12/0;}catch(ArithmeticException ex){System.out.println("Arithmetic Exception occured ");}catch(ArrayIndexOutOfBoundsException ex){System.out.println("Array Range over ");}catch(Exception ex){System.out.println("Exception master class that can handle all the exception ");}}}

ThreadingWhat is multithreadingMultithreading is a feature provided by the operating system that enables your application to have more than one execution path at the same time. Multithreading allow us to execute more than one application at the same time. Example microsoft word takes user input and display it on the screen in one thread while it continues to check spelling and grammatical mistakes in th scond thread, and at the same time the thrid thread saves the document automatically at regular intervals. MultitaskingIn multitasking different application execute at the same time. Example you listning music and doing chatting with your friend of facebook and at the same time you are painting an art in photoshop.

Thread: A thread is similar to a program that has a single flow of control. It has a beginning, a body, and an end, and executes commands sequentially.

Page 144: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Creating Threads: Threads are implemented in the form of objects that contain a method called run ( ). The run ( ) methods makes the body of entire thread. Syntax: public void run ( )

{Statement;Statement;}

The run method can invoked by start ( ) method. A new thread can be created in two ways.1. By creating a thread class: Define a class that extends Thread class and override its run ( ) method

with the code required by the thread.2. By converting a class to a thread: Define a class that implements Runnable interface. This interface

has only one method, run ( ), that is to be defined in the method with the code to be executed by the thread.

Extending a Thread Class: We can make our class runnable as thread by extending the class java.lang.Thread. This gives us access to all the methods directly. We can implement Thread class like below:

Class mythread extends Thread{

- - - - - - - - - - - -

}

Implementing the run ( ) method: we have to use this method to implements our thread. This method is present in thread class.

Public void run ( ){

- - - - - - - -

}

Starting a new Thread: we have to create an object of class in which we are implementing the thread and after that call the start ( ) method by the help of this object.mythread obj=new mythread();obj.start();example: /*******creating thread using Thread class**/import java.lang.Thread;class a extends Thread{int i; public void run() { for(i=1;i<=5;i++) { System.out.println(i); } System.out.println("exit from thread a "); }}class b extends Thread{ public void run() {

Page 145: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

for(int j=1;j<=5;j++) { System.out.println("\t"+j); } System.out.println("exit from thread b "); }}class c extends Thread{ public void run() { for(int i=1;i<=8;i++) { System.out.println("\t\t"+i); } System.out.println("exit from thread c"); }}class threadtest{ public static void main(String args[]) { new a().start(); b object; object=new b(); object.start(); c obj=new c(); obj.start(); }}Life Cycle of Thread: Life cycle of thread contain following stages.

1. Newborn state: When we create a thread object, the thread is born and is said to be in new born state. Thread at this stage is not yet to run. We can do following things at this stage.i. Schedule it for running using start ( ) method.ii. Kill it using stop ( ) method.

Start stop

Runnable State: The runnable state means thread is ready for execution and is waiting for the availability of the processor. i.e. thread has joined the queue of threads that are waiting for execution. If all thread has same priority then they have given time slots for execution in round robin fashion i.e. first come, first serve manner. This process of assigning time to threads is known as time-slicing. However if we want a thread to run before other thread of same priority then we can do so by using the yield ( ) method.

Running State: Running means that the processor has given its time to the thread for its execution. The thread runs until it loss control on its own or it is preempted by a higher priority thread. A running thread may loss its control in one of the following situations.

1. It has been suspended using suspend ( ) method. A suspend thread can be revived by using the resume ( ) method. This approach is useful when we want to suspend a thread for some time due to certain reason, but do not want to kill it.

2. It has been made to sleep. We can put a thread to sleep for a specified time period using the method sleep (time) where time is in milliseconds (1000 milliseconds = 1 second). This means that thread is out of the queue during this time period. The thread re-enter in runnable state as soon as this time period is over.

New born

Runnable state

Dead state

Page 146: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

3. It has been told to wait until some event occurs. This is done using the wait ( ) method. The thread can be scheduled to run again using the notify ( ) method.

Blocked State: A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. This happens when the thread is suspended, sleeping or waiting in order to satisfy certain requirements. A blocked thread is considered not runnable but not dead and therefore fully qualified to run again.Dead State: Every thread has a life cycle. A running thread ends its life when it has completed executing its run ( ) method. It is natural death. However, we can kill it by sending the stop message to it at any state thus causing a premature death to it. A thread can be killed as soon as it born or while it is running or even when it is in not runnable condition.Stopping a thread: whenever we want to stop a thread from running further, we may do so by calling its stop ( ) method. The stop method may be used when the premature death of a thread is desired. A thread will also move to the dead state automatically when it reaches the end of its method.Use of different methods of Thread classimport java.lang.Thread;class a extends Thread{int i; public void run() { for(i=1;i<=5;i++) { if(i==1) yield(); System.out.println("\t from thread a ="+i); } System.out.println("exit from a "); }}class b extends Thread{ public void run() { for(int i=1;i<=5;i++) { System.out.println("\t from thread b: ="+i); if(i==3) stop(); } System.out.println("exit from b"); }}class c extends Thread{ public void run() { for(int i=1;i<=5;i++) { System.out.println("\t from Thread c ="+i); if(i==1) { try { sleep(1000); } catch(Exception e) { } }

Page 147: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

} }}

class threadmathod{ public static void main(String args[]) { a obj1=new a(); b obj2=new b(); c obj3=new c();

System.out.println("Start thread a "); obj1.start();

System.out.println("Start thread b "); obj2.start();

System.out.println("Start thread c "); obj3.start();

System.out.println("End of main "); }}

isAlive ( ) and join ( ) methods: The isAlive method is used to check whether a thread has finished execution or not. It returns true if the thread on which it is called is still running else it returns false. It has the following prototype:final Boolean isAlive ( )

join ( ) method: The join method waits for the thread, on which it is called, to terminated. A maximum amount of time for waiting can be specified as an argument. if zero milliseconds or no argument is specified, it means that you want to wait forever for the target thread to terminate. In such a case use the following prototype.Final void join ( ) throws InterruptedException

/**********use of isAlive and join and check method**/class printthread extends Thread{ public printthread(String threadname) { this.setName(threadname); }

public void run() { System.out.println(getName()+" is going to sleep "); try { sleep(2000); }catch(InterruptedException e) { System.out.println(getName()+" is intrrupted "); } System.out.println(getName()+" has done with sleeping ");

Page 148: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}

public void check() { if(isAlive()) System.out.println(getName()+" is alive"); else System.out.println(getName()+" is not alive"); } public static void main(String args[]) { printthread t1,t2,t3; t1=new printthread("Thread 1 "); t2=new printthread("Thread 2 "); t3=new printthread("Thread 3 ");

System.out.println("Starting Threads "); t1.start(); t2.start(); t3.start(); t1.check(); t2.check(); t3.check(); System.out.println("Threads started "); try { t1.join(); t2.join(); t3.join(); }catch(InterruptedException e) { System.out.println("join () is interrupted "); } t1.check(); t2.check(); t3.check(); System.out.println("Thread died "); }}

Suspend ( ) and resume ( ) methods: suspend and resume methods are starts to pause and restart thread execution, respectively. The stop method stops the execution of the thread on which it is called. Once a thread is stopped, using stop, it can be restarted using the resume method.

Example:/*********suspend and resume method*******/class threadprint extends Thread{ threadprint(String threadname) { this.setName(threadname); }

public void run() {

Page 149: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println(getName()+" is going to sleep "); try { sleep(2000); }catch(InterruptedException e) { System.out.println(getName()+" is interrupted "); } System.out.println(getName()+" has done with sleeping"); }}class suspend_resume{public static void main(String args[]){threadprint t1,t2,t3;t1=new threadprint("Thread 1");t2=new threadprint("Thread 2");

System.out.println("starting thrads");t1.start();t2.start();

System.out.println("Thread started ");System.out.println("suspending thread 1");t1.suspend();System.out.println("suspending thread 2");t2.suspend();System.out.println("restarting thread 1");t1.resume();System.out.println("restarting thread 2");t2.resume();}}

/***********suspending, Resuming and stopping threads *************/class newthread implements Runnable{String name;Thread t;boolean flag;

newthread(String threadname) { name=threadname; t=new Thread(this,name); System.out.println("new thread "+t); flag=false; t.start(); } public void run() { try { for(int i=15;i>0;i--) { System.out.println(name+" : "+i);

Page 150: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Thread.sleep(200); synchronized(this) { while(flag) { wait(); } } } }catch(InterruptedException e) { System.out.println(name+" existing "); } } void mysuspend() { flag=true; } synchronized void myresume() { flag=false; notify(); }}

class suspendresume{public static void main(String args[]){newthread ob1=new newthread("one");newthread ob2=new newthread("two"); try { Thread.sleep(1000); ob1.mysuspend(); System.out.println("suspeding thread one "); Thread.sleep(1000); ob1.myresume(); System.out.println("Resuming thread one "); ob2.mysuspend(); System.out.println("suspending thread two"); Thread.sleep(1000); ob2.myresume(); System.out.println("Resuming thread two "); }catch(InterruptedException e) { System.out.println("Main thread Interrupted "); } try { System.out.println("Waiting for threads to finish "); ob1.t.join(); ob2.t.join(); }catch(InterruptedException e) { System.out.println("Main thread interrupted ");

Page 151: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

} System.out.println("Main thread existing "); }}

The Main Thread: When java program starts up, one thread begins running immediately. This is usually called the main thread of the program, because it is the one that is executed when your program begins. The main thread is important for two reasons:

1. It is the thread from which other “child” threads begin.2. Often it must be the last thread to finish execution because it performs various shutdown actions.

We can obtain reference to main thread by calling the method currentThread(), which is public static member of Thread. This method returns a reference to the thread in which it is called.Example:/**********main thread example****/class mainthread{public static void main(String args[]){Thread t=Thread.currentThread();System.out.println("Current thread :"+t);t.setName("My Thread ");System.out.println("After name change :"+t); try { for(int n=5;n>0;n--) { System.out.println(n); Thread.sleep(1000); } }catch(InterruptedException e) { System.out.println("Main thread interrupted "); }}}

Output: Thread [main,5,main].Here first main is the name of thread, 5 is the priority of thread which is normal priority, last main is the group of threads to which our thread belongs

Thread Priorities: Every java thread is assigned a priority ranging from 1 (Thread.MIN_PRIORITY) to 10 (THREAD.MAX_PRIORITY). We can set and get the priority of threads using the following methods:

setPriority (int level)-> this method sets the priority of the thread on which this method is invoked to level.

int getPriority ()-> this method return the priority of the thread on which this method is invoked.

If we don’t set priority of a thread, the thread is given a default priority level 5 (Thread.NORM_PRIORITY) which is the normal level of priority.

Depending on the priority level, the system runs the thread with the highest priority. A low priority thread in running state may be removed from execution in order to allow a higher priority thread to run immediately. Only when the high priority thread completes execution do the low priority threads get a chance to run. Threads having same priority are executed in a time-sliced manner. Each thread is assign a time interval (time slice) during which it can execute. After the completion of the time slice, even if that thread has not finished execution, the processor is taken away from that thread and given to the next thread of equal priority.

/*****************Thread Priority**********/import java.lang.Thread;class thread1 extends Thread{ public void run()

Page 152: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{ System.out.println("This is thread1 class"); }}class thread2 extends Thread{ public void run() { System.out.println("this is thread2 class "); }}public class thread4{public static void main(String s[]){ thread1 t1=new thread1(); thread2 t2=new thread2();

t1.setPriority(Thread.MAX_PRIORITY); t2.setPriority(Thread.MIN_PRIORITY);

t1.run(); t2.run();}}

/***************Thread priority**********/import java.lang.Thread;class A extends Thread{ public void run() { System.out.println("Thread A started "); for(int i=1;i<=4;i++) { System.out.println("\t form Thread A : = "+i); } System.out.println("Exit from A "); }}

class B extends Thread{ public void run() { System.out.println("Thread B started "); for(int j=1;j<=4;j++) { System.out.println("\t from Thread B : = "+j); } System.out.println("Exit from B "); }}class c extends Thread

Page 153: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{ public void run() { System.out.println("thread c started "); for(int k=1;k<=4;k++) { System.out.println("\t from Thread c : k= "+k); } System.out.println("Exit from Thread c "); }}class threadpriority{public static void main(String args[]){A obj1=new A();B obj2=new B();c obj3=new c();

obj3.setPriority(Thread.MAX_PRIORITY);obj2.setPriority(obj2.getPriority()+1);obj1.setPriority(Thread.MIN_PRIORITY);

System.out.println("Start thread A ");obj1.start();

System.out.println("Start thread B ");obj2.start();

System.out.println("Start thread c");obj3.start();System.out.println("End of Main Thread ");}}

/********************thread priority demo**********************/class threadcounter extends Thread{int i; public void run() { for(i=1;;i++); }

public static void main(String args[]) { threadcounter hi=new threadcounter(); hi.setPriority(Thread.MAX_PRIORITY);

threadcounter lo=new threadcounter(); lo.setPriority(4);

lo.start(); try { Thread.sleep(2000);

Page 154: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}catch(InterruptedException e){}

hi.start(); lo.stop(); hi.stop();

try { hi.join(); lo.join(); }catch(InterruptedException e) { System.out.println("Join interrupted"); } System.out.println("value of i in high priority thread is "+hi.i); System.out.println("value of i in low priority thread is "+lo.i); }}

Synchronization: When two or more threads are running concurrently, they may require access to the same resource. Therefore, there must be some mechanism to ensure that only one thread gets access to a resource at a time. This is known as synchronization.

Synchronization can be achieved by way of an object called monitor or semaphore. A monitor is an object that is used as a mutually exclusive lock or mutex. A data item (resource) can be locked by a thread in order to prevent this data item from being accessed and updated by any other thread. When a thread acquires a lock, it is said to have entered the monitor. Only one thread can own a monitor at a given time. All other threads that wish to enter this monitor will have to wait till this owner thread exits the monitor.

The code which you want to be accessed by only one thread at a time is placed inside a synchronized block or in a synchronized method.

For example consider the below given program. In this the variable i is static. That is, all the threads (t1, t2 and t3) will be working on the same copy of i. the program is intended to print the pattern 3 12 4 2 3 5 3 4 6 4 5 7 5 6 7 9 7 8 10. We want thread t1 to calculate i=i+2 and print the value of i, thread t2 to calculate i=i-2 and print the value of i and thread t3 to calculate i=i+1 and print the value of i. the program runs till i becomes equal to 10.

Note that the pattern in the output is not what we had expected. This occurred because the sleep ( ) method allowed other threads to access and change the value of i before the previous thread could print its value. This caused the haphazard result. Program:class pattern extends Thread{static int i=1;char operator;int value;

pattern(char op, int val) { operator=op; value=val; start(); }

public void run() { while(i<10)

Page 155: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{ switch(operator) { case '+': i=i+value; break; case '-': i=i-value; break; } /* try { sleep(2000); }catch(InterruptedException e){}*/ System.out.print(pattern.i+" "); } } public static void main(String args[]) { pattern t1=new pattern('+',2); pattern t2=new pattern('-',2); pattern t3=new pattern('+',1); }}

Output: 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 10 10 10

To fix this problem we have to serialize the access to it. that is, we have to make sure that its value is changed and printed by only one thread at a time. This can be done by making run ( ) a synchronized method. This prevents other threads from entering run ( ) while another thread is using it.

Every object with synchronized methods is a monitor. The monitor allows only one thread at a time to execute a synchronized method on the object. If there is several synchronized method, only one synchronized method may be active on an object at one time. All other threads attempting to invoke synchronized methods must wait. When a synchronized method finishes execution, the lock on the object is released and the monitor let another highest priority thread to invoke the synchronized method.

A thread executing a synchronized method may decide that it does not want to proceed and can call the wait ( ) method. This removes the thread from the monitor and other thread can try to enter the monitor. Also when a thread executing a synchronized method completes, it can notify the waiting threads of this so that they can try to obtain the lock on the monitor object again and execute. This is done by calling notify ( ). if a thread call notifyAll ( ) then all threads waiting for the object become eligible to reenter the monitor, but only one of them can obtain the lock on the object at a time.

Monitor objects maintain a list of all threads waiting to enter the monitor object to execute synchronize methods. A thread is inserted in the list if it calls a synchronized method of that object while another thread is already executing a synchronized method of that object. A thread is also inserted in the list if the thread calls wait ( ) while operating inside the monitor. The synchronized program is below but the result produced by it is still not what we required.

Program:class pattern extends Thread{static int i=1;char operator;int value; pattern(char op, int val) {

Page 156: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

operator=op; value=val; }synchronized public void run() { while(i<10) { switch(operator) { case '+': i=i+value; break; case '-': i=i-value; break; } System.out.print(pattern.i+" "); } } public static void main(String args[]) { pattern t1=new pattern('+',2); pattern t2=new pattern('-',2); pattern t3=new pattern('+',1); t1.start(); t2.start(); t3.start(); }}Output: 3 1 2 0 1 2 3 4 5 6 7 5 7 3 1 -1 -3 -5 -3 -2 0 1 3 4 5 6 7 8 9 10We are not getting expected result yet; this is because using synchronization only ensures that once a thread enters a synchronized block no other thread can execute that block. However, we cannot determine which thread will get hold of the monitor at a time. That is, we cannot say for sure that t2 will execute only after t1 and before t3. This is unpredictable since each thread is an independent until and can execute at any time. The answer lies in using the wait ( ) and notify ( ) methods. Where one thread executes only when notified by the other and waits for the other thread to complete. We can see the correct result by the next program in section Inter Thread Communication----------

Inter Thread Communication: The wait ( ), notify ( ) and notifyAll ( ) methods are used for communication among threads. The wait method causes the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify ( ). Whereas the notify method calls the first thread that called wait ( ) on the same object, notifyAll method wakes up all the threads that called wait ( ). In the latter case the thread with the highest priority will run first. Program:class patterns extends Thread{static int i=1;char operator;int value;static boolean add2value=true;static boolean add1value=false;static boolean subvalue=false;

patterns(char op, int val) { operator =op; value=val;

Page 157: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}

public void run() { try { calc(); }catch(InterruptedException e){} } synchronized public void calc() throws InterruptedException { while(i<10) { switch(operator) { case '+': if((value==1) && (add1value)) { i=i+value; System.out.print(patterns.i+" "); add1value=false; add2value=true; notifyAll(); } else if((value==2) && (add2value)) { i=i+value; System.out.print(patterns.i+" "); add2value=false; subvalue=true; notifyAll(); } else wait(10); break;

case '-': if(subvalue) { i=i-value; System.out.print(patterns.i+" "); subvalue=false; add1value=true; notifyAll(); } else wait(10); break; } } } public static void main(String args[]) throws Exception { patterns t1=new patterns('+',2);

Page 158: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

patterns t2=new patterns('-',2); patterns t3=new patterns('+',1); t3.start(); t2.start(); t1.start(); }}Output: 3 1 2 4 2 3 5 3 4 6 4 5 7 5 6 8 6 7 9 7 8 10

Q. Using thread creates a digital clock that will display the date and time continuously.import java.util.*;class threadclass extends Thread{Date d; threadclass() { d=new Date(); } public void run() { while(true) { System.out.println(d.toString()); try { this.sleep(10000); }catch(Exception e){} } }}class test{public static void main(String args[]){Thread t=new threadclass();t.start();}}/**********************1************************/class threadclass extends Thread{Thread t; threadclass(String s) { t=new Thread(this, s); t.start(); } public void run() { for(int i=0;i<10;i++) System.out.println(t.getName()); }}class test1{public static void main(String args[]){threadclass t1=new threadclass("thread1");threadclass t2=new threadclass("thread2"); }}

Page 159: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

/*********************2************************class threadclass extends Thread{Thread t; threadclass(String s) { t=new Thread(this, s); t.start(); } public synchronized void run() { for(int i=0;i<10;i++) System.out.println(t.getName()); }}class test2{public static void main(String args[]){threadclass t1=new threadclass("thread1");threadclass t2=new threadclass("thread2");}}/******************3**********************/class threadclass extends Thread{Thread t; threadclass(String s) { t=new Thread(this, s); t.start(); } public void run() { for(int i=0;i<10;i++) System.out.println(t.getName()); yield(); }}class test3{public static void main(String args[]){threadclass t1=new threadclass("thread1");threadclass t2=new threadclass("thread2");}}

Implementing the Runnable Interface: We can create thread by implementing Runnable interface. The runnable interface declares the run ( ) method that is required for implementing threads in our program. Example /*************implementing runnable interface**/import java.lang.Thread;class x implements Runnable{ public void run() { for(int i=0;++i<=10;)

Page 160: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{ System.out.println("\t"+i); } }}class runnabletest{ public static void main(String arsg[]) { x obj =new x(); Thread t=new Thread(obj); t.start(); }}

Example/*********multiple thread**********/import java.lang.Thread;class multi1 extends Thread{ public void run() { for(int i=1;i<=5;i++) { System.out.println("valu of i = "+i); } } }class multi2 implements Runnable{ public void run() { for(int j=1;j<=5;j++) {

try { System.out.println("\t\t"+j); } catch(Exception e){} } } }class runthread{ public static void main(String args[]) { multi1 m1=new multi1(); m1.start(); multi2 obj1 =new multi2(); Thread m2=new Thread(obj1); m2.start(); // new Thread(new multi2()).start(); }}

Deadlock: Deadlock is a special type error. It occurs when two threads have a circular dependency on a pair of synchronized objects. For example suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will block as expected. However if the thread in Y in turn tries to call any synchronized method on X then thread waits forever, because to access X it would have to release its own lock on Y so that the first thread could complete. Deadlock mainly occurs only in two situations.

i. When two thread time slice is in just the right way.ii. It may involve more than two threads and two synchronized objects.

Example:/***************deadlock creation************************/ class A{ synchronized void foo(B b) { String name=Thread.currentThread().getName(); System.out.println(name+" entered A.foo"); try {

Page 161: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Thread.sleep(1000); }catch(Exception e) { System.out.println("A Interrupted "); } System.out.println(name+" trying to call B.last()"); b.last(); } synchronized void last() { System.out.println("Inside A.last"); }}class B{ synchronized void bar(A a) { String name=Thread.currentThread().getName(); System.out.println(name+" entered B.bar"); try { Thread.sleep(1000); }catch(Exception e) { System.out.println("B Interrupted"); } System.out.println(name+" trying to call A.last()"); a.last(); }

synchronized void last() { System.out.println("Inside A.last "); }}class Deadlock implements Runnable{A obj1=new A();B obj2=new B();

Deadlock() { Thread.currentThread().setName("Main Thread "); Thread t=new Thread(this, "Racing Thread"); t.start();

obj1.foo(obj2); System.out.println("Back in main thread "); }

public void run() { obj2.bar(obj1); System.out.println("Back in other thread"); }

Page 162: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

public static void main(String args[]) { new Deadlock(); }}Note: (This program will not over, because it is deadlock condition so we have to press CTR+C to terminate the program.)

Managing Input / Output files in java (File Handling)

File: A file is a collection of related records placed in a particular area on the disk. A record is composed of several fields. And a field is a group of characters. Characters in java are Unicode characters composed of two bytes. Each byte containing eight binary digits (bits), 1 or 0. The file handling in Java can be broadly categorized in two types:

1. High Level (standards files or stream oriented files)2. Low Level(System oriented files)

High level file handling is managed by library functions while low level file handling is managed by system calls. The stream classes should be included in the program to make use of the I/O functions. Like PrintWriter() , BufferedWriter. Files are of two types:

We can store data in secondary storage devices such as floppy disks or hard disks. The data is stored in these devices using the concepts of files. Data stored in these file is called persistent data.

Files are of two types: 1. Character files or text files-> The files that store characters as per a specific character encoding

scheme (Unicode in java)2. Binary file-> The files that store data in machine readable form.

Buffering: A Buffer is a temporary storage used to hold data until enough has been collected that it is worth transferring. Buffering can be used for both input and output. An input buffer is used for reading a large chunk of data from a stream. The buffer is then accessed as needed and when emptied, another chunk of data is read from the stream into buffer. An output buffer is used to store up data to be written to a stream. Once the buffer is full, the data is sent to the stream all at once and the buffer is emptied to receive more data.

Flush: if we want to force buffer to write data as soon as possible which is in it, to the file then we use flush operation. The BufferedInputStream and BufferedOutputStream filters may be used to add buffering to any byte oriented stream. The BufferedReader and BufferedWriter filters may be used to add buffering to any character oriented stream.

File Processing: Storing and managing data using file is known as file processing which includes tasks such as creating files, updating files and manipulation of data. Reading and writing data in a file can be done at the level of bytes or characters or fields depending on the requirements of a particular application.

Stream: A stream in java is a path along which data flows like a river or a pipe along with water flows. It has a source of data and a destination for that data. Both the source and the destination may be physical devices or programs or other streams in the same program. Java streams are classified into two types namely

Page 163: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

input stream and output stream. An input stream read data from source file and sends it to the program. Similarly and output stream takes data from the program and sends i.e. writes it to the destination file. Stream classes: The java.io package contains a large number of stream classes that provide capabilities for processing all types of data. These classes may be categorized into two groups based on the data type on which they operate.

1. Byte stream classes that provide support for handling I/O operations on bytes.2. Character stream classes that provides support for managing I/O operations on characters.

These stream classes further can be classified based on their purpose.

Byte Stream Classes: Byte stream classes have designed to provide functional features for creating and manipulating stream and file for reading and writing bytes. Since the streams are unidirectional, they can transmit bytes in only one direction and therefore java provides two kinds of byte stream classes. Input stream classes and output stream classes.Input Stream Classes: Input Stream classes that are used to read 8-bit include a super class known as InputStream and a number of subclasses for supporting various input-related functions. The super class InputStream is an abstract class, and therefore we cannot create instance of this class. Rather we must use the subclasses that inherit from this class. The InputStream class defines methods for performing input function such as

1. Reading bytes.2. Closing streams3. Making positions in streams4. Skipping ahead in a stream5. Finding the number of bytes in a stream.

Methods of InputStream class.read() Reads a byte from the input streamread(byte b[]) Reads an array of bytes into bread(byte b[], int n, int m) Reds m bytes into b starting from nth byte.available() Gives number of bytes available in the inputskip(n) Skips over n bytes from the input streamreset() goes back to beginning of streamclose() Closes the input stream.

Output Steam classes: Output stream classes are derived from the base class OutputStream. Output stream class is also an abstract class. The output stream class includes methods that are designed to perform operations like, writing bytes, closing streams, and flushing streams.write() Writes a byte to the output streamwrite(byte [] b) Writes all bytes in the array b to the output streamwrite(byte b[], int n, int m) Writes m bytes from array b starting from mth byteclose() Closes the output streamflush() Flushes the output stream

Character stream Classes: This class can be used to read and write 16-bit Unicode characters. Like byte streams, there are two kinds of character stream classes, namely reader stream classes and writer stream classes.

Reader Stream Classes: These classes are designed to read characters from files. Reader class is the base class for all other classes in this group. These classes as functionally very similar to the input stream classes, except input streams use bytes as their fundamental unit of information, while reader streams use characters. The Reader class contain methods that are identical to those available in the inputstream class.

Page 164: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

Writer Stream Classes: These classes are designed to perform output operations on files. These classes are designed to write characters to a file. The Writer class is an abstract class which acts as base class for all the other writer stream classes. This base class provides support for all output operations by defining methods that are identical to those in OutputStream class.

File Class: The java.io package includes a class known as the File class that provides support for creating files and directories. This class also contains several methods for supporting the operations such as.

1. Creating a file2. Opening a file3. Closing a file4. Deleting a file5. Getting the name of file6. Getting the size of a file.7. Checking the existence of a file8. Renaming a file.9. Checking whether the file is writable10. Checking whether the file is readable

Creation of Files: A filename is a unique string of characters that helps identify a file on the disk. The length of a filename and characters allowed on the OS on which the java program is executed. A file name may contain two parts, a primary name and an optional period with extension. For example:Input.data, test.doc, student.txt , salary etc.Data type is important to decide the type of file stream classes to be used for handling the data. We should decide whether the data to be handled is in the form of characters, bytes or primitive type. The purpose of using a file must also be decided before using it. For example, we should know whether the file is created for reading only, or writing only or both the operation. Syntax : File f=new File(“Student.txt”);Here student is the file name and txt is the extension of this file.

Output (Writing) to a text file: The steps of writing to a file are as follow:1. Create a FileWriter stream type object as per following syntax:

FileWriter fout=new FileWriter(“Name.txt”);

2. Link the FileWriter object with BufferedWriter object as per following syntax.BufferedWriter bw=new BufferedWriter(fout);This object creates a buffer for the stream created with FileWriter.

3. Now link the BufferedWriter object with PrintWriter object.PrintWriter pw=new PrintWriter(bw);The print writer object is responsible for writing characters on to the text file you linked with FileWriter object.

4. Now write any characters or text from your program with PrintWriter object using either print or println methods.pw.print(“This is a “);pw.print(“test file”);

5. At last close the stream chain by using close() with all stream objects.pw.close();bw.close();fout.close();

Example: /***************writing data to a file directly ***/import java.io.*;class IO

Page 165: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{public static void main(String args[]) throws IOException{FileWriter fw=new FileWriter("Student.txt");BufferedWriter bw=new BufferedWriter(fw);PrintWriter pw=new PrintWriter(bw);pw.println("Arif");pw.println("asif");pw.close();}}

/***************writing data to a file from key board ***/import java.io.*;class IObykeyboard{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);String name;int rollno;FileWriter fw=new FileWriter("Student.txt");BufferedWriter bw=new BufferedWriter(fw);PrintWriter pw=new PrintWriter(bw);System.out.println("Enter name of the student ");name=in.readLine();System.out.println("Enter rollno of the student ");rollno=Integer.parseInt(in.readLine());pw.println(name);pw.println(rollno);pw.close();}}

/***************writing data to a file by command line argument*******/import java.io.*;class IObycommandline{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);String name;int rollno;

FileWriter fw=new FileWriter("Student.txt");BufferedWriter bw=new BufferedWriter(fw);PrintWriter pw=new PrintWriter(bw);

for(int i=0;i<args.length;i++)pw.println(args[i]);

pw.close();}}

Input (Reading) from a text file: To read from a text file we have to follow the following steps.1. Create a FileReader stream object.

Page 166: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

FileReader fr=new FileReader(“Student.txt”);This object creates an input stream using the default encoding shceme.

2. Now link the FileReader object with BufferedReader object as per following syntax.BufferedReader br=new BufferedReader(fr);This object creates a buffer for the stream created with FileReader.

3. New read text using the readLine() method from the BufferedReader object and store in a string object.String str=br.readLine();

4. Use the read text in the program as required.

5. Close the file.Br.close();

Note: When you use readLine() with a BufferedReader. If no more data is found, a null is returned. Thus we can check it by this technique.While((str=br.readLine())!=null){…………statements;}

Example: /*************Reading data from a file ****/import java.io.*;class Reading{public static void main(String args[]) throws IOException{FileReader fr=new FileReader("Student.txt");BufferedReader br=new BufferedReader(fr);String str;while((str=br.readLine())!=null)System.out.println(str);br.close();}}

Appending to a text file: if we want to retain the old contents and append the new contents, then we need to create FlieWriter object just like this.FileWriter fw=new FileWriter(“Student.txt”, true);This means that new data will be appended to file. But if you write false of skip over this part of argument data will be overwritten.

Example: /**********appending to a text file****/import java.io.*;class append{public static void main(String args[]) throws IOException{BufferedReader in=new BufferedReader(new InputStreamReader(System.in));FileWriter fw=new FileWriter("Student.txt",true);BufferedWriter bw=new BufferedWriter(fw);PrintWriter pw=new PrintWriter(bw);String name;

Page 167: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

int rollno;for(int i=1;i<=5;i++){System.out.println("Enter name and Rollno ");name=in.readLine();rollno=Integer.parseInt(in.readLine());pw.println(name);pw.println(rollno);}pw.close();bw.close();fw.close();}}

Copying one file into another/*appending (copying) the contents of one (source) file to another (destination). file*/import java.io.*;class copyfile{public static void main(String args[]) throws IOException{String str;BufferedReader br=new BufferedReader(new FileReader("Student.txt")); //source file PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter("Teacher.txt",true))); //destination file

while((str=br.readLine())!=null) pw.println(str); //reading from newly copied file

pw.close(); br.close(); }}/***********counting characters from a file **/import java.io.*;class countcharacter{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new FileReader("Student.txt"));String str;int count=0;while((str=br.readLine())!=null){count+=str.length();}br.close();System.out.println("The total number of character in Student file is "+count);}}

/*concatenation of two files*/import java.io.*;class sequencebuffer{

Page 168: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

public static void main(String args[]) throws IOException{FileInputStream file1= new FileInputStream("file1.dat");FileInputStream file2= new FileInputStream("file2.dat");

SequenceInputStream file3= new SequenceInputStream(file1, file2);

BufferedInputStream inbuffer = new BufferedInputStream(file3);BufferedOutputStream outbuffer = new BufferedOutputStream(System.out);

int ch;while((ch=inbuffer.read())!=-1){outbuffer.write((char) ch);}inbuffer.close();outbuffer.close();file1.close();file2.close();}}

Byte file or binary file/**************writing bytes to a file ********/import java.io.*;class writebytes{public static void main(String args[]) throws IOException{byte cities[]={'d',’e’,'l','h','i','\n','m','a','d','r','a','s','\n','l','o','n','d','o','n','\n'};FileOutputStream outfile=new FileOutputStream("city.txt");outfile.write(cities);outfile.close();}}

/*************Reading bytes from a file *****/import java.io.*;class readbytes{public static void main(String args[]) throws IOException{int b;FileInputStream infile=new FileInputStream("city.txt");

while((b=infile.read())!=-1)System.out.print((char)b);

infile.close();}}

/**********copying bytes from one file to another ********/

Page 169: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

import java.io.*;class copybytes{public static void main(String args[]) throws IOException{byte b;

FileInputStream infile=new FileInputStream("city.txt");FileOutputStream outfile=new FileOutputStream("state.txt");do{b=(byte)infile.read();outfile.write(b);}while(b!=-1);infile.close();outfile.close();}}

/***********Reading and writing bytes to a file simultaneously **/import java.io.*;class readwrite{public static void main(String args[]) throws IOException{File infile=new File("counting.dat");

DataOutputStream dos=new DataOutputStream(new FileOutputStream(infile));for(int i=1;i<=20;i++)dos.writeInt((int)(1*i));dos.close();

DataInputStream dis=new DataInputStream(new FileInputStream(infile));for(int i=1;i<=20;i++){int n=dis.readInt();System.out.println(n+" ");}dis.close();}}

/********Reading/Writing using a random access file ********/import java.io.*;class random{public static void main(String args[]) throws IOException{RandomAccessFile file=new RandomAccessFile("rand.dat","rw"); //rw for both reading and writingfile.writeChar('x');file.writeInt(555);file.writeDouble(3.1234);

file.seek(0); //go to beginning of file

System.out.println(file.readChar());System.out.println(file.readInt());

Page 170: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println(file.readDouble());file.seek(2); //go to second itemSystem.out.println(file.readInt());file.seek(file.length());file.writeBoolean(false);file.seek(4); //go to fourth itemSystem.out.println(file.readBoolean());file.close();}}

/*concatenating and buffering files*/import java.io.*;class sequencebuffer{public static void main(String args[]) throws IOException{FileInputStream file1= new FileInputStream("text1.dat");FileInputStream file2= new FileInputStream("text2.dat");

SequenceInputStream file3= new SequenceInputStream(file1, file2);

BufferedInputStream inbuffer = new BufferedInputStream(file3);BufferedOutputStream outbuffer = new BufferedOutputStream(System.in);

int ch;while((ch=inbuffer.read())!=-1){outbuffer.write((char) ch);}inbuffer.close();outbuffer.close();file1.close();file2.close();}}

What is white space?White space is a term that includes the spaces, tabs and newline characters that separate words and symbols in a program. The compiler ignores extra white spaces. Therefore it does not affect execution. However, it is crucial to use white spaces appropriately to make a program readable to humans.

String Tokenizer: StringTokenizer class is found in the java.util package. This contains number of useful methods that can be used to isolate tokens. To use these methods we must offcourse first create an instance of the class StringTokenizer as shown below:

StringTokenizer data=new StringTokenizer(string);

Where string is a text string. The StringTokenizer class also provides two methods that are immediately useful for processing strings.

1. countTokens: This method returns the number of tokens that are delimited by any white space in a given string, thus we know how many tokens there are and therefore can use this number as a loop parameter with which to process the string.

Page 171: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

2. nextToken: This method returns the next token in a string from the current token. When used for the first time the next token is the first token in the string. Thus this method can be used to pass along the string token by token.

Example: /*program to illustrate usage of methods inside string Tokenizer class**/import java.io.*;import java.util.*;class tokenizer{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int token=0;System.out.println("Input a string ");StringTokenizer str=new StringTokenizer(br.readLine());token=str.countTokens();System.out.println("Number of Tokens ="+token+"\n");for(int i=0;i<token;i++)System.out.println(str.nextToken());}}

/**program to use StringTokenizer class for a sequence delimited by comma**//**program to use StringTokenizer class for a sequence delimited by comma**/import java.io.*;import java.util.*;class tokenizer2{public static void main(String args[]) throws IOException{DataInputStream in=new DataInputStream(System.in);int token=0;int total=0;System.out.println("Input a sequence of integers seprated by comma (,) ");StringTokenizer str=new StringTokenizer(in.readLine(),",");

token=str.countTokens();System.out.println("Number of tokens in this string is "+token);

/*int arr[]=new int[token];for(int i=0;i<arr.length;i++){arr[i]=new Integer(str.nextToken()).intValue();System.out.println(arr[i]);total+=arr[i];}*/

for(int i=0;i<token;i++){int num=new Integer(str.nextToken()).intValue();//or//int num=Integer.parseInt(str.nextToken());System.out.println(num);total=total+num;}

Page 172: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

System.out.println("Total of number= "+total);}}

String Tokenizer and File Handling: We can also use the StringTokenizer to process input from a file line by line.

/***program to use string tokenizer with a text file ***/import java.io.*;import java.util.*;class tokenizer3{public static void main(String args[]) throws IOException{FileReader fr=new FileReader("Student.txt");BufferedReader br=new BufferedReader(fr);String str;int i=0;int token=0;while((str=br.readLine())!=null){StringTokenizer st=new StringTokenizer(str);token+=st.countTokens();}System.out.println("Number of tokens = "+token);br.close();}}

Stream Tokenizer: A stream tokenizer takes as input stream and passes it into tokens, allowing the tokens to be read one at a time.

/***program to illustrate usage of stream tokenizer class****/import java.io.*;import java.util.*;class tokenizer4{public static void main(String args[]) throws IOException{FileReader fr=new FileReader("Student.txt");StreamTokenizer str=new StreamTokenizer(fr);

int token=-1;int tokentype=0;do{tokentype=str.nextToken();token++;}while(tokentype!=StreamTokenizer.TT_EOF);System.out.println("Number of tokens = "+token);}}

/**write a program to count the number of words, and lines in the file**/import java.io.*;

Page 173: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

import java.util.StringTokenizer;class Tokenizer5{public static void main(String args[]) throws IOException{BufferedReader br=new BufferedReader(new FileReader("Student.txt"));String str;int charcount=0, wcount=0, linecount=0;

while((str=br.readLine())!=null){charcount+=str.length();StringTokenizer st=new StringTokenizer(str);wcount+=st.countTokens();linecount++;}br.close();System.out.println("The total number of character is "+charcount);System.out.println("The total number of words is "+wcount);System.out.println("The total number of Lines is "+linecount);}}

/***convert January 26 is celebrated as the republic day of india**/import java.util.*;class convert{public static void main(String args[]) {String str="January 26 is celebrated as the Republic Day of India";String str2=" ", word=" ";int token=0;StringTokenizer st=new StringTokenizer(str);token=st.countTokens();for(int i=0;i<token;i++){word=st.nextToken();if(word.equals("January"))word="Agust";else if(word.equals("26"))word="15";else if(word.equals("Republic"))word="Independence";str2=str2+word+" ";}System.out.println("The changed string is:\n"+str2);}}

Page 174: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

AssertThe concept of Design by Contract (DBC) was first introduced in the Eiffel programming language. This technique specifies the interaction between various components of an application. The DBC technique uses assertions to check whether the application meets the requirements specified in the defined conract.

Design by contract: This technique uses three types of assertions to chek whether the software complies with the specification. The three types of assertions are:Precondition: An application must satisfy this specified condition before calling an external component.Postcondition: An application must satisfy this specified condition after execution of the external component.Invariant: The applilcation must always satisfy this specified condition.

An assertion is a statement, which contains a Boolean expression that the programmer assumes to be true./* Demonstrate assert */class AssertDemo {static int val = 3;// Return an integer.static int getnum() {return val--;}public static void main(String args[]){int n;for(int i=0; i < 10; i++){n = getnum();assert n > 0 : "n is negative";System.out.println("n is " + n);}}}Compilation and execution will be according to the picture shown below. Version will change 1.7 will change with jdk version and no need to apply 0 of version like jdk1.7.0 will be written as

Page 175: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

/*Assert demo*/public class divide{void division(int first, int second){assert second!=0: "The second value cannot be zero";double result=first/second;System.out.println("The result is "+result);}

public static void main(String args[]){divide d=new divide();d.division(10,2);}}

/*Assert demo*/public class checknegative{public void checkassert(int value){assert 0<= value: "Value must be non-negative "+value;System.out.println("OK");}

public static void main(String args[]){checknegative cn=new checknegative();System.out.println("cn.checkassert(2) : ");cn.checkassert(2);System.out.println("cn.checkassert(-2): ");cn.checkassert(-2);}}

/*Assert demo*/class superex{public void check(boolean test){assert test: "Assertion failed : test is "+test;System.out.println("OK");}

Page 176: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

}

public class sub extends superex{public void checktest(boolean test){assert test: "Assertion failed : test is "+test;System.out.println("OK");}

public static void printAssertionError(AssertionError ae){StackTraceElement []stackTraceElements=ae.getStackTrace();StackTraceElement stackTraceElement =stackTraceElements[0];System.err.println("AssertionError");System.err.println("Class = "+stackTraceElement.getClassName());System.err.println("Method = "+stackTraceElement.getMethodName());System.err.println("Message = "+ae.getMessage());}

public static void main(String []args){try{sub obj=new sub();System.out.println("obj.check(false): ");obj.check(false);System.out.println("obj.checktest(false): ");obj.checktest(false);}catch(AssertionError ae){printAssertionError(ae);}}}Run this program by following method:

/*Assert demo*/public class ErrorCheck{public static void main(String args[])

Page 177: Decision Making and Branching - Web viewthe key word public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class

{try{AssertValue();}catch(AssertionError er){er.printStackTrace();}}

public static int AssertValue(){int value=2;assert value!=2: "value given is 2";return value;}}

/*Assert demo*/class withdraw{public static void main(String args[]){System.out.println(withdrawamount(5000,1000));System.out.println(withdrawamount(2000,3000));}

public static double withdrawamount(double balance, double amount){assert balance>=amount;return balance-amount;}}