0% found this document useful (0 votes)
2K views85 pages

Java Vol 1 - Technical Publication

Uploaded by

himanshus3106
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2K views85 pages

Java Vol 1 - Technical Publication

Uploaded by

himanshus3106
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
EDITION : 2020 ee eee eat INCLUDES LABORATORY PROGRAMS Oe eae Sty Pree soe SUBIECT CODE : 22412 eporiinieed Siistue st MSBTE - | SCHEME S.Y. Diploma Semester - IV Computer Engineering Group & Information Technology (CO / CM/IF/O%) JAVA PROGRAMMING Anuradha A. Puntambekar ME. (Computer) Formerly Assistan! Professor in PES. Modern Collage of Engineering, Pune Prashant P. Sawant M.E. (Computer Engineering), HOOD (Information Technology) Pillai HOC Polytechnic, Porvel, Dist. Roigad Swati T. Ghorsad ME. (CSE), B.E. (CSE}, Diploma (CM) Lecturer, Kini Polytechnic, Amravati => TECHNICAL PUBLICATIONS | ‘suce ns An Up-Thrust for Knowledge KKK 5 o JAVA PROGRAMMING Subject Code : 22412 Second Year Diploma Semester - IV Computer Engineering Group & Information Technology (CO / CM/ IF / CW) Second Revised Edition : January 2020 © Copyright with A.A.Puntermbekor All publishing righis (orinied end ebook version} reserved with Technical Publications, No part ofthis book should be reproduced in any form, Electronic, Mechanical, Photocopy or any information storage and relriaval system without prior permission in writing, from Technical Publications, Puna Published by ) Ani Residency, Ofice Ne. 1,412, Shonver Fh ne - 411020, .. NOTA FeeHMeML oe oi -G20.2449849¢/97. Tolotex’ + 9 91-020-24495197 pvbictions.org Webel: veloc Ipvblcations.org Printer sin Pint 8 Bde S.No, 10\A, ‘Ghul nde Exae, Nerd Viloe Roe, THe Dit me - 411041 zal ISBN $78-93-332-0029-8 ul | WSBrE I 9780333900995 [2] o PREFACE The importance of Java Programming is well Bnown in various engineering tlelds Overwhelming response to our books on various subjects Inspired us to write this book. ‘The book is structured to cover the key aspects of the subject Java Programming. The book uses plain, lucid language to explain fundamentals of this subject. The book provides logical method of explaining various complicated concepts and stepwise methods to explain the important topics. Each chapter is well supported with necessary illustrations, practical examples and solved problems. All chapters in this book are arranged In a proper sequence that permits each topic 10 build upon earlier studies. All care has been taken to make students comfortable in understanding the basic concepts of this subject. Representative questions have been added at the end of each section to help the students in picking important points from that section The boob not only covers the entire scope of the subject but explains the philosophy of the subject. This makes the understanding of this subject more clear and makes it more interesting. The book will be very useful not only to the students but also to the subject teachers, The students have to omit nothing and possibly have to cover nothing more. We wish to express our profound thanks to all those who helped in making this book a reality. Much needed moral support and encouragement is provi ied on numerous occasions by our whole tamily. We wish to thank the Publisher and the entire team ot Technical Publications who have taken immense pain to get this book in time with quality printing Any suggestion for the improvement of the book will be acknowledged and well appreciated Authors AA. Pantambehar Prashant P. Sawant Swatt T. Ghersad Dedicated to Goi, SYLLABUS Java Programming (22412) Teaching] creat sania Sohne Scheme | (Lst+P) ute Theowy Pract! raver| ese | A Total ese PA Tot ie wax [in| ax | win | wax | win | mex | win [wax] min | wax | wn all 7 [2 [mlela| [iw] « [ow] ola] wo | m| uni Unit Outcomes (GOS) “Topics and Sub tples Marks {in courtive domain) 1a. Write programs to [11 Java Features andthe Java] 10 piste czeate ‘asses and | Programming Environment, Object syuntea | obpets for the given | Onented, Compiled, Tnterpreted, Counts | problem Platiorm independent, Portable, Robust fie kowe (aa, tye | and Secure, Dynamic chumcterstis of the | 2 Defining a class, creating object given Java token accessing lass members lc Explain the function of | 1.3 Java Tokens and Data types, Constants the given operator with | "and Symbolic Constants, variables, example ynamic initialization, data types, attay tie he| and sting, scope of Variable, Mas Cotas he) mein and ntidond fn implicit and explicit values type conversions’ to | LA Operators and Expressions, Arithmetic solve "the given | Operators, Relational Operators, Logical problem, Operators, Increment and Decrement, ae arse cograms | Conditional Operators Bit wise 1 OP ene Ce | Operators, Instance of Oporatos, Dot bing Televant control | Operators, Operator precedence and oes. assccialiviiy, Evaluation of Expressions, Matrematica! Functions ~ muind.rax0, srt, pow), exp), toundd, aba 13 Decision making and looping: I statement, if else statement, nested if else statement, if else if ladder, the switch statement, nested switch statement, The ? operator, The while Statement, the Do while statement, the for’ statement, break, continue | and return statement, nested loops, labeled loops, foreach version of the for loop. unt (se Coneinicios for [21 Constructs and methods, types of] 18 ates the given programairg | ometrictony: ring of tothody sratcten | problem Srpument passing, te ‘this’ Keyword, Cease |p. etentty scope ana | ctmmand "ime arguments, varangs fi Identity | soope and) Canablelengih arguments,” garbage merce Te | lesion, feta) math, he het code, oem 4 22° Visibility control public, Private 2 Descttbe the given ity . Deserbe the even |" protected default, friendly private Protected access example dL Watt the programs by [22 AtTays. and Stings: Types of arrays 20, Wee Beene eating an array, strings, string classes implemenung arrays (© nplementing arrays to) Si sting Duller, vectors," WIapper soe ee lasses, enumerated ty proble ses, en ps Develop prograse ing vate. etl rapper lasses for the given problem vit-it [3,Apply the identifed |31 Inheritance: concept of inhertance, | 12 nberitence, | 3pe_ of Inhertance for| Types of Inheritance viernes’ | the given programming [5° giree. ante 2 Single Inheritance multilevel and problem Inerance, "HlerarchiealInerltance Package 3b. Differentiate between | method “and constructor _overleading ovelloading —and| and overriding. dynamic method overriding for the given | ispatch, final variables, final methods example. use of ‘super, abstract methods and de Develup program using | dass state members, the specified inert [33 Tnerfces: Define terface, td Gee met kin implementing interface, accesing Sd. Create user | defined | interface, aisles and inethods prose be the hen mckae xtending "interlace ‘interface Pr references, nested interfaces Be. Ade class and intefee | 34 Pocuere’ Deane, peckone, wpe of te the given package peckage naming and creating packages, secessing package, import statement, static import, "adding lass and interfaces to a package. Unit-1V [aa Distinguish the ereors [4.1 Errors and Exception + Types of errors | 12 Bs and exceptions (any) | exceptions, try “and catch. statement Te in the given example nested try statement, throws and Finally “velop. program for} S2tement, buts exceptions, chained tne, Pe sven | exceptions, "creating awn exception epi (throw clause), subclasses 4 Grate dunce in |42 Muka roaming Cag 4 the given maltiple cade ming _ Frocese In the gta | and by” implementing runnable rocesies # Interface, Life eycle of thread Thread re Methods wait sleepO, notify) 46 Explain the function of | resumed, suspend®, "stop. Thread the specified phase in| exceptions, thread pricrity and methods thread life eyele using | Synchronization, intentread the given example communication, deadlock tnit-v [5a Describe the given | 5.1 Introduction to applets = Applet, Applet | 10 Java phase of applet” lie| lifecycle Gheleton), Applet tag, lappicsana | eycle using a typical | Adding Applet to HTML fle passing ence | example parameter to applet, embedding Programm | 5b. Develop programs | “SRPICD fags, in Java como, adding “ins using Spplet | controls to applets implementation for the |52 Graphics Programming: Graphics sive prablem classes ins, rectal, lips, cle ares. polygons, color and” fonts Develop. program for polygons, ; Peete selon | SetColoe), getColon), setForeGround!) implementing thes! selfiackGroundQ, font class, Variable geome Hae defined by font cass + name, pointsize 5d. Develop program for! size. syle, font methods = getFamily’) implementing the given | getFont(), _getFoniname 0, getize)) fom settings. Style), “getAllFonts) and get Svailable font family mame) of the sraphics environment clas. Unit vi [62 Use 170 stream lasses | 5.1 Introductéon ond Concept of Streams 0s ina. program to solve tama! | go. Write programe for|[63 Be Stam Chases = nt Seam mots reading "and writing | Chis, Output Sueam Chistes ava chic atreaeis haracter Stream Classes, Using : sid irom he ghen [4 Sharaer Sham Clas Using files < Write programs for [65 Using File Class : 1/0. Rxceptions er on ote Creation of Files, Reading/ Writin reading "and writing ; Dye and from We hatacters, Reading/Writing Bytes Ae Handling Primitive daa types 6c. Write program — to demonstrte use of primitive data types ‘with the specified steam, ‘otal Marks 70 TABLE OF CONTENTS Chapter-1 Basic Syntactical Constructs in Java (1 +1) to (1+ 30) 1.6 Java Tokens 1-8 wo Chapter-2 Di Seeeeee 28 29 240 2a 242 183 Lea Iss Nested ifelse Statement 1.21 Wolke Ladder 1-21 Switch Statement 186 Nested Switch Statement 187 ‘The while Statement L&8 ‘The do while Statement 189 ‘The for Statement 18.10 The Break State a 1 18.11 The continue Statement 1-2! 18.12 The retun Stat m7 1-26 1.8.13 The nested Loops 1 1.8.14 The Labeled Loops 1 1.8.15 The for-Each Ves jon of the for Loop ...1 Lisi aes ved Syntactical Constructs in Java (2-1) to (2-18) Constructors and Method 2-1 Types of Constructors Nesting of Methods .. Argument Passing The this Keyword. Command Line Arguments Varargs : Variable Length Arguments. Garbage Collection and Finalize Method The Object C! Visibility Control Anays. . se 211.1 Types of Arrays with their Creation Strings 2.12.1 Sting Classes 212.2 Sting Buffer Vector Wrapper Classes... 2 Enumerated Types aT) Il Chapter -3 Inheritance, Interface and Package (3-1) to (3-26) a4 32 33 34 35 36 37 38 39 340 aut 312 343 a4 34s 3.46 347 349 320 321 32 323 324 328 Inheritance Types of Inheritance Methed Overloading Constructor Overloading Overding Dynamic Method Dispatch Final Variables and Final Methods Use of Super Abstract Methods and Classes Static Members Part - Il; Interface Definition of Interface Implementing Interface Accessing Interface Variables and Methods Interfaces Extending Interfaces Interface References. . Nested Interfaces Part - IIT : Package Definition of Packages. Built-in Java Packages. Type of Package Naming, Creating Package Accessing Package: Import Statement Static Import Adding Class and Interfaces to Package: a1 3-1 3-3 3-6 Uni ue Chapter -4 Exception Handling 4a 42 43 4a 45 46 4 4s 49 4.10 4 412 413 44 415 416 47 48 419 Chapter-5 Java Applets and Graphics SI and Multithreading (4-1) to (4-20) Part - ‘xception Handling Errors and Exception Types of Errors Concept of Exception, try-catch Statement Nested try Statement Throws Statement Using Throw fins cement Built in Exception Chained Exception Creating Own Exception Subclasses Part - I : Multithreading Concept of Multithreading, Creating a Thread. Life Cycle of Thread Thread Exceptions ‘Thread Priority and Methods. ‘Synchronization Interthread Communication Deadlock 410 410 40 seu su 4s 4.17 aes Programming — (5-1) to (5 - 20) Java Applets [rm Concept of Applet TECHBICAL PUBLICATIONS". An up rtf noedse 38 Applet Life Cycle Applet Tag Creating Applet... Executing Applet Code 55.1 Adding Applet to HTML File 55.2. Embedding Applet Code in Java, Passing Parameter to Applet Adding Controls to Applets, Part - II : Graphics Programming | Introduction to Graphics Programming 5.8.1 Graphics Classes 582 Lines SX3_ Rectangles S84 Ellipse and Citcle 585. Ans 586 Polygons Chapter -6 Managing Input, Output Files in Java (6-1) to (6 - 40) 6.1 Introduction and Concept of Stream. 6 6.2 Streamn Classes 6 63° Byte Stream Classes 6 64 Character Stream Classes 6 6S Using File Class 63 66 VO Exception 63 67 Creation of Files 6-4 68 Reading/Writing Charscters 6-4 69 Reading) Writing Bytes 6-6 69.1 Handling Primitive Data Types. 6-9 Java Programming Laboratory (L- 1) to (L-8) Solved Medel Question Paper (M-1) to (M-2) Solved Board Question Papers {S-1) to(S - 12) TEGHCAL PUBLICATIONS". An up tas Brinomtaae a TEGHNCAL FUBLICATIONS"- An up tat i nono Ee UNIT - Basic Syntactical Constructs in Java Java Features Java is getting popular because of its features. Following is a list of buzewords that makes Java a popular Programming language. 1. Java is simple and small programming language © Java isa simple programming language. thouzh you have ne programming background you can lear this language comfortably. * The programmers who worked on C or CH can learn this language more efficiently because the syntax of Java resembles with C and CH: ‘© In fact Java is made more elear and adaptable than cH. 2. Java is robust and secure + Following are reasons that make Java more secured than other programming languages - 1. Java does not support the concept of pointers dircetly. This makes it impossible to accidentally reference memory that belongs to other programs or the kernel. ‘The output of Java compiler is not executable code but itis a bytecode. The instructions of bytecode is executed by the Java Virtual Machine (JVM). That means JVM converts the bytecode to machine readable form. JVM understand only the bytecode and therefore any infectious code can not be executed by SVM. No virus can infect bytecode, Hence itis difficult to trap the intemet and network based applications by the hackers. 3. In programming languages like C or C++ the memory management is done explicitly by the user. That means user allocates or deallocates the memory. Whereas in java its automatically done using garbage collection, ‘Thus user can not perform the memory management directly. 4, Ifan applet is executing in some browser then itis not allowed to access the file system of local machine. 3. Java is a platform independent and portable programming language * Platform independence is the most exciting feature of Java program. That means programs in Java can be executed on variety of platforms. This feature is based on the goal - write once, rum anywhere and at anytime forever: ‘+ Java supports portability in 2 ways - Java compiler zoncrates the byte code which can be further used to obtain the corresponding machine code, Secondly the primitive data types used in Java are machine independent. 4. Java is known as object oriented programming language © Java is popularly recognised as an object oriented programming language. = It supports various object oriented features such as data encapsulation, inheritance, polymorphism and dynamic binding. * Everything im Java is am object. The object oriented model of Java is simple and canbe extended easily. 5. Java is multithreaded and interactive language * Java supports mulithreaded programming which allows a programmer to write such a program that can perform many tasks simultaneously. * This ultimately helps the developer to develop more interactive code a-p 6. Java can be compiled and interpreted ‘© Normally programming languages can be either ‘compiled or interpreted but Java is a language which «can be compiled as well as interpreted ‘+ First, Java compiler translates the Java source program into a special code called bytecode, Then Java interpreter interprets this bytecode to obiain the equivalent machine code, * This machine code is then directly executed to ‘obtain the output. 7. Java is known for its high performance, scalability, monitoring and managoability © Due to the use of bytecode the Java has high performance, The use of multi-threading also helps to improve the performance of the Java, + The J2SE helps to increase the scalability in Java. For monitoring and management Java has large number of Application Programming Interfaces (APD. + The monitoring and ‘racking the information at the application level. are tools available for 8. Jovais a dynamic and extensible language + This language is capable of dynamically linking new class libraries, methods and objects. ‘© Java also supports the functions written in C and (C++, These functions are called native methods. 9. Java is a designed for distributed systems © This feature is very much usefitl in networking environment. ‘+ In Java, two different objects on different computers can communicate with each other © This can be achieved by Remote Method Invocation (RMI). This feature is very much usefull in Client-Server communication, 10.Java can be developed with ease ‘There are various features of Java such as Generics, static import, annotations and so on which help the Java programmer to create a error free reusable code. 2 Basie Syatrctioel Constrcts in Jair Board Questions 1. State and explain any four features of Java. 2. Whyjava became platform independent language ? Explain. EAE [2] ava Programming Environment + The Java environment is made up of three things- development tools, classes and methods and java runtime environment + The java development Development Kit (JDK). + The classes and methods are called Application Programming Interface (API) which forms a library called Java Standard Library (JSL) + The java runtime environment is supported by Java ‘Virtual Machine GVM). [E22] Java Development Kit JDK) + The Java Development Kit is nothing but a collection of tools that are used for development and runtime prog tools constitute Java + Iteonsists of - 1. javac - The Java compiler which translates the source code to the bytecode form and stores it ina separate class file. 2. java - The Java interpreter, which interprets the bytecode stored in the class file and executes the program to generate output 3. javadoc - For creating the HTML document for documentation fram source code file 4. Javah ~ It produces header files for the use of native methods 5 Jab - The Java debugger whieh helps find the errors in the program, 6. appletviewer - For executing the Java applet. 7. javap - Java disassembler, which helps in converting byte code files into program de ption Toshnital Publestons”~ Anup frat rinoedlge ia es Ivo Programming + Following are the steps that illustrate execution process of the application program - 1. The user ereates the Java source code in the text editor. The source code is compiled using the javac command. 3. ‘The javadoe tool can he used to create the HTML, files that document the source program. 4. On compiling the souree program a class file gets generated which consists of the byte code 5. The developer may use Javah tool for generating the required header files. 6. The class file produced by javae can be interpreted using java in order to produce an executable, Commenting ‘source program ‘Java source AINE program Javadoc: pis vavac | Compilation Java class Header 4? |] Javan [ay Mea | Debugging Execution Java ;/——+] jab Java program output] Fig. 1.21 Execution process of application program 122 + Java Virtual Machine is a set of software and program Java Virtual Machine (JVM) ‘components. ase Syntatical Constricts i ava + As the name suggests is @ virtual computer that resides in the real computer. Java can achieve its platform independence feature due to Java Virtual Machine + The execution of any Java program is carried out as shown in Fig, 1.2.2 ‘Java Source Program ‘java fie) I Javac Compier I Byte Cove (Bis te} dave Java Java Vat Virtual iw crine | | machine | | amachine winzows | | Mac Linux Fig. 1.2.2 Execution of Java program «When we want to write any Java program, we write the source code and store it in a file with extension java. + This java file is compiled using javac and a class file gets created. This class file is actually a byte code. The name byte code is given because of the instruction set of Java program. + The Java Virtual Machine takes byte eode as an input, reads it, interprets it and then executes it, + The Java Virtual machine can generate an output corresponding to the underlying platform (operating system), [Board Questions J. What is WM? What is byte code ? 2 What 1s byte code ? Explain ay mo tools evaillabie in IDK. CTC Aa up tat rho ai} es fl Joe Program 1a Base Syntactic Construct in a 3 ne Bee tools available in JDK mang gana . NSBTE : Summer 15, Mat imenuee ee eae language. 13] Difference between Java and other ii -— Programming Languages 7. InCwecanuse InCH wean In Java there is the pointers, use the ‘no concept of pointers. pointers. Sr. c cH Java al 8 InCthereisnoInCH+ wean In Java, there class, The write a program must be at least 1. Cisalnguage The C++isa ‘The Javais a sniciore wo PRR ome class that needs to be language that language that intend of thet ‘compiled. noedstobe gets interpreted compiled, and compiled. Board Question 1. How java is different than other progranoning 2. Cis platform C++ isplatform Javaisa language? dependent. dependent —_ platform SCA independent 74] How to Write and Execute Java Program 3. Cdoesnot C+ doesnot _—_Java supports + Java programs are always stored by fllename extension support muli- support multi: —-malti- fai threading threading threading. # THeRane or NENA ME DE RE he programming. programming class. 4, Cdocsmot Ci doesnot Using Java, one | | * These java programs can be written using simple ee) no notepad file and executed on command prompt create and create and interactiveand | | + ‘The structure of Java program is as follows - implement the implement the user friendly ieamenenaiel graphical user graphical user graphical user ise See interface. interface. interface. 5 j ‘Import statements section §, Caves nothave C++ has Java has Class definition ‘any exception exception. exception RET eee ees handling handling handling { mechanism, mechanism mechanism public static void main(String] args) using try-catch using try-catch { nee joe aaa cad 6 Cdoesnot CH supports Java does not » supports any mute support Documentation section» The documentation section ‘object oriented inheritance. multiple provides the information about the source program. This programming isanobject inheritance section contains the information which is not compiled by concept. Itisa oriented however it the Java, Everything written in this section is written as procedure programming makes uso of comment. oriented interface I is an Tesinesl Fubiostons an up tt fer krone [ao Programming 1 Basic Synactical Constructs in few Package section : It consists of the name of the package by using the keyword package. When we use the classes from this package in out program then it is necessary to write the package statement in the beginning of the program, Import statement section : All the required java API can be imported by the import statement. There are some core packages present in the java, These packages include the classes and method required for java programming. These packages can be imported in the program in order to use the classes and methods of the program. Class definition section : The class definition section contains the def contains the data and the methods manipulating the data Main method class : This is called the main mettod class because it contains the main() function. can access the methods defined in other classes ition of the class, This class normally is class Note that we can write the Example of My First Java Program program in simple Notepad. Java Program|Firstprog java] a Pe race menos ail sis my First Java Program | Note that the mame of the program and class name should be same fe Subic static void maincstring araelI> t.peintineThts ts my Pest Javea pre: How to Executa? The output of this program can be generated on the command prompt using the commands. Open command prompt and type javac command. The syntax of execution of Java program is Javae filename java java filename Here is illustration Techneal Pubicatons”-An up thas nouleone Jou Programming Program explanation + In our first Java program, on the first line we have ‘written a comment statement as ® ‘Taio is my First Java Program 7 This is a multi-line comment. Even a single line comment like C-+ is also allowed in Java, Hence if the statement would be /(is is my First Java Program Is perfectly allowed in Tava + Then actual program starts with class Furstprog Here class is a keyword and Firstprog is a variable name of class. Note that the name of the class and name of your Java program should be the same. The class definition should be within the curly brackets, + Then comes public static void main(String argsll) This line is tor a function void mainQ. The main is of type public static void. The public is a access mode of the main by which the class visibility can be defined. Typically main must be declared as public, The parameter which is passed to main is Seng angst], Here String is a class name and args(] is an array which receives the command line arguments when the program + Then display on command. prompt window we write following code - the message System out printin( This is my first java program’) Glass and Object MSBTE Concept of Class Definition of Class : Each class is a collection of data and the functions that manipulate the data. The data components of the class are called data fields and the function components of the class are called member funetions or methods. Basie Stactaal Constructs in Ja + Thus the state of an object is represented using data fields (data members) and behaviour of an object is represented by set of methods (member functions) The class template can be represented by following Fig. 15.1 Fig. 1.5.1 Class template © The Java Class can written as follows clase Customer { snp; int Age; String Name; Data Custoren(){ } Customen(int 1D) { } Constructor double withdraw money) { Methoct ) + Encapsulation means binding of data and method together in a single entity called class, Thus a elass is used to achieve an encapsulation propert * This class is not having the main function, The class that contains main function is called main class. Concept of Object + Definition of object : Object is an instance of a class. * Objects are basic run-time entities in object oriented programming. + For example - If the class is country then the objects can be India, China, Japan, U.S.A and so on. + A single lass ean ereate any number of objects. + Declaring objects - The syntax for declaring object is - Class Namo Object Name=new class Name() up ttf known Java Programming + Example Prutt f1=new Fruit) Por the class Fruit the object f1 can be created. The mew operator is used to create an obje operator memory is allocated for the object Example of Class and Object, - Using new + Following is a simple Java program that illustrates the use of class, ‘impor java; jmpor java lana." {impor java.math.* public class MyClass 4 String namo; te int rol; eyes double marks; public void display(Stzing nat x double m) q ‘System.out-printin() ‘Systom.out_printin(‘Name: +n) ‘System out printin( ‘Roll number: +1); ‘System out printin(Mars:"+m): } publio tatic void main(String argel)) { int ab; ‘MyClass obj1=new MyClass() (obj1.aisplay(’Amay’10,76.65): (bj2.display(’Akbar’ 29.87.33) obj3 display(‘Antheny’,30,96.07); } } Output Name: Amar Roll number: 10 ‘Marks: 76.65 Name: Akbar Roll number: 20 ‘Marks: 87.33 Name: Anthony Roll number: 20, ‘Marks: 96.07 Basie Symiactical Constrct in ao Program Explanation ‘+ In above program we have declared one simple class. This class displays small database of the students. The Gata: members of this class are name,roll and marks There is one member function named display winich is for displaying the data members. In the main function we have created three objects objl,obj2 and obj3. These objects represent the real world entities. These entities are actuslly the instances of the class. The class representation of the above program can be as follows - ima ‘ros mate waar Members fanetion is defined here: sey ieeeen| (eee oT oa Fig. 152 Example 1.5.1: Define @ Cass item having data member ‘code and price. Accept deta for one object and display it. Solution: MyCiass,java import jevaio."; import javerlang.*; Jmport javanath + public class MyClass q int code: double price; public void display(int ¢,double p) { Syatem.out printin(): System. out printin("Code: "+e) System. out print "Price: "+ p) } public static vold main(String argsit) ¢ MyClass obj! =new MyClass) objl display(101,76.50); , Teatniza Pusloatons Anus tact fo nowledse [rca Pregroning oa asc Syntatical Constracts i ava Example 152: Wille a program to creale a cass account having variable accno, accname and balance. Define deposite ( and withdraw () methods. Create one object of class and perform the operation, CSD Solution : public class Account ( private double balance: rrublie void initialized) 4 balance=1000; + public veid dapesit{doublo amount) { balance ~ balance + amount; } Public vold withdravr(double amount} { balance + Public double getBalance() { retam belanea; } public statie void main(String args) { Account ae=new Account); acinitialzed; ‘System out.printin(‘Depositing some amount’); acdeposit( 100) System outprintin(‘Total Balance is: "| acthalance( Syetom out printin("Withdrawing some amount"); ac.withdeaw(200); System out printin("Total Balance is: actbalance(); lance - amour Board Questions 1 Define a class and object Write syntax to create class and object with an excenple Whar ts the use of new operator ? is tt necessary to ocd Sobers olgad! of te chats de crasiad? My? Winter 16, Marks 4 8 Java Tokens CS TONE The smallest individual and logical unit of the java statements are called tokens, In Java there are five types of tokens used. These tokens are - 1. Reserved keywords 2. Identifiers 3. Literals 5. Separators 4. Operators Rosorved keywords Keywords are the reserved words which are enlisted as below abstract default int super assert double interface __switch boolean else long this byte extends mative throw break final new throws case for package transient catch __float__private try char goio_protected void class if __publie volatile const implements __retun while continue import short true go instanceof static false sul Identifiors Identifiers are the kind of tokens defined by the programmer. They are used for nam ng the classes, methods, objects, variables, interfaces and packages in the program. Following are the ries to be followed for the identifiers. 1. The idemifiers can be written using alphabets, digits, underscore and dollar sign. They should not contain any other special character within them. ‘There should not be a space within them. ‘Anup rst orients + 710% Jia Programming 1-9 Suse Syutatict Constructs in faa 4. The identifier must not start with a digit, it should : ean always start with alphabet. 5. The identifiers are case-sensitive. For example - : ‘Commas are used to separate the contents. Ge Period is used to separate the package In above code a and A are treated as two different fame from subpackages identifiers faeces 6. ‘The identifiers can be of any length. ‘A variable is an identifier that denotes the storage Literals Literals are the kind of variables that store the sequence of characters for representing the constant values. Five types of literals are - 2. a 1. Integer literal Floating point literal 3. Boolean literal Character literal 5. String literal ‘As the name suggests the corresponding data type constants can be stored within these literals, Operators Operators are the symbols used in the expression for evaluating them Separators: For dividing the group of code and arranging. them systematically certain symbols are used, which are known as separators. Following table describes various separators. ‘Name of the Description Separator Oo Parenthesis are used 10 enclose the “arguments passed to it to define precedence inthe expression, For surrounding cast, type oO (Curly brackets are used for -initialising array for defining the block a Square brackets are used for declaring array types dereferencing array values location Variable is a fundamental unit of storage in Java. The variables are used in combination with identifiers, data types, operators and some value for initialization, ‘The variables must be declared before its use. ‘The syntax of variable declaration will be data typename of varlabls|=intiatzatiol|,—mtiatzarion|t Following are some rules for variable declaration - + The variable name should not begin with digits. + No special character is allowed in identifier except underscore. + There should not be any blank space with the identifi ‘+ The identifier name should not be a keyword, + The identifier name should be meaningful. For Example int aby char m~"a'; byte k=12,pt=22, The variables have a scope which defines their visibi and a lifetime. Data Typos Various data types used in Java are byte, short, int, long, char, float, double and boolean, byte This is in fact smallest integer type of data type. Its width Js of 8-bits with the range 128 to 127. The variable ean bbe declared as byte type as - byte ij ‘Ae up thrac frImondedge Jee Progamming short This data type is also used for defining the signed hhumerical variables with a width of 16 bits and having a range from ~32,768 to 32,767. The variable can be declared as short as - short ab: int This is the most commonly used data type for defining the numerical data, The width of this data type is 32-bit having a range 2,147,483,648 to 2,147,483,647. The declaration can be - intp.a: ong ‘ometimes when int is not sufficient for declaring some data then Jong is used. The range of long is really very long and it is ~9.223,372,036,854.775.808 to 9,223,372,036,854,775,807. The declaration can be = long xy float To represent the real number (i.e. number that may have decimal point) float data type can be used. The width is 32-bit_and range of this data type is |4e ~ 045 to 3.4e+038, double To represent the real numbers of large range the double data type is used. Its width is 64-bit having the range 4.9e-324 to 1.867308, Char This data type is used to represent the character type of data. The width of this data type is 16-bit and its range is 0 t0 65,536, Lot us see one simple Java program which makes use of various data types. boolean Boolean is a simple deta type which denotes a value to be either true or false, Java Program Note that for displaying the value of variable, in the rinéin statement the variable is appended to the message 70% 1-10 Basic Syactical Constrict in fs w + [In C we use comma in printf statement but in Java + is used for this purpose] Java Program [DatatypeDemo.java] ee ‘his program introduces use of various data type {in the program ” class DetatypeDemo 4 public static void main(String arge[l) ns ¢= 10000" 128; ong €~10000*1000+128; ouble ©=99.9998 char f=" boolean g=tnus) alse: System.out.printin("The value of a=: "4a); dynamic initialization boolean System out printin(‘The value of b=:'+b} System.out.printin("The value of Syotemout.printin("The valuo of a=: "+4, ‘System.out printin(‘The vahie of e=:“+e): System.out.printin(The value of f:"+0} fe: te); ‘System.out.printin(‘The value off after increment =: +0); System.out.printin("The value of g=: +9); np: System out printin("The value of Output ‘The value of a=: 10 "The value of b=! 1280 ‘The value of c=: 1280000 ‘The value of d=! 1280000000, “The value of e=: 89.9998 The value of f= a ‘The value off after ineroment=:b ‘The value of g=i tue ‘The value of h~: false Techical Puntesons” An up er traning I Ln Basic Symtacical Constructs in aca 3] Constants and Symbolic Constants Constants Constants mean the fixed values that do not change during the execution of a program. In Java various types of constants are used and these are as shown in following Fig. 1.6.1 Java constant Numeric constant (Character constant Charactor Sting Integer constant al constant sete cana Reelcaneel constant constant Fig. 1.8.1 Typas of constants Numeric constants Numeric constants are used for representing the numerical values. The numeric values can be integer or real type. Hence there exists the integer and real constants. Integor constants Integers mean sequence of digits. There are three types of integers - Decimal integer numbers. That means these can be preceded by unary minus, For example - 111, + The decimal integers consist of a set of digits (| through 9. These numbers can be unary 200, 455 Octal integer : The octal integer constants consists of set of 0 to 7 having a zero at the beginning, For example - 033, 0431, 0633 ‘Hexadecimal intoger : Along with the 0 to 9 digit, it also consists of the letters A to F. Real constants : The real constants contain the floating point parts. For example - 0.045, 0,567, 0.3211 Character constants : A single character constant is enclosed within a pair of single quotes, ‘Tye String constant : A string is a collection of characters enclosed between double quotes. The characters can be alphabets, numbers, white spaces or special characters For example - For example - “India” ,"Bestl 0”, “s?ss” Symbolic Constants + There are two problems that are associated with the constants and those are ‘Modifiabitity : The constants may need to he modified during the program, For example : The value of pi may be 3.14 at one place in the program and it may be required as 3.14159 at some other place in the same program for the aceuraey Teaiea Publocione Anup ts orlando Joa Pragramning Basie Syntactic Constrt fava 2. Understandability = The purpose of each constant need 10 be remembered. For example : The constant INDEX may be required to store the index, the constant COUNT may keep track of some count or there may be some constant for SIZE. + To overcome these problems there is a usc of symbolic constants, The keyword final is used to declare the symbolic constants, + The syntax for declaring the symbolic constants is final datatype variable_name=value + For example ‘nal int INDEX=1: final int SIZE: + Conventions : Following are the conventions that are associated with the symbolic names - 1. Symbolic names must be written in capital letters. 2. Affer declaring the symbolic name one must not modify it The symbolic constants are declared for types. 4. The symbolic constants can not be declared inside a method, They should be used only as class data members in the beginning of the class. [Ee] oynamic niiaization «+ Java isa flexible programming language which allows the dynamic initialization of variables. + In other words, at the time of declaration one can initialize the variables (note that in the above program we have done dynamte tnitializartor + In Java we can declare the variable at any place before itis used Scope of Variable + There are three types of variables ~ 1. Instance variable 2. Class variable 3. Local variable + Instance and class variables are declared ins + The local variables aro declared inside the method. Example of Static Variable class Test 1 public woid 20tA0) { ‘int A=10:/flocal variable { System.out printin( Block A: +A); i/scope of A=10 ends here t 20,//scope of A=20 starts here Systomout printin( Block A: "+A }/ecope ef A=20 onde hore y }/scope of all the variables end hers public class VarSeopeDemo { public state void main(String args) 4 opisetAl) ) y ‘output Blocte A:10 Block A:20 fare not accessible to the method + The local variables outside the method because their scope is scope of the Local method) + The area in whieh the variables are ac scope. + The program blocks can be nesting , ie. one block ean nited within the { and } essible is called be defined within another block. + When the objects are instantiated at that time the instance variables are created, The instance variables are associated with objects, Hence with each different object there is different value associated each instance variable. + Example of Instance Variable claas Tost ‘ publi int A:/instance variable public void 90tA0) A=10; } y = Tosinise Pubienons” «An yptirs rinontaeoe 1 a Cy Programming 1B Basic Syntatical Constricts i vt ponte class VarScopeDemo a = public static void main(String argefl) int a=5; t long b; ‘Tost obj-now Teat(//instance of class ie croatod bea; obj. setA(}/accessing the variable using instance of the class Systemout printin('A= "+-0bj A) Output ‘The class vartables are global to the corresponding class, This variable ean be accessed by the objects of that class. + Example of class variable class VarScopeDeme private static int Ay//elaaa or static variable public static void main(Stsing argstl) { 0: Sysemoutomin’a= “+A + } output a=t0 [Ee] typecasting Java allows the automatic conversion between these data types. But Java performs type conversion between the ‘compatible data type elements, For instance: If we ign an integer value to a float type element then Java automatically makes this conversion. However, this automatic conversion can not be done between any data ype, rather such a conversion is done with the compatible data type elements. eer mR ee eae + When two data types are compatible to each other. + When the target data type clement is larger than the source data type ‘+ For incompatible data types we have to do explicit type conversion. This mechanism is called casting, Hence Defintition: Type means incompatible data types casting explicit conversion between For casting the values we use following syntax: (ope) variable Example: In the following Java program, we use the type casting Java Program|TypoCastProg java] public class TypeCastProg q ppublic statie void main(Stingll ares) 4 couble x ‘System. out printIn("Value of [deublol "4: ‘Syetem.out println(‘Convorsion of double to integer’) yo ints System.out printin( ‘Value of finteger] y+); double n; m=10; n= (double): ‘Syster.out printin( ‘Value of finteger! m: "+m); ‘System. out printIn('Conversion of integer to donb") ‘Systam.out printin('Value of [deubla] n:"4n); ‘Output Value of [double] #265 ‘Conversion of double to integer op tse once [rea Programming Vaive of linteger|¥: 25 Value of finteger| m: 10 Conversion of intager to deuble Value of double] n: 10.0 Program Explanation In above program, 1) We have made the type casting of- Integer to double, double to integer 2) When # double value is converted to an integer the fractional parts is lost. This is called trumeation, But when an integer gets converted to double then fractional part is padded Following table shows the possible type casting without Joss of information- From To byte short, char, int, ong, float, double short i Jong, Moat, double + 70% 4 Basie Syntactic Constructs i Jars Board Questions 1. State and explain scope of variable with an exanple. Ceeeee ees 2: What ts seapeicf variable’? Give example of elaes vartable, mstance variable and locai variable. ab ocr temper emer Std oceete Uae Ei el, Spe cna in with their storage sizes in bytes. DSSS Operators and Expression css TSCA ST Various types operators used in Java are - 1. Arithmetic operators 2. Relational operators 3. Logical operators 4, Increment and decrement operator char int, long, float, double int long, float, double long double , float float double 7.6.7] Standard Default Values Java provides default values to the variables if we don’t initialise them, ‘The standard default values for the variables of different data types are enlisted below- Data typeof the variable Default value byte oO short 0 int ° OL float our double 00d char Boolean false seference rll 7.4] Arithmetic Operators Type Operator Meaning Arithmetic = Addition of unary plas 2 Subtraction or unary + Multiplication ear / Division cab Mod Program demonstrating arithmetic operators class ArithOpe:Demo C public static void main(String] args) { ‘System.ont printin(\n Performing arithmetic operstions De: ‘System.out.printin('a= +a}; a int a=10. ‘System out printin( c=ath; ‘Syotom.out:printin("\ Addition of two numbore io" ‘Systemn.out.printin("\ Subtiaction of two aumbers is"; oath a TesticalPublenions An yp tire Gr inoutaoge Joa Prograraming System out printin(\n Multiplication of two numbers is "t¢) c=apo, System. out printin(\n Division of two numbers is “4c); } Output Performing arithmetic eparatione 10 b= 20 Addition of two numbers is 30 Subtraction oftwo numbers is -10 ‘Multiplication of two numbers is 200 Division of wo numbers is 0 Relational Operators Type Operator Meaning “Example Reltional < Less than act = Grvoter then b10 Less than equal to ~ Greaterthan equal to a5 = qual to s==100 = ‘Not equal to Program Demonstrating Relational Operators laos Re!OperDeme { public static void main(String] args) { ‘System out printin(\n Performing Relational operations ") System. out priniin(\a Tas ab)); 2 System.out printin(\a Tae a<—b is “+(a<=b), System out prntin(\a Tae a>=e1s"+(a>=c): System out printin(\n The ie (a Basie Syniactcal Const i ane ‘Systom out.printin( "wn The al=b is “H(al=b)) ‘Output Petfonning Relational operations 10 2 b The acbis uue The a>b is false The a<=b is trae The a>=c is trie ‘The al istrue Logical Operators ‘Type Operator Meaning Example Logical && —_Andoperator 0&1 I Oroperaror 1 Program Demonstrating Logical Oporators import java.io." import javalang-" publlc cass LogicalOper 4 public static void main(String argsl)}throws IOException boolean operl oper? opert=tive; oper2=false: boolean anetane2; ans oper! &oper2; ans2=opert |oper2; ‘Syotem.out printin("The oport is:"+opert}; ‘Systerm.out printin("The oper2is:"-+oper2); Tectnical Pubeatons An op tira frhronibage Jrsa Programming System out priniln("The oper! &oper2 is; "+ ans) System out printin("The oper! jopar2is:"+ans2)}; Output Tho opert io: rus The oper? is: false The opertéoper2 Is: false The oper! oper? ie: true A] Increment and Decrement ‘Type Operator Meaning Example Increment + Increment by one +4 or i+ Decrement Decrement by one ~~ kor k- Program Demonstrating increment and Decrement Operator class InciDecrOperDemo t public static void main(String] args) 4 ‘Systemout.printin(\a Performing increment and decrement operations") inta=i1, = 22: Systemout.printin(’e= "+8); Systemout.printin(b= "+b), ‘Systomout.printin(\n Prelaeromenting a'4+ +42); ‘System out printin(\n Postinerementing b ++ b +4); ‘Systemout.printin(\n After this statement the value of b is, ao y + Output Performing increment and decrement operations ant b= 22 Prolacrementing a 12 Baie Syntasticn! Construct i or Postincromenting bs 22 After thio statomont the value of bis 22 [73] conditional Operators The conditional operator is?” conditional operator is ~ ‘The syntax of Condition?expression :expression2 Where expressionl denotes. the expression? denotes false condition true condition and For exampl a>b?truesfalse This mes s that if a is greater than b then the expression will return the value true otherwise it will return false, Program Demonstrating Conditional Operator class Test « public static void main(String args{}) ‘ int abe 2510; b=20; System out printin('a System out printin("> c=a>brab; Syotom.out printin(c "ie groate , ‘output a-10 b=20 201s greatest Bitwise Operators Assume A=35 ic, in binary form 00100011 and B= 14 i.e. in binary form 00001110 Testncel Pubiessone” Anup at oricwlaice aT) Ee So Jom Prograveing wr esc Syntactiod Const nat Type Operator Mean Example with zeros bitwite ana « Binary AND Operator copies abi to the result ifitexss in both AAR=0O100011 & operands, 10001110 on000010 Trath Table 4 B | Oupue o 0 o 0 1 ° 1 o o 1 1 1 bitwise or Binary OR Operator copies a bit if it exists in either operand. AB Truth Table A B | Oupue ‘010001 | 09001110 7 z 5 =0o101111 ie 47 o 1 1 1 o | 1 1 1 ° bitwise XOR ss Binary XOR Operator copies the bit if it is set in one operand but ASB sot both - Truth Table on; 00011 *co00t 10 A B | ouput =v0101101 [pe 0 0 eds o 1 1 1 ° 1 1 1 ° bitwise complement ~ ‘Binary ones complement operator is unary and it has effect of ~36 Sipping bits. Left shift < ‘The left operands value is moved left by the number of bits 00] 00011<<2. specified by the right operand =1000 1100 Right shit > The left operands value is moved right by the numberof bits 00 100011>>2 specified by the right operand 0000 1000 Zerofillnght shi’ >>> The lett operands value is moved right by the umber ofits 001000115552 specified by the right operand and shifted values are filled up 0000 1000, Tachnia! Publcetons” —Anup tnt fr moa va Programming Baste Syntatical Constructs in Ja. Program Demonstrating Bitwise Operator ublle class Test { ublic static void main(String argst) { int a = 9; /* 35 = 0100011 */ int b = 14,/* 14 = 00001210 */ int © = c=akb: /*2=00000010"/ Syster.out printin('a & b =" +c) e=alb: s47= 0101111) System.out printin('s | b=" ¢ ) esa b (45 =co101101 + Systom.out printin('a *b="+e) «22 Syetom.out printin('s <<.2= (#140 = 1000 1100*/ +er e=e@>>2 (8 = 0000 1000 */ Syetemoutprintin('a >> 2 = "4 €): e-e sss 2 /*8- 0000 1000 */ System.out printin('a >>> 2=" +e) Instance of Operators and Dot Operators © There are two special operators used in Java- instanceof and dot operator = For determining whether the object belongs to particular class or not an instanceof operator is used. For example - Ganga instanceof River If the object Gat returns true otherwise false wza is an object of class River then it ‘© The dot operator is used to access the instance variable and methods of class objects. For example Castomername for accessing the name of the customer CustomerID //for accessing the ID of the customer [Operator Precedence and Associativity + Precedence : The precedence relation specifies which operation must be done first during the expression evaluation. ‘+ Associativity : Associativity tells the direction of execution of operators that can be either left to right or right to left. For example, in expression a= b~ ~ 10 the assignment operator is executed from right 10 left that means ¢ will be assigned by 10, then b will be assigned by c and finally a will be assigned by b. * Followi Wg table denotes the precedence relation and associativity. The operators are arranged from Highest priority to lowest priority, The operators in the same row indicate the equal precedence. Precedence Operator Description —_Assoclativity| 1 ‘Array index Left > Right 0 ‘Method call Member acooss e+ Pre or postix increment Right > Left Pre or postfix decrement + ‘Unary plus, minus e Binwise NOT. ! Logical NOT 3 (ype typecast Right > Left east) object ereation oi ‘multiplication Left > Right 1 division % modulus (remainder) | adit, subtraction Left > Right , String concatenation 6 << Len shift Left > Right > ‘Signed right shift 25> Unsigned or zerofill Right shift oa < Less than Leh > Right < ‘Less than or equal to 2 Greater than Tern Puntestons Anup tract br knawedge + 710% ba Je Programming 1g ast Sync Consructs in aoa = Gna imarrenite than addition, So we perform multiplication operation instanceof reference text first and then addition 2 ana Left-> Right | | [E740] Mathematical Functions Not equal to + Java provides a support for performing mathematical oan: een ee operations by means of mathematical funetions + The basic mathematical functions are defined in the 1° Bitwise XOR Left-> Right Mell /Slaoa“dafined “wi, javahane:packeipe,Vanous n a ent> eign | | ematical functions are - sin( double angle) Returns the sine of angle in radians 12 && Logical AND Left Right "| | | cos(double angle) Returns the cosine of angie in radians | LoeiealOR Felt Rish'| | | an (double angle) Returns the tan of angke in radians iat Conditional Gemary) —_Right-> Left | | | asin(double val) Returns the angle whose sine is val a Assignment and short Right Left | | | se0sdouble val) _Retuns the angle whose cosine is val eee atan(double val) __Retums the angle whose tan is val operators pow(double a, Iteomputes a oule y) exp(double a) Teomputes ¢” saitidouble 3) Iecomputes square root of = max(a,b) Itcomputes the maximum of a and b rinfah) Itcomputes the minimum of a and b Iogtval) It computes the logarithmie values of val [£75] Evaluation of Expression abstval) Itcomputes the absolute valve of val + Expression is a combination of operators and operands fi pacltio aiainee, cxilval) Itretums the smallest whole number ‘which is greater than or equal to val + Forexample c=a#b*e;/! Expression with arithmetic operators focal Pe ere ee err (a>b)&&(b<0)// Expres relational operators sion with logical operators and ‘The evaluation of expression is an order of evaluating the expression using precedence and associativity rales, For example ~ To evaluate 2+3*4 we will first perform 3*4=12, then add 2 to 12 and the result of this expression will be 14. ‘This is because multiplication has higher precedence ‘which is lesser than or equal to va Following is an example of Java program which makes use of mathematical function - Example 1.7.1 : Write a simple Java program fo ilusrate use of mathematical function, Solution : Java Program|MathDemo,java] class MathDemo q public static void main(Stringll aras) 4 ‘An upthnstorkroninege Ins Pragramnning oable val: vval=26; System.out printin( "yn The squate root of +vel+" is "-+Math.sexx(val); Int a=10,b=20, ‘Systemout prin‘in(\n The maximum of '+Math.max(ab)) ‘System, out printin\n The minimum of “+a-+* and "+b" 38 “Math min(a.b): ‘System. out printin( "in The sin of +val+ ie *EMath sineval) ‘System.out printin("in The eos of "+val: “4Math.costval): } y and "tht" is Output ‘The square root of 25.0 is 5.9 "The maximum of 10 and 20 is 20 ‘The minimum of 10 and 20 ie 10 The n of 25.0 is -0.19295175009777303 “The cos of 26.0 s 0.9912028118634736 Le 1-20 ‘Board Questions 1. Describe any two relational and any two logical operators in Java with simple example. NSBTE : Summer 16, Marks 4 Explain any two relational operators in Java with exanple. ca 3%) What this operator is calied ? Explain with suttable example. 4. Explain any two btt-wise operators with example, CSS 5. Explain following biowise example () Left shift operator (2) Right shift operator CSET SUTRA operator with an 73) Decision Making and Looping os SEAS SET A] Statement The if statement is of wo types - Basic Syntctenl Constructs in Joa 1) Shmple if statement : The if statement in which only ‘one statement is followed by that is statement ‘Syntax (apply some conaition) ‘statement For example ia>b) Syetom out printin(“a ie Biitg!); it) Compound if statement statement that can be executed when if condition is true, Then it is called compound if statement. All these executable statements are placed brackets. if there are more than one im curly ‘Syntax apply some condition) { statement 1 statement 2 } 18.2] 1 else Statement The syntax for if. .els condition) ase statement statement will be ~ For example a>) System out printin(‘a is big") else System out printn("b ‘big brother") The if,..else statement can be of compound type even, For example, iseining~—tras} { Systemout printin( “I won't go out") System out printin(‘l will watch TV, Serial) System ont printin(*Also will enjoy cafieo”) ) lee ouput tor insolege Joa Pragramning Basie Syntactic Constrt fava ( ‘System.out.printn("T will go out”) ‘System out printin(*And will meet my frend” System.oat.printin|“we will go for « movie" System.out.puinila|“Any how I wlll enjoy my life"): ‘The syntax off. .else if statements, iif condition trae?) statement else if(another condition) ‘else iffanother condition) else For example iflege==1) System.out.printia|"You are an infan:") ese sage==10) System.oat.printin|*"You aro a kia"); else illage==20} System.oat.printin(“"You are grown up now"): lee System-outprintn(*You are an adult”); 4.8.4] |i-else-if Ladder + The control flow statements are evaluated from top 10 if ladder will be evaluated bottom. Hence the if-else from top to bottom. + As soon as an if statement from the ladder evaluates to true, the statements associated with that ifare executed and the remaining part of the ladder is bypassed. + The last most else is executed only when no condition in the whole ladder returns true. + Example Program public class Test C public static woid main(Stringf} args) char marks=68, if (marks <50) System.out.printin(You are Fait"; elseif (marks >=60 && marks <60) Systom.out printin(Second class is else if (marks>€0 & marks <70) Syston. out printin (First Class"); awe ‘System. out printin(” Distinctiontl ‘Output Firat Clase 1.5] Switch Statement Using switch statement we ean make a choice from a list ‘of values. Each value in switch statement is considered as ‘case, A variable is used in switch statement to match the desired case, ‘The Syntax of switch statement is switchlexpression) 1 ‘case value statements break ‘eave value: statements break default: //optional statements } For example switchich) { cose 1: Systom.out printin(‘Monday"; break ‘case 2: Syetom out printin(‘Tuestlay’); breale case & System out printin( Wednesday’) breake cose 4: System. out printin(Thursday") break toon out printin(‘Fridsy" breale case 6: System. out printin(Satusday’) real cave 7: Syster.out-printin(‘Sunday’ breake case §) } Example 1.8.1 from an if statements ? Tn what ways does a switch statement differ CeCe: = Toshnise Pubienons” «An yptirst rinontaeoe aon Prgramining Sei) a asc Syntactic Conetrcts in Java Solution : if statement switch statement Lielse statement west for ‘equality as well as for logical expression. ‘witeh statement tests only for equality. 2 The fstatement evaluates integer, character pointer, floating point or boolean values ‘The switch statement evaluates only character or integer valve. 3. The ifelse statement uses multiple statements for ‘witch statement uses single expression for multiple choices. sultiple choices. 4 Either if statement will be Switch statements ‘executed or else statement executes one ease after will be executed. otber until it reads break statement. [EES] Nestea switch Statement Nested Switch slatoment is @ switch statement inside another switch statement For example - Consider following Java program public clase Test { public static void main(Strinall args) case 1 ewiteb(>) 4 case 1:Systom out printin( Java’ break; case 2:System.out.printin( PHP); break; ) break: caso 2 sswiteh (>) 4 case 1'Systomout.printin( HTML") break: case 2:System out printin( XML) break; 4 output PEE Program Explanation : In above Program, As value of ; the control will enter in the outer switch with case | As value of b=2,the control will enter in the inner switch with case 2 Hence the outpat is “PHP”. TB7] The while Statement + This is one form of statement which is used to have iteration of the stement for the any number of times. «© The syntax vwhiie(condition) { statement 1 statement 2; stetoment 3: y For example int count wihiletcount<=6) 4 ‘System.out printin("f am on line number * +count); count +: } Let us see a simple Java program which makes the use of while construct. Java Program [whiledemo java] fe ‘This is java program which Mlustrates while statement ” clase whiledemo { public static void main(String ares!) { int count=1.i=0; ‘while(count<=5} Jrsa Programming Syetom.out printin|"The value ofi~ "+4); Output The value of The value of m2 The value of i~ 3 ‘The value of = 4 Tne value of Trample 1827 Deine «dan having one 3 digh rane Tan Edt ec Wetec Sede rene ttt fuer Solution : pac clas NunRavoran { pebie vokdinbind) { sia Syren out pena The number +m > dati sol casas) { System.out.print(‘Reverse of number is: "), rhein > 0) a wr 10+ (aun 109 mat; } System.out printla(rev); + ‘public static void main(String!) args) { NuraReveree objone NunBaverae: cea tated oo diaplay; i } Output The number is: 128 Reverse of number is 421 Example 183: White @ program to find sum of digit of ‘number entered by user TTT rz a Baie Syntasticn! Construct i or Solution : ‘public class DigitSum { ‘nt gum public void initialize) { num=123; Syetem.out printin('The number ie:" tau): } public vold aisplay() ‘ int while(num > 0) ‘ sum = cum + (num % 10); mura = num / 10; ) System. out printin(‘The sum of digits is: “+ sum): } public static void main(String! args) { DigitSum obj~new DigitSum() obj initialize); objaisplay(), } y Output "Tho numbor ie: 129 ‘The gum of digite ie: 6 Example 1.6.4; Waite a progam to find the number of and sur of all integers greater than 100 and less than 200 that are divisible by 7 Ee Oe Solution ‘public class Digittance q public static void main(String!) args) ‘ int eum=0;, Systemoutprintin("In Numbers between 100 to 200 which is divisible by 7) for(int i=101;1<20035+ +) 4 907-=0) q Syetemout.print(? 4); z “f Testncel Pubiessone” Anup at oricwlaice Joa Pragramning System. cut printin"\n sum = "+ sum}; ‘Output [Numbers berween 100 to 200 which is divisible by 7 305 112 119 128 132 140 147 154 161 168 175 122 189 196 ‘sum = 2107 [8a] Tee do wnite statement + This is similar to while statement but the only difference between the two is that in case of do, .while statement the statements inside the do,..while must be executed at least once + This means that - © The statement inside the do...while body gots executed first and then the while condition is checked for next execution of the statement. © Whereas in the while stotement first of all the condition given in the while is checked first and then the statements inside the while body get executed when the condition is true, Syntax ao « statement 1 statement 2, ‘statement m }whilelcondition); For example Java Program [dowhiledemo,java} ‘This is java program which Mlustrates do... while statement ” class dowhiledemo 4 ublic ctatic void main(String argell) { ‘nt count: do 4 0, Basie Syntactic Constrt fava Systom.cut printin(The value of |= “+1); count ++ }while(count <5); ? , ‘Output ‘me value of ‘The value of ‘The value ofi~ 3 ‘The value of! ‘The value of 759] The for Statomont for is a keyword used to apply loops in the program. Like other control statements for loop can be categorized in simple for loop and compound for loop. ‘Simple for loop for (statement 1;statement 2;statement 3) execute this statement; ‘Compound for loop : for(statement 1;statement 2; statement 3) £ ‘exocute this statement: execute this statement; execute this statement; ‘at's al ) Here Statement 1 is always for initialization of conditional variables, Statement 2 is always for terminating condition of the for loop. Statement 3 is for representing the stepping for the next condition. For example : forte { Syotem.out pratla(‘Java ie an interesting language"): 8ystem.outprntn(“Yeva is a wonderful language”) System out printin("And simplicity ists beauty" ) Let us see a simple Java program which makes use of for loop. Ic =5ut+) = Toshnise Pubienons” «An yptirst inontaeoe aml BA Jrea Programming Java Program [forloop.javal ” Thls program shows the use of for loop ” clase ferloop ( public static vold main(Stuing arest)) q for(int i=Oi<=6;i+ +) System.out.psata("The value of "+1, y , Output The vane of :0 The valve off 1 The vale of 2 The value of: 3 The vatve of 4 The value of: 5 Example 1.8.5: Write a program to generate Fibonacci series 112358 13 213455 89. Tg Solution : clase Fthonacci { public static void main(String args!) 4 int ab, ev} ana; fo(a=1n<=10;0+-+4) ‘ System out print(" +a); +b: Deere Dace a eorae Reo Basic Syotaa Consiucts in Ja The Break Statement ‘When a break statement is encountered in a loop then the loop is terminated and the control resumes the next statement following the loop. For example Java Program public class breakDemo { public static void main(String{] args) 4 for (inti = 1; <= 10,544) t Wa==5) t Jbroak, // terminate loop iftie 5 y System. out print + } Bystem.out printin(‘Loop is terminated using break") } 3 Output 1.23.4 Loop Is terminated using brea! Program Explanation : In above program, 1) The for loop is executed for i=1 to i=10. 2) But when i value reaches to 5, the break statement is encountered, 3) Due to this, the control terminates the for loop end the ‘System.out printin statement outside the for loop will be executed. Hence is the output TB.11] The continue Statement ‘When a continue statement is encountered inside the body of a loop, remaining statements are skipped and loop proceeds with the next iteration, For example - Java Program ublic class continuebemo { public static void main(Stringl] args) 4 for(int = 1; <= 1014+) t a ==5) € ‘continuo; y TecriclFuboton” Anup tut fer kronleine Jsa Programming Systemout print + Output 1294678910 Program Explanation : In above program, 1) When the value of i proceeds with further remaining values of i, Hence is the output 2) Note that : You cannot use break to transfer control to a block of code that does not enclose the break statement. Example 18 5 then it is skipped and loop 7 Wille a program lo check whether an enlered number Is prime or noi CECE Solution: class PimeNumberemo { public static vold main(String argstl) { tnt n = Integer.parsemnt(argsi0): >boolean flag = tras ia <2) fag else 4 fotint i= ‘ sftn 63 { se: fag = false: break ? flag = true) } d if(@ag == true) System.out printla(a + "is a prime number’) aise Syetomoutprintin(a + "ig not a prime numibe ‘Output DAMSBTE_JAVA Programs? javec PrimetvumberDemo java DAMSBTE_JAVA_Programa> java PrimeNumberDeme 15 15s aot a prime number Basic Sytatisol Constructs infer [EBaz] The return statement + The return statement is used to retum from a function. ‘That means Using return statement the control. goes back othe caller function. © At any time the retum statement can be used to transfer back the control to the caller function, + The return statement causes to terminate the function immediately. + Example Program ‘Glass RetumProg, 4 public static void main(String axgol)) ‘ int =10; Systerm.ou print "This statement is before execution of return’) iffe==10) ‘System out printin"This exontedl"; + y statement willl not be ‘Output “This statement is before execution of return TB.13] Tho nested Loops When one loop is present inside the other loop then that structure is called nested loop. The outer loop takes control of the number of complete repetitions ofthe inner loop, Example Program Gass NestetLoops 4 public otatic void main(String axgol)) « int ij forlim ix ~31++)//outer loop « System outprintin('i = "Hi fox()=1)<=3)++)/fnner loop q Systemoutprint(*j ~ > System out.printin( a , = Tectia Pubieators Anup trust forknowledne Ja Pregranoning Output CSSA Solution = clase Test public statie void main(String argel!) { int is for(l=1d=53+ +) { be) System out print" “4; + ‘Syetom out printin("); y y Output raaaa 2222 333 44 5 Example 18.8 = Write a java program to display all the edd numbers between 1 to 30 using for loop and if statement. Solution public class Test public static void main(String] args) { 1-27 ase Syntacticn! Constricts i ava System out printin("The eed mumbrs aro") for(int i++) { iGx21~0) System.out print(’"-+); Output "The odd numbers are 1.3579 11 18 15 17 19 21 28 25 27 29 Example 189 pattern Wiite a Java progam to display following Solution class TiiangleDisplay { Public static void main|Strnal| args) System.out prin ) fox(e=15<~ (2-1); #41) 4 System.outprint(); d System.out printin("; Output Tectia Pubiaions” An up tat rowed + 10% Sion Progretaing Example 1.8.1 ‘number pattem White a Java program 10 display following 1 12 123 1234 12345 Solution : lage NumberPatrernDigplay. { public static void mein(Stzing!) argo) 4 lot is fox(i=t31<=5 14+) 4 formtsijavac MunberPatterndi splay java D:\>Java NunberPatternDisplay a4] 4) labelled break + Sometimes the control needs to be transferred to a The Labeled Loops specific instruction. This ean be done using the statements like goto. + Java provides the support for jump statement using labeled break. + The syntax for labelled break is break label; 12 Basic Syactcn Constructs in fom Jabel is the name of the block which need to be skipped. + Following program demonstrates the use of labeled break, Example Program clase brealkblDemo { ublic static void main(String argsil) third, { ‘System out printin(‘Bofore the break) ifi==8) break second: // break out of second block Syster.cut printin("tnside third block); > System out printin( Inside socerdl block) System.out.printn(‘Taside first block" ) ‘Output Botore the break, Inside fist block. Program Explanation : In above program, 1) We have created three blocks, by labeling them as first, second and third 2) Inside the third block the labeled break statement is written to break the second block. 3) Hence the control skips execution of second and third block and reaches to the first block. So is the output. 2) labelled Continue + The labelled continue is basically a continue statement with label + The syntax is continue Zabel: + Example Program : Following java program, illustrates the labeled continue statement, pp tt role Jo Programming 1-29 asc Static! Consiact in aoa geen nane + Sia forldate_type variable name:arry_naoe public setic void main(String argsll) pene anaes eee) } Systam.out printhn(Even value: continue Labell; , ‘System.out.printin('Odd value: = “+ » } y output Even valve (Odd value: = t Even value: = (Odd value: = 9 Even value: = (Odd vaiue: = 5 Even value: = (Odd value: = 7 Even value (Oda vaiue: = 9 TB15] The for-Each Version of the for Loop ‘© The for-cach clement is used to access each element of anamay, © There are two advantages of for-each statement - i). Tteliminates the possibility of bug fi) Ih makes the code understandable. more readable and Techies Pubiotons™ + Example Program class ForBachProg { public static void main(String args|)) < int arvayl]=(10,20,30,40}; System.outprintin("The elements in anay are fon(nt tarray) Syotom.out printin(); i Output The elements in array are 10 20 30 40 Board Questions 1. Write general syntax of any two decision making statements and also give its examples. 2 Explain break and conmmues starements with example Cette ees 3 State syntax and describe wor'ang of ‘for each’ version of for loop with one example. CSREES 4 Mbusirate with exemple the wse of switch case ‘statement 5. Descrtbe break ard continue statement with exaonpie STE : Wintor 15, Marke 4 An upthr ty inauleege Le Inns Progranasing 1-3 Baie Syntctcal Construct in Joa Notws ‘Teotrical Publeatons "Anup tuto inonledge UNIT Derived Syntactical Constructs in Java [2:1] Constructors and Method + Definition = The constructor is a specialized method for initializing objects. Name of the constructor is same as that of its class name. In ether words, the name of the constructor and class name is same, cine Tot { Class Name Teste _—~—“CBstructor Moody of constructor Whenever an object of its assoc ted class is created, the constructor is invoked automatically The constructor is ealled constructor because it creates values for data fields of class Properties of Constructor 1, Name of constructor must be the same as the name of the class for which it is being used The constructor must be declared in the publie mode. The constructor gets invoked automatically when an object gets created The constructor should not have any return type. Even @ void data type should not be written for the constructor Constructor can make use of new or delete operatars for allocating or releasing memory respectively. “Multiple constructors can be used by the same class 7. When we declare the constructor explicitly then we must declare the object of that class. Difference between Constructor and Method sr Constructor ‘Method No. 1. Thename of the ‘The name of the method constructor must be should mot be the class same as the class ‘name. 2. Itdoes not return team return and hence it anything hence mo has a return type. If method return type. does not return anything then the return type is void ‘The purpose of ‘The method is defined to construcieris to execute the core logic of initialize the data the class. ‘members of the class ‘The constructor is, ‘The method must be called. invoked implicitly at explicitly using the object the time of object name and det operator creation. [22] tyres of Constructors Various types of constructors are 1 Let us discuss them in detail Default constructor 2. Parameterized constructor 1) Default Constructor © The default constructor is a simple constructor in which no parameter is passed 10 the constructor function. @-n)

You might also like