You are on page 1of 64
Introduction to Object Oriented Programming paradigm MM INTRODUCTION TO PROGRAMMING PARADIGM. Programming paradigm refers to the fundamental style of computer pro ‘ the approach to problem-solving and programming language constructs usa to nt Solution. defines the methadlogy or set of princes that programmers fay and implementing software applications, gram ing TYPES OF PROGRAMMING PARADIGM ‘There are several programming paradigms, each with its own approach to soh different types of language const a 8 ructs. The main programming paradigms include: Imperative Programming: This paradigm focuses on defining the steps or Xo achieve the desired output, The on how to achieve the result rath Object-Oriented Programmin Procedures code is executed in a specifi order, and the en er than what the result should be {OOF}: This paradigm focuses on the use of objec psulate data and functions. OOP emphasizes may ulate real-world scenarios, 1 in fans Pataigm emphasizes the use of functions and the cong Lr nal Pogamng. the emphasis on what should Be dong ‘at should be done. and the ability to sim Functional Pro is paradigm emphasizes the use of Processes or threads are executed simultenso ‘advantages and disadvantages, , the programming language us Processing and sy and the choice of pa se, nd the pre ach programmin ‘depends on the the programmer. i paradigm has Broblem to be solve ani languages for each Drogramming paradigm = Pascal, Fortran, and BASIC ana and Fare examples of "a emphasizes the use of functions with networked environme wedded in web pages and run on ‘content, such as games and [oP follows! [OOP has access specie ec using member functions OF provides an e957 way to add ne data ond function. lexample: C+, JAVA, VB.NET. ample: C, VB, FORTRAN. [1.4 Basics OF OOP ted. programming (OOP) present real-world concepts and are instances of classes that encapsulate data and functions. An object and behavior (methods) remplates for creating objets. A class defines the data and methods we, You can think of a cass as a blueprint for creating objects. ion is the process of hiding complex details and focusing on essen ion is achieved through encapsulation, where the internal details iO. a SN TOR is a programming paradigm that emphasizes the use of factions. Here are some basics of OOP: Interfaces, which that operate on n be used for web ftware component ring. and Go ae exanies of programming iguages JECT ORIENTED PROGRAMMING CONCEPT cnet neni 4 ony or and medica Ovi nD va AN ined Z AV mqutho and implemen gt 15. avvoriat muna 10 deOe ya is strony MeO r a | mations, lang38® te ors without the neg 2. server side " ‘ ¢ 10 da web Services ° : latforrn yg ‘ 2 to bytecode Ee thy orphism code into bytecoas to write code ong, s that the Ji, ne through er used by the pr a eae teaiprondele eS aa the performance of odern computers, va. Java is widely used in enterpr e and web appli among other areas, its popularity is dul technology, Java consists of; ‘oftware development kit) tuntime environment] f vate on cetware environment In hia Brogramfunaem ‘are-only platform that runs On (Sf aia lace !15.1 HISTORY OF Jaya 1 Java Is strongly associated with the Internet. Java was designed with networked environments in Here are some ways that Java is used on the Internet 1, Applets : Java applets are small programs that can be embedded in web pages and run on the client-side, Applets can be used to provide interactive content, such as games and animations, within a web page. 2. Server-Side Development : Server-side Java applications can be used for web application development, e-commerce, and database connecti 3. Web Services : Java can be used to develop web services, which are software components that can be accessed over the Internet 4, Networking : Java provides classes for networking, which allow developers to create networked applications that communicate with other applications over the Internet. 5, Security : Java has a robust security model that provides protection against malicious code and unauthorized access. Java's “write once, run anywhere” philosophy provided this advantage. 3 ADVANTAGES OF JAVA Java has several advantages that make it a popular programming language. Here are some of the key advantages of Java 1. Platform independence : Java is a platform-independent language, which means that Java code can be compiled on one platform and run on any other platform without any modifications. This is possible due to Java's compilation process, which produces bytecode that can run on any platform with a Java Virtual Machine (JVM). Object-Oriented Programming : Java is an object-oriented language, which means that it supports concepts such as encapsulation, inheritance, and polymorphism. 3. Robustness : Java has a strong memory management system that prevents memory leaks and reduces the risk of crashes. It also has a strong exception handling system that helps developers to identify and recover from errors quickly. 4, Large Standard Library ; Java comes with a large standard library that includes classes for tasks such as networking, input/output, and database connectivity. 5. Multi-threading ; Java supports multi-threading, that a single program can perform multiple tasks simuluanepiaty n performance of complex Lid applications. Security : Java has a robust signing, and encryption. but distinct software packages that are used to develop of each: 1. JDK : The JOK is a sol tools necessary to Java source code into bytecode that can be tools such as the Java debugger, the Java d JDK is typically \6 a ti \Wed by developers who are building Java applic! is id to run Jay, 2 INE The JRE is a runtime environment that 1s iyo lh My, Which Interprets the bytecode general the the Underlying hardware Written classes that ¢ Who are funning Javi 1S import istalled 6 to tun Ja RE aS well as the Java clas ‘ant to note that the JRE is N Your computer, You already have the JRE instal Va applications an 1d don’t plan on developing Jav; » Comparison, between JDK and JRE Whe: 10 and J comparison Used to develop java applications cludes the lava compiler, documentation Benerator, Typically, larger in sae due development tools an res debugger, and JavaFX SDk to additional oUrces Typically stalled on for j computers sed ava development developers tow U8 Java applications Used to devel compatible lava rite, test, and |9p Java applications With a specific ‘an be used by Java applications, The JRE fa applications on thelr computer, 4 subset of the JDK. This means that a Object Oriented Progriny “Sy a Dpllicatig mpiler ang oe which Provides 4 ' \s typically Used ty 'f You fy er, if you CAN instay lons from scratch 6 library, led as well, Howey fa applications, you Used to run Java Applications Includes the Java UVM) and Java Typically, includes ¢ fitbray Installed on ’nd-users” computary to run J ava applications Used by end S15 to run Java Applications Compatible with ay Java ay Virtual Machi class library smaller in size as it on the JVM ang Java class code that cay or 1 PE executed by any efficient, and ea 'Y to interpret by the Jvm, Figure : Journey of lava Application > .VM Is 2 platform-independent execution environment that converts Java byte code into machine language and executes it. The JVM is called “virtual machine” because it provides 3 machine interface that does not depend on the underlying operating system and hardware architecture This independence supports the write-once run-anywhere (WORA) concept of Java programs. Java Virtual Machine is 2 program that runs pre compiled Java programs, which mean JVM executes .class files (byte-code) and produces output. JVM handles following main tasks. Code Loading, Byte Code Verificati [1.6 JAVA ENVIRONMENT SETUP 1, Execution, Provided runtime environment Setting up 2 Java development environment involves installing the necessary software tools and configuring them to work together. Here are the basic steps to set up a Java environment: 1. Download and install the latest version of the Java Development Kit (JDK) from the Oracle website. The JDK includes the Java compiler, tools, and libraries required to develop Java ppokcaets This allows the system to locate: applications. 4, Create a new Java project in such as the JDK version and target platform. 5. Write and test the Java code and testing. (ject Onentes Programming with JAVA: 2023.24 9 Object Oriented Progra, INSTALLING JDK i staling JO the fis tp in Fearing Java Programing : The Java Software Development Kit (Java SOK or JOK) is an application, Create ‘Microsystems to create and modify Java programs. 3 > Steps to Setup JOK > Step 1: Downloading 10K 1. Go to Java SE download site 2 On download page, accept terms and conditions of Oracle. It’s mandatory, Object Orioutedt Programming with JAVA is Figure : java and java in jak > Step 3: Setup JOK in Computer/Setup Class Path 1, After installation is done, please note down the installed path as shown... (right click on s bar to get copy option) Figure; JAVA Path Let's refer to this JDK installed directory as Now open the properties of “My Computer” by either right-licking the icon on the desktop or right-clicking Start Of Computer, When the pop-up menu opens, scroll to the bottom and select “Properties”, 20 window. Properties” win mn “System 5 3. This ahaa “Environment Variables and the | Contra Pane! Home | W Dasic information about YOUr Come | Devceinager Windows edition Remote settings Windoss 7 Protestonal Copyright© 2000 icon ft Conran, gg Serie Packt Windows a bist Orienced Progremealegyih BAVA eee Figure: Setting path variable in “Path” value field, append “c:\Program Files\Java\jdk1. {xxx)\bin” (VERIFY that this is your followed by a semi-colon (i) 5. JDK’s binary directory) IN FRONT of all the existing directories, which separates the JDK’s binary directory from the rest of the existing directories. DO NOT DELETE any existing entries; otherwise, some existing applications may not run. at System Variable | vansble pane: Venable valve: Variable name: PATH :\Program Files\ava\jdk1._{xxx}\bin Variable value: [exiting entries]; ¢ > step 4: Verify the JDK Configuration UN 1. Launch a.€MD prompt (Click “Start” Lae 2, Provide a“ and to list the o the .. = enter “cmd”). the PATH environment variable. Check js listed in the PATH. Object Orienteg Prog, Fieue Verity the JDK Configuration ve 48V8 ~ version” and led which wi java "o verify that JOK/RE are ro ill display their Version Object Oriented Programming with JAVA 23 ———— . | lgure: Eclipse download 3, Once you are done with selection, you will be directed to the mirror selection page. Here proceed with the download by clicking on the green arrow. Eclipse downloads - mitror selection ss sis 825 4, The Eclipse setup zip file download will begin. Here, saves the file to a convenient path like C drive or your Desktop. . 5. This will finish the Eclipse download. > Step 3: Setting up Eclipse ‘simply unzip the downloaded file into a run “eclipse”, an exe application within "in the Eclipse installed directory, ‘ory path where Java development files will be saved, Object Oriented Programming JAVA 25 [Xo or FRONT PRC cys sro Eclipse Java EE IDE for Web Developers he Figure : Eclipse Workbench 5. You have now successfully loaded Workbench, now you can start Java development. > Creating Java Project 1, For every Java applicatios relevant resources ‘source files, classes and From eclipse menu, Che (Objet Ovens Programming with JAVA indow Help Jove Project Sy Projet. Package Chas © tierce © Sum Source Felder Working Set Java Wetking 3 Provide "MytieloWorid® Ww t of the Settings as it 5 agg and let the res 85 the project nam, Delo j Figure 4 Click on Next” buy Mill move to ny Sets 35 is De Ut folder ( YOU has fles Code) will be 8 i Vato SSS accentuate semaines” Buc 2 A IRESystem Libra LnvaSE-.7) 6. Itwill ask you for Java pers| sion” and click on “Ok”. lea JAVA PROGRAM STRUCTURE In Java, a program is structu ed into classes and methods. Here’s a brief overview of the Structure of a Java program: 1. Package declaration: The package declaration is the first line of code in a Java program I5 used to group related classes together. I's optional but recommended to use + name that reflects the purpose of your program. import statements: Import statements are used to import classes from other packages your program. ors of objects that belo: its superclass (if any), and the class body, 4. Main method: The main method is the entry point a\ starts executing and is defined within the clas signature that must be follo : Object Oriented Programming with JAVA 29 F, Statements and expressions: Statements and expressions are used to perform actions and manipulate data in a Java program. They can include assignments, loops, conditionals, and method calls. an example of a basic Java program that prints “Hello, world!” to the console: example; plic class HelloWorld { c static void main(String{] args) { outprintia(“Hello, world!”); ins evample, the program is in the @l] args)” signature and prints “Hello, world!” to the console sing the “System.out.println” statement. sis is just a basic overview of the structure of a Java program. In practice, Java programs can be veh more complex and may include multiple classes, packages, and dependencies 7.6.2 COMPILING AND RUNNING A SIMPLE JAVA PROGRAM Compiling and running a simple Java program involves a few basic steps: 1. Write the Java code: Use a text editor or integrated development environment {IDE) to create a Java source file with the “java” file extension. For example, create a file called “elloWorld.java” and write the following code: jass HelloWorld { tic void main(String{] args) { system.outprintin(“Hello, world”); 72. Compile the code : Use the Java compiler {javac) to compile the source ‘code into bytecode. Caen S terminal or command prompt and navigate to the directory containing the Java file. Then, run the following command : World.java file called “HelloWorld.clas reve are no errors in the code, this will generate se th al i to run the compiled program. In the command: This will execute and print “Hello, world!” to the console. “ 16.3 COMMENTS IN JAVA focument and explain your the compiler. Comm, > PES of comments in java, 1 Single Line Comment 2. Muti Une Comment 3. Documentation Comment i ~ Object Oriente be HTML files created for your Calculator class in the a there will the HTML files and see the explanation of Calculator class provideg Uren a; me Ou TM files i omment Bh gy, com come | | | | = / | Figure : Use of documentation comment 17 DATA TYPES " Java, there are two types of data : 1. Primitive Data Types: * byte, ‘short, int, toy * These data types are used to ‘present simple values, such as nu 2. Reference Data Types: "6 float, double, boolean, char Glasses, interfaces, arrays, and strings These data types are used data types, as well as oth, Here's a brief description of each primi * byte: an 8-bit integer value short: a 16-bit integer value int: @ 32-bit integer value long: a 64-bit integer value float: a single-precision * double: a double, * boolean: a true/fal to represent complex ler objects, itive data type in J . floating point value Precision floating point value Ise value char: a single character value ‘opject Oriented Programming with JAVA 33 {And here’s an example of how to declare a variable with each primitive data type: ine my Byte = 100; 5 short myShort = 10000; int mylot = 100000; Jong mylong = 1000000000L; oat myFloat = 3.146, 3.14159; poolean myBoolean = true; double myDouble = char myChar = ‘a3 > Example: Using primitive data types [Dacaypessiava public class Datatypes { public static void main(String{] args) { INTEGE System.outprintin( INTEGERS byte bl = 75; | System.outprintn(“byte value : “ + “bl = “ + bl); short st = 100; system.outprinda(“short value + “sl = “+ st); int il = 1245; system.outprintn(“int value : “+ “il = “ + it); long 11 = 70200; system out prindn(“long value: “ + “I= “+ Il); | Floating-Point Types system out,prineln(™ === Floating Point Types | doar = 1245ah C8 et: come double di = System.out pri Characters system.out pain 2 Spuemoutprinda ‘thas values: cl = "+ cl +” and 2 = “+e, Boolean Spstem.out prndia Boolean boolean; = fale Systemoutprinta(boolean value : b is “ + b); b= tue, Sysemoutpina( "boolean va : bis “ + bj, = INTEGERS byte value: bt = 75 shor value $1 = 109 int Vale : if = Object Oriented Programming with JAVA se 38 7.8.1 SCOPE AND LIFETIME OF VARIABLES — in programming, @ variable can be declared and defined inside a class, method, or block. It defines the scope of the variable i.e, the visibility or accessibility of a variable, Variable declared inside # block or method are not visible to outside. If we try to do so, we will get a compilation error: note that the scope of a variable can be nested. © We can declare variables anywhere in the program but it has limited scope. oA variable can be a parameter of a method or constructor. A variable can be defined and declared inside the body of a method and constructor. © It can also be defined inside blocks and loops. Variable declared inside main() function cannot be accessed outside the main{) function Variable Type Scope ie ~ tifetime instance variable | Troughout the class except in | Untill the object is available in the static methods memory | Class variable Troughout the class Until the end of the program Local variable | Within the block in which iti [Until the control leaves the Block in declared which it is declared The lifetime of a variable refers to how long the variable exists before it is destroyed. You can declare variables in several different places: ‘A member variable is a member of a class or an object. A member variable’s scope is the entire declaration of the class. The local variable is declared within a block of code. In general, the scope of a local variable is the block in which it was declared. Parameters are being used to pass values into methods. The scope of a parameter is the entire method. anstance variable String name = "Anand; class and static watlable static double height= 5.9; public stitic void main(String args) local variable int matks = 72; [SeopOtVarabiesjae lass ScopeOrVatiables | Static int vas { ScopeOfVariables(), € accessed from Oupus Variable Object Oriented Programming with JAVA Member Variables (Class Level Scope) These variables must be declared inside class (outside any function] They can be directly accessed anywhere in class, Member variables can be accessed outside a class with following rules Modifier World Package Subclass public Yes Yes Yes protected Yes Yes No | Default (no modifier) Yes No No private No No No. Local Variables (Method Level Scope) x Variables declared inside a method have method level scope and can’t be accessed outside the method, 1.8.2. DEFAULT VARIABLE INITIALIZATIONS Following table shows variables types and their default values “Table : variables types and their default values Data Type Default Value Boolean False char \uoo00 int, short, byte / long | 0 / OL float /double O.0f / 0.04 any reference type Null Here, char primitive default value is \u0000, which means blank/space character. [1.9 OPERATORS Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc. > Java operators can be classified as: Unary: Takes one argument. The (postfix) its argum Binary: Takes Ternary: Take pear before (prefix) its argument or after between its arguments. between its arguments. xprt+ expr— | expr —expr texpr-expr > ! object Oriented Programming with JAVA 15 39 > Java Arithmetic Operator Example: Expression FrimedcExample class Arithmeti ample2 { public static void main(String args) { system outprintin(10*10/5+3-1*4/2), y wpa a > Java Unary Operator Example: ++ and — TrithmedcBxample3 java class ArithmeticExample3 { public static void main(String args{}){ int x=105 System.out println(s++);//10 (11) System.outprintin(++3)3//12 )3//12.(11) ystem.out printin System.outprintin(—x);//10 Oupue 1.9.2 BITWISE Java defines several short, char, and byte. Bit Table lists the bitwise 0} integer types, long, int, tby-bit operation. fist ieseiieeeinteesenes Operator & (bitwise and) J (wise 0 * (wise XoR), * (bitwise Compliment) SS (left shit) }>> (right shift) Table ; bitwise operators Binary AND Operator copies a bit to the res loperands, ult if it Binary OR Operator copies a bit if it exists in eithe, Binary XOR Operator copies the bit if it is not both, Binary Ones Com tipping’ bits, Binary Left shift Operator, The left operands Value j the number of bits specified by the right operand, Binary Right Shift Operator, The left operands by the number of bits Value ig i tight zero fi by Specified by the right perand, Operator. The lef ber of bits specified by {aes are fled up with 2et0s, Per Set in ong 4 plement Operator is unary and hag the « Object Oriented Programming with JAVA [Oompa Jo | | Io ce Shift Operator Example: >> vs >>> [RighiSninOperstor2java | os RightShiftOperator2 { bobitive fiUtnbe 1 and works same Ourpue | 1073741819 3 RELATIONAL there are following relational operat ‘ors supported by Java language ‘Table : Relational operators ifyes then condition | ot, if values are not | are equal or m | I= (not equal to) ? (greater than) ue than the v alue of right greater than the v alue of right operand, < (less than) than or equal to the value of true >= (greater than © n or equal to the value of ri or equal to) ight <= (less than OF | equal to) Object Oriented Program, a AMA LOGICAL } Table lists the logical operators, aur Description sf h the operands are non. AW Toate ond) PCa Logical AND operator. I bot ~~ Peonalion becomes tes two operands are non am NV Wogicat or) | catted Logical OR Operator. if any of the 20 the condition becomes true, 2er0, res the logical St "Wotieal nat) | called Logleal Not Operator, Use to reve If rator will Sperand, Wa condition is trve then Logical NOT ope: Make fy rn : & and Bitwise & AND Operatol Example: Logleal The logical && Operator doesn't check Second condition Only if fist one ig true, Jav. econd condition if first condition is false, It The bitwise Perator always cheeks both condition LopicatieWise jana 's whether first condition is true op ‘T885 LogicalleWiget Public static void main(String angsty intamto, int bes, int €=29 System. out.prindn(astaes System.out print Ise 88 true false False & true naSb&ace false System out printla(a beat Hey, false && true System out printha a false 10 because second Condition is not cheeked) System out pring SbRAY+< 0:7 /faee && true = falge System out printing) because second condition is checked ject Oriented Programming with JAVA, Sha OR Operator Example: Logical || and Bitwise | The logical || operator doesn’t check second condition if first condition is true. It checks second. condition only if first one is false. The bitwise | operator always checks both conditions whether first condition is true or false. ogi ave cas public static void main(String args[){ inta=10; int b=5; 0; ogicalBitWise3.{ inte gystemoutprintln(a>b| |ab |ab| |a++b|a++ do..while Loops Oo ... loops run the | like this: When i=5 loop will be Statement block; } while (condition); + Bample: A simple Object Oriented Programmin, 4 86 Say, = — ST chss DoTest { j Public static void main (String argsf}) { | invis yy x YSeM.Out.printin(“Loop No” + ); | } while ( <= 9) | Ougpee | Loop No : 1 | Loap No : 2 | Loop No : 3 | | Loop No : 4 Loop No : 5 > For Loop Construct The most complex of the 100, The “for” loop is often number of times, P statements is for, \sed where you want to repeat a section of a’program for a fixed | © = Syntax: for (initialization; { 5 termination; increment) statements; Initialization: is a statement that Ini beginning of the loop. © Termination: is an expression that determines when t the expression evaluates to false, the loop terminates, Increment: gets invoked for each iteration through components can be empty statements, + Example: Using for loop ForUse java public class ForUse{ public static void main (String. args|)) Pi ing with oriented Programming with JAVA 7 one JUMP STATEMENTS sumbers betwee 115 “sing statements are control re int in the program. eee that transfer execution control from one point to Yr famming language fe two Jump statements that are provided in the Java greak statement. 1151 BREAK Continue statemer satement i statement ends a loop immediately even if the condition being tested is still true. Example FeckDemo java cass BreakDemof lc static void main(Sting int ] oumbers = {102m foriat x : numbers ) { Using break statement 15.2 CONTINUE The continue sta “ Object Oriented Programm [ContineeDemo iva Example: Using Continue Statement public class ContinueDemo{ public static void main(String args{]) { int {] mumbers = (10, 20, 30, 40, 50}; | forfint x : numbers ) { | iff 30) { po aages \ } | System.out print( x ); System. out print(“\n"); | j bee | | | } You can use the break and Continue statements with all three kinds o }1.15.3 RETURN A return keyword is used to finish the execution of a method. return ; The value returned by return must match the type of methods deck When 2 method is declared void use the form of return that doesn’t rum ; 1.16 ARRAYS Asray is a collection of similar type of data. An array is an indexed of same data values. ” Oriented Progeamining with JAVA jie TYPES OF AIMAYS are three types of arrays in java here ingle Dimensional Array multidimensional Array Non-Rectangular Arrays single Dimensional Array afining and Constructing one y pefining tructing one dimensional array ‘array Declaration | t t syntax: Jaarypel | identifier; or Jaatype identifier| Js Goth are valid syntax for array declaration, But the former is more réadable. Example (] a har[ } arty short{ } ant; gl | atts inf Jf] ary 1/20 + initialization of Art o new operator is Example: int{ ] resultArray = within square brackets. You can initialize All array indexes ger value 69. This will initialize Array elements can b ‘Accessing array el Object Orienteg Sy » AS aventioned earlier array index starts from 0. To access nth a Syntax atravnamelncl) oF Daigo Rae A ener sie ray (1 esukitray © RNEAARIRE Systemous, priniln(*Blement A Ath place” + resultArray(3)}; above code wil print th we ath element of array arr on consoley Mle: Sin, gle Dimensiona Tae Dimensional aay mys []) 0,50,60,90}; Programming with JAVA ot ence Nene a ee ees ‘s have look at below program to understand 2-dimentional array Giovawray Demo = <'IwoDimArrayDemo { oni f pute peste void man (Sting aga) } qc ewoDim []) = new ine (2][3}; | scien O1[01=18 pvoDim[01[} vob im|0][21>35 twoDim(t][0] twoDim(t][1 ewoDim(t][21=65 gystem.out printin(ewoDim|o}(0] +" + qwoDimfo]ft] +" + ewoDim[O}2); gystem.out printin(owoDim[t][0] +”” + twoDim[t}[1] +”” + ewoDim[t}2): wpa NonRectangular Arrays in non-rectangular arrays number of rows elements are fixed, but number of colu row are different. mns for each in Java it is co We can allocate Example: Non-Rt nrarray.java class nrarray Programming with JAVA we look at below program to understand 2-dimentional array je ess TwoDIMATTayDemo { pay sti voidl main (Sting [ng inc ewoDim []] = new int [2]; evoDdim[O}(01=15 ewoDim [0] }— gwoDim(01(2} ewoDimn (1101 _woDimt}(1=55 | woDim[t][21=6 System ounpeintn (ewe aI FOOD eee | systemout printin(twoDim|t}[0] +" + ewoDim[t][1] +” + ewoDienf 12) |) ous 4356 on-Rectangular Arrays n-rectangular arrays number of rows elements are fixed, but number of columns for each In not row are different. int arrayl{ JL int array2f JL in Java it is compl We can allocate Example: Non-R wareayva class aratay public static void int art{ }[ J=new ine{5][ ]s arr{0]=new int{l}; arr[l]=new int{2); arr[2|=new int{3]; art[3]=new int(4]; 3 4 4 arr[4]=new int(5]; for(int i=0i<=4i++) { x for(int jr0j fi lize() method a * The finalize() method is invoked each time before the « 4 10 perform cleanup * This method is defined in Object clase as proweted vold finalize} jented Programming pet! o a a 1 system e , 241 : 4 re? yet roa id Java contro! str “4a following |S not vali - myattrcase 4. which of the xr a itelse do-hile me: it it of the following Java 5, What is the outpu - inl) eryaray = (1 2), 8 41h System.out. printin(nyArray(](0)) at : d4 es Hello “ + “World”? 6. What is the result of the following Java expression: Hello 2. “Hello World’ b. “HelloWorld” ©. "WorldHello” d. compile error What is the output of the following Java code? int i= 0; whilefi < 10) { System.out.print(i +“ "); 0s da Which of the he fol ‘5 not a valid Java data @. boolean wing. © string 10. What is the output of the i] myArray = (1, > 3 int sum = o, eek fortint int = 051 < myArray.ten ath; it, Sim + mysrayy “4 } Syst SM.OUt printin( “sy * sum); sors With JAVA, niet gn Oe attncaverage: "+ (Sum / myArraylengihiiy ya 1X0 Averages 2.5 b. Sum: 10 Average: 2 Ng averages 4. Sum: 4 Average! 2.5 [answers to megs | aa a had Bee ti na & d % ¢ 10. b [sh FE Questions | 2 Marks te the difference between Procedure v/s Objected Oriented Language: Oriented Programming proced NING |_ Object Oriented Programmin, —op program is divided into small th OOP, program is divided into parts sas called funetions, called objects. por, Importance Is given to functions, | In OOP, Importance is given to the data rather than procedures. por follows Top Down approach, OOP follows Bottom Up approach. ple: C, V8, FORTRAN. Example: C+, JAVA, VB.NET. st the different OOP concepts, os there are following different concepts of OOP := anstraction Encapsulation inheritance: Polymorphism Why Java does not support ans: Some reasons for java does: Security Passing argument by Manual Memory Mat 4 Describe Byte Code. BB isi called bytecode. ee The Java compiler trans Java bytecode is not the | An interpreter (JVM), tf Uist any four Features of Jav Of Platform Independent Secure & Multithreaded ete, 6 Describe Applet Ans nsmitted over the Inter, pplication designed to be tra iq An applet is an appl SO heeier atible Web brow: & devecompatl fam dynamically downloaded AN applet is actually a small Java program, ; Be, Sound file, or video clip just lke an image, sox Ms hic mand of Write only compile command and run comi Ans: Compile command for testjava file: javac test java 2 Kun Command for testjava file java test 8. Define class and object Ans: > Class: Glass 's user defined data "Ye and behaves like the builtin "Ypes of aprogramming la biects are variable of type class Once: a class is define, Me CaN create number of objects belonging to that class > Object An Object is instance of class APY Variable having cage ‘YPe that know as object 8. _ Define Source co, Ans. 4 Programmers write Series of ing Programs kno le 10. How Java is str Ans: Java is stron Java was Hot Jy An applet is ion designed t jvorcompatibie Web brome wan, APIs actually a sma Java program, Just like an, image, sound file, or video clip, In other Words, an applet |S @ program that can ‘a A att Fun the same animate sound over 11 HOW Java" W secily Portable Ans: than other language, § “ Tava'ls Secure because it does not memory poi priented Programming with JAVA 69 q yoommmitremminvinis ee aable by human also, It contains Garbage Collector, Exception Handling, Bytecode Verifier and Security Manage! ane is Portable Deeaute Byte-coueigerieratedby.Jave compllaican e:kied On any machine, portable means applications oF program will be un on any machine or Operating System. txplain Data Abstraction & Encapsulation, ns Ane pata Abstraction: nstraction separate: ; Aust rt specification (or interface) from implementation of class pstraction refers to a aaa as tof representing essential features without including the background etal > pata Encapsulation: The wrapping of the data and fun, ction t encapsulation ‘ogether into a single unit class, is known as Encapuslation provides Data Hinding Conce; pts Using Class. 3, Java is a Platform . Language ans: Independent. 4. Describe JVM in Java, ans: > IM JVM Stands for Java Virtual Machine Java Virtual Machine is a’ program that JVM executes .class files The Java compiler t An interpreter (JVM), uns pre-compiled Java programs, which mean epresentation called bytecode andexecutes it Ans: ) i i ites its call by any object from a J ~ Where, public keyword indica b ana, idea et method is class method, which can be calleg Withoys Se, of class, void indicates method doesn’t return any value and String 4 argument, Questions ing esl) ig Uist basic concepts of OOP. Explain any one, 2. Write syntax to compile and execute Java program 3. Explain Java's All feature in brief . 4. Describe the Structure of a typical Java program. “ 5. Explain following () Byte Code i) VM Ui) Platform independent (iy) Portal a Applet. hy What are Java Operators ? Ye 6 ¥ 8 5: el ¢ Oriented Programming with JAVA onjee! 71 10 uu 12. Ginat is the instanceof operator in Java and ki iow is it used? what are the assignment operators in Java ow do you break out of a loop in Java? DUS PS a fou conti ow do : continue to the next iteration of a lo tis the synta Jouneniels what th 2 x for a try-catch block in Java — = t What is the difference between checked and unche ee ese cked exceptions in Java? jow do you use the return statement im, ene y return statement to control progr : am flow in Java? UNIT 1 ASSIGNEMNTS Write a Java program that declar es and average. three integer variables (a, b, c) and computes their sum write a Java program that decla res tw . area of a circle. 0 double variables (radius, area) and computes the Write a Java program that takes two i 0 i i operations: addition, subtract integer inputs (a and b) and performs the following D ‘ion, multiplication, division, and modulo. ite a Java progral i ’ ye a cae ae takes a temperature input in Celsius and converts it to Fahrenheit, ite @ Java program that takes an integer input (n) and prints out the first n terms of th Fibonacci sequence. ferms of the Write a Java program that uses a for loop to it jp to iterate over an int um of all its elements. pa an integer array and computes the Write a Java program. that ' ‘ : erate over an integer array and compute the product of all its elt Shad ae Write a Java program that the maximum value. Write a Java program that | ‘on a given integer input ( array and computes ‘of the week base¢

You might also like