Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
41 views
OOPJAVA
OOPS THROUGH JAVA FOR BTECH II YEAR
Uploaded by
Palla Srija
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save OOPJAVA For Later
Download
Save
Save OOPJAVA For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
41 views
OOPJAVA
OOPS THROUGH JAVA FOR BTECH II YEAR
Uploaded by
Palla Srija
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save OOPJAVA For Later
Carousel Previous
Carousel Next
Save
Save OOPJAVA For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 139
Search
Fullscreen
J.B.INSTITUTE OF ENGINEERING & TECHNOLOGY UGC AUTONOMOUS Bhaskar Nagar, Moinabad (M), RR Dist, Telangana-500075 ° OBJECT ORIENTED PROGRAMMING THROUGH JAVA (Common to CSE, IT & ECM) B.Tech. IT L T-P-D C I Year I- Semester 3 00-0 3 Course objectives: students will : Familiar with constructors and string handling functions Explain inheritance and polymorphism. Familiar with packages and interfaces Familiar with exception handling and multithreading Familiar with applet programming, event handling and scripting. Course outcomes: At the end of the course, students will be able to: Familiar with constructors and string handling Understand inheritance and polymorphism Understand packages and interfaces Understand exception handling and multithreading Understand applet programming wpeONe Wsene UNIT — Introduction: OOP concepts, history of Java, Java buzzwords, data types, variables, scope and life time of variables, arrays, operators, expressions, control statements, type conversion and casting, simple java program. Classes and Objects: concepts of classes, objects, constructors, methods, this keyword, garbage collection, overloading methods and constructors, parameter passing, recursion. String handling: String, String Buffer, String Tokenize. UNIT - Ti: Inheritance: base class object, subclass, member access rules, super uses,using final with inheritance, method overriding, abstract classes Interfaces: defining an interface, implementing interface, differences betweenclasses and interfaces and extending interfaces. Packages: Defining, creating and accessing a package, importing packages,access control, exploring package - java.io UNIT — Il: Exception handling: concepts of exception handling, benefits of exception handling, exception hierarchy, checked and unchecked exceptions, usage of- try, catch, throw, throws and finally, built in exceptions, creating own exception sub classes. Multithreading: differences between multi-threading and multitasking, thread life cycle, creating threads, synchronizing threads, daemon threads, thread groups. UNIT - Iv: Applets: concepts of applets, differences between applets and applications, life eycle of applet, types of applets, creating applets, passing parameters to applets. Event Handling: events, event sources, event classes, event listeners, delegation event model, handling mouse and key board events, adapter classes. The AWT class hierarchy, user interface components-labels, buttons, canvas, scrollbars, text components, checkbox, checkbox groups, choices, listsUNIT -V: Layout manager: layout manager types-border, grid, flow, card and grid bag. Swing Introduction, limitations of AWT, components, containers, Exploring swing- JApplet, JFrame and JComponent, Icons and Labels, Text fields, buttons — The Button class, Checkboxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll Panes, Trees and Tables. TEXT BOOKS: 1. Java The complete reference, 8th editon, Herbert Schildt, TMH. 2. Understanding OOP with Java, up dated edition, T.Budd, Pears oneducation. REFERENCE BOOKS : 1, An Introduction to programming and OO design using Java, J. Ninoand FA. Hosch, John Wiley & sons, 2. An Introduction to OOP, second edition, T.- Budd, pearson education, 3. Introduction to Java programming 6th edition, Y. Daniel Liang, pearson education,Java — James Gosling James Gosling is a famous Canadian software developer who has been with Sun Microsystems since 1984 and is considered as father of Java programming language Gosling did the original design of Java and implemented its original compiler and virtual machineUNIT-I INTRODUCTION History of Java: In 1990, Sun Micro Systems Inc (US) was conceived a project to develop software for consumer electronic devices that could be controlled by a remote This project was called Stealth Project but later its name was changed to Green Project, In January 1991, Project Manager James Gosling and his team members Patrick Naughton, Mike Sheridan, Chris Wrath, and Ed Frank met to discuss about this project Gosling thought C and C++ would be used to develop the project But the problem he faced with them is that they were system dependent languages The trouble with C and C++ (and most other languages) is that they are designed to be compiled for a specific target and could not be used on various processors, which the electronic devices might use James Gosling with his team started developing a new language, which was completely system independent This language was initially called OAK Since this name was registered by some other company, later it was changed to Java James Gosling and his team members were consuming a lot of coffe while developing this language Good quality of coffee was supplied from a place called “Java Island Hence they fixed the name of the language as Java The symbol for Java language is cup and saucer Sun formally announced Java at Sun World conference in 1995 On January 23" 1996, JDK10 version was released Features of Java (Java buzz words) Simple: Learning and practicing java is easy because of resemblance with ¢ and C++ Object Oriented Programming Language: Unlike C++, Java is purely OOP Distributed: Java is designed for use on network; it has an extensive library which works in agreement with TCP/IP Secure: Java is designed for use on Intemet Java enables the construction of virus-free, tamper free systems Robust (Strong/ Powerful): Java programs will not crash because of its exception handling and its memory management features Interpreted: Java programs are compiled to generate the byte code This byte code ean be downloaded and interpreted by the interpreter class file will have byte code instructions and IVM which contains an interpreter will execute the byte code Portable: Java does not have implementation dependent aspects and it yields or gives same result on any machine Architectural Neutral Language: Java byte code is not machine dependent, it can run on any machine with any processor and with any OS High Performance: Along with interpreter there will be JIT (Just In Time) compiler which enhances the speed of execution Multithreaded: Executing different parts of program simultaneously is called multithreading This is an essential feature to design server side programs Dynamic: We can develop programs in Java which dynamically change on Internet (eg: Applets)Obtaining the Java Environment: We can download the JDK (Java Development Kit) including the compiler and runtime engine from Sun at: http://javasuncom/javase Install JDK after downloading, by default JDK will be installed in C:\Program Files\Java\jdk150_05 (Here jdk150_05 is JDK"s version) Setting up Java Environment: After installing the JDK, we need to set at least one environment variable in order to able to compile and run Java programs A PATH environment variable enables the operating system to find the JDK executables when our working directory is not the JDK’s binary directory Setting environment variables from a command prompt: If we set the variables from a command prompt, they will only hold for that session To set the PATH from a command \Program Files\Java\jdk150_05\bin;%PATH% TERE) eet Ee eee CeCe eee CeCe MNES TEN Setting environment variables as system variables: If we set the variables as system variables they will hold continuously © Right-click on My Computer © Choose Properties © Select the Advanced tab © Click the Environment Variables button at the bottom aut © In system variables tab, select path (system variable) and click on edit bution © A window with variable name- path and its value will be Sanborn displayed © Don’t disturb the default path ect value that is appearing and just renin cae append (add) to that path at the cerL0 20 end: :CAProgramFiles\ava\ ‘jdk150_05\bin; o Finally press OK buttonProgramming Structure Comments: Comments are description about the aim and features of the program Comments increase readability of a program Three types of comments are there in Java: Single line comments: These comments start with // eg: // this is comment line Multi line comments: These comments start with /* and end with */ eg: /* this is comment line*/ Java documentation comments: These comments start with /** and end with */ These comments are useful to create a HTML file called API (application programming Interface) document This file contains description of all the features of software Structure of the Java Program: As all other programming languages, Java also has a structure The first line of the C/C'-+ program contains include statement For example,
is the header file that contains functions, like printf (), scanf () ete So if we want to use any of these functions, we should include this header file in C/ C++ program Similarly in Java first we need to import the required packages By default javalang* is imported Java has several such packages in its library A package is a kind of directory that contains a group of related classes and interfaces A class or interface contains methods Since Java is purely an Object Oriented Programming language, we cannot write a Java program without having at least one class or object So, it is mandatory to write a class in Java program We should use class keyword for this purpose and then write class name In C/C++, program starts executing from main method similarly in Java, program starts executing from main method The retum type of main method is void because program starts executing from main method and it returns nothing Sample Program: J/A Simple Java Program import javalangSystem; import javalangString; class Sample { public static void main(String args[]) { 3 ‘Systemoutprint ("Hello world"); Since Java is purely an Object Oriented Programming language, without creating an object, to a class it is not possible to access methods and members of a class But main method is also a method inside a class, since program execution starts from main method we need to call main method without creating an object Static methods are the methods, which can be called and executed without creating objects Since we want to call main () method without using an object, we should declare main ()method as static JVM calls main () method using its Classnamemain () at the time of running the program.JVM is a program written by Java Soft people (Java development team) and main () is the method written by us Since, main () method should be available to the IVM, it should be declared as public If we don"t declare main () method as public, then it doesnt make itself available to JVM and JVM cannot execute it JVM always looks for main () method with String type array as parameter otherwise JVM cannot recognize the main () method, so we must provide String type array as parameter to main () method A class code starts with a {and ends with a} A class or an object contains variables and methods (fimnctions) We can create any number of variables and methods inside the class This is our first program, so we had written only one method called main () Our aim of writing this program is just to display a string “Hello world” In Java, print () method is used to display something on the monitor A method should be called by using objectnamemethodname () So, to call print () method, create an object to PrintStream class then call objectnameprint () method An alternative is given to create an object to PrintStream Class ie Systemout Here, System is the class name and out is a static variable in System class out is called a field in System class When we call this field a PrintStream class object will be created internally So, we can call print() method as: Systemoutprint (“Hello world”); printin () is also a method belonging to PrintStream class It throws the cursor to the next line after displaying the result In the above Sample program System and String are the classes present in javalang package Escape Sequence: Java supports all escape sequence which is supported by C/ C++ A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler When an escape sequence is encountered in a print statement, the compiler interprets it accordingly [Escape Sequence Description t Tnsert a tab in the text at this point 0 Tnsert a backspace in the text at this point in Tnsert a newline in the text at this point r Insert a carriage return in the text at this point Tnsert a form feed in the text at this point Insert a single quote character in the text at this point yracter in the text at this point ter in the text at this point Tnsert a double quote v Insert a backslash chara Creating a Source Fil Type the program in a text editor (ie Notepad, WordPad, Microsoft Word or Edit Plus) We can launch the Notepad editor from the Start menu by selecting Programs > Accessories > Notepad In a new document, type the above code (ie Sample Program) Save the program with filename same as Class_name (i¢ Samplejava) in which main method is written To do this in Notepad, first choose the File > Save menu item Then, inthe Save dialog box: Using the Save in combo box, specify the folder (directory) where you'll save your file In the File name text field, type "Samplejava", including the quotation marks Then the dialog box should look like thi aa My Computer eg =. eens S My Newok Save ctype: | Text Document (tt) Se [aust ‘Now click Save, and exit Notepad Compiling the Source File into a class Fil To Compile the Samplejava program go to DOS prompt We can do this from the Start menu by choosing Run and then entering cmd The window should look similar to the following figure | The prompt shows current directory To compile Samplejava source file, change current directory to the directory where Samplejava file is located For example, if source directory is JQR on the D drive, type the following commands at the prompt and press Enter: fs See nee a pos\sak Now the prompt should change to D:IQR> At the prompt, type the following command and press Enter javac Samplejavaccs Leb] PSE etd TED 4 a The compiler generates byte code and Sampleclass will be created Executing the Program (Sampleclass): To run the program, enter java followed by the class name created at the time of compilation at the command prompt in the same directory as java Sample ccs TELx| oad The program interpreted and the output is displayed The Java Virtual Machine: Java Virtual Machine (JVM) is the heart of entire Java program execution process First of all, the java program is converted into a class file consisting of byte code instructions by the java compiler at the time of compilation Remember, this java compiler is outside the JVM This class file is given to the JVM Following figure shows the architecture of Java Virtual Machine ‘clase loader subsystem hhenp E | Ee class files method native | native method | o execution method engine |__aaerface Hbraries Figure: The internal architecture of the Java virtual machine In JVM, there is a module (or program) called class loader sub system, which performs the following instructions: First of all, it loads the class file into memory ‘Then it verifies whether all byte code instructions are proper or not If it finds any instruction suspicious, the execution is rejected immediately10 -lf the byte instructions are proper, then it allocates necessary memory to execute the program This memory is divided into 5 parts, called run time data areas, which contain the data and results while running the program These areas are as follows: ‘0 Method area: Method area is the memory block, which stores the class code, code of the variables and code of the methods in the Java program (Method means functions written in a class) o Heap: This is the area where objects are created Whenever JVM loads a class, method. and heap areas are immediately created in it © Java Stacks: Method code is stored on Method area But while running a method, it needs some more memory to store the data and results This memory is allotted on Java Stacks So, Java Stacks are memory area where Java methods are executed While executing methods, a separate frame will be created in the Java Stack, where the method is executed JVM uses a separate thread (or process) to execute each method © PC (Program Counter) registers: These are the registers (memory areas), which contain memory address of the instructions of the methods If there are 3 methods, 3 PC registers will be used to track the instruction of the methods © Native Method Stacks: Java methods are executed on Java Stacks Similarly, native methods (for example C/C++ functions) are executed on Native method stacks To execute the native methods, generally native method libraries (for example C/C++ header files) are required These header files are located and connected to IVM by a program, called Native method interface Execution Engine contains interpreter and JIT compiler which translates the byte code instructions into machine language which are executed by the microprocessor Hot spot (loops/iterations) is the area in class file ie executed by JIT compiler JVM will identify the Hot spots in the class files and it will give it to JIT compiler where the normal instructions and statements of Java program are executed by the Java interpreter Naming Conventions, Data Types and Operators Naming Conventions: Naming conventions specify the rules to be followed by a Java programmer while writing the names of packages, classes, methods ete Package names are written in small letters eg: javaio, javalang, javaawt ete +h word of class name and interface name starts with a capital eg: Sample, AddTwoNumbers Method names start with small letters then each word start with a capital eg: sum (), sumTwoNumbers (), minValue () Variable names also follow the same above method rule eg: sum, count, totalCount Constants should be written using all capital letters eg: PI, COUNT Keywords are reserved words and are written in small letters eg: int, short, float, public, voidi Data Types: The classification of data item is called data type Java defines eight simple types of data byte, short, int, long, char, float, double and boolean These can be put in four groups: Integer Data Types: These data types store integer numbers [Data Type jemory size Range Byte I byte 28 to 127 Short P bytes [32768 to 32767 Int [bytes [2147483648 to 2147483647 Long! IB bytes -9223372036854775808 to 9225372036854775807 eg: byte mo = 10; Jong x = 150L; L means forcing JVM to allot 8 bytes Float Data Types: These data types handle floating point numbers [Data Type jemory size Range Float H bytes [34038 to 3438 [Double [8 bytes [172308 to 17308 ‘g Hloat pi~ 3142f, double distance = 198e8; Character Data Type: This data type represents a single character char data type in java uses two bytes of memory also called Unicode system Unicode is a specification to include alphabets of all international languages into the character set of java [Data Type jemory size [Range [Char i bytes to 65535 eg: char ch= "x" Boolean Data Type:can handle truth values either true or false eg:- boolean response = true; Operators: An operator is a symbol that performs an operation An operator acts on variables called operands Arithmetic operators: These operators are used to perform fundamental operations like addition, subtraction, multiplication ete Operator Meaning Example Result + ‘Addition B+4 7 = Subtraction =7 2 ] ¥ Multiplication = 25 ] Division (gives quotient) [477 2 % ‘Modulus (gives remainder) B0 %7 6 ‘Assignment operator: This operator (~) is used to store some value into a variable imple Assignment Sompound Assignment =xty =y Ixy ay X=xy zy Unary operators: As the name indicates unary operator’ act only on one operand12 ‘Operator Meaning | Example Explanation Unary minus [j=-k; __|k value is negated and stored into ] b value will be incremented by I Increment | b++; | (called as post incrementation) Operator +b; b value will be incremented by 1 (called as pre incrementation) b value will be decremented by 1 Decrement (called as post decrementation) Operator b value will be decremented by 1 (called as pre decrementation) Relational operators: These operators are used for comparison purpose Operator Meaning [Example E Equal Not equal Less than E Greater than Ee Less than or equal to Logical operators: Logical operators are used to construct compound conditions A ‘compound condition is a combination of several simple conditions Operator] Meaning [Example Explanation iffa>b && ac) Ifa value is greater than b and ¢ Wea and operator {Systemoutprint(“yes”); | then only yes is displayed iffa—1 || =1) Ifeither a value is 1 or b value is 1 or operator [Systemoutprint(“yes”); | then yes is displayed iff (a0) ) Ifa value is not equal to zero then not operator {Systemoutprint(“yes' only yes is displayed13, Bitwise operators: These operators act on individual bits (0 and 1) of the operands They act only on integer data types, ie byte, short, long and int ‘Operator Meaning Explanation & Bitwise AND Mulliplies the individual bits of operands fl Bitwise OR Adds the individual bits of operands a Bitwise XOR Performs Exclusive OR operation ze Left shift Shifis the bits of the number towards leit a specified number of positions b> Right shift ‘Shifts the bits of the number towards right @ specified number of positions and also preserves the sign bit [>>> Zero fill right shift Shifts the bits of the number towards right a specified number of positions and it stores 0 (Zero) in the sign bit Bitwise complement | Gives the complement form of a given number by changing 0"s as 1"s and vice versa ‘Ternary Operator or Conditional Operator (? acts on 3 variables The syntax for this operator is Variable = Expression!? Expression2: Expression}; First Expression| is evaluated If it is true, then Expression2 value is stored into variable otherwise Expression3 value is stored into the variable eg: max =(a>b) 2a: b; This operator is called ternary because it Program 1: Write a program to perform arithmetic operations //Addition of two numbers class AddTwoNumbers { public static void mian(String args(]) {int 1-10, j-20; Systemoutprintin(""Addition of two numbers is : " + (i+))); Systemoutprintln("Subtraction of two numbers is :" + (-j))s ystemoutprintn( "Multiplication of two numbers is : "+ (i*))); Systemoutprintin("Quotient after division is : "+ (if) ); Systemoutprintin("Remainder after division is : " +(i%j) ); } Output: FOR eee Cer ferrets Recreate juotient after division Brestnies4 Program 2: Write a program to perform Bitwise operations //Bitwise Operations class Bits {public static void main(String args{]) {byte xys x=10; yall; Systemoutprintin Systemoutprintin Systemoutprintin ("x | y="+(xly))s Systemoutprintin _(" "4(xy))s Systemoutprintin Systemoutprintin Ee Cees1s. Control Statements Control statements are the statements which alter the flow of execution and provide better control to the programmer on the flow of execution In Java control statements are categorized into selection control statements, iteration control statements and jump control statements Java’s Selection Statements: Java supports two selection statements: if and switch These statements allow us to control the flow of program execution based on condition if Statement: if statement performs a task depending on whether a condition is true or false Syntax: if (condition) statement]; else statement2; Here, each statement may be a single statement or a compound statement enclosed in curly braces (that is, a block) The condition is any expression that returns a boolean value The else clause is optional Program 1: Write a program to find biggest of three numbers ‘Biggest of three numbers class BiggestNo {public static void main(String arg {int a=5,b=7,0=6; if (a > b && a>c) ‘SystemoutprintIn ("a is big"); else if (b> 0) ‘Systemoutprintin ("b is big"); else ‘SystemoutprintIn ("e is big"); eee nS ENC SS Romeo y Switch Statement: When there are several options and we have to choose only one option from the available ones, we can use switch statement Syntax:switch (expression) {case valuel: //statement sequence break; case value2: _//statement sequence16 break; case valueN: //statement sequence break; default: //default statement sequence Here, depending on the value of the expression, a particular corresponding case will be executed Program 2: Write a program for using the switch statement to execute a particular task depending on color value To display a color name depending on color value class ColorDemo {public static void main(String args[]) {char color =. switch (color) { case," Systemoutprintln (“red”); break; case 2: Systemoutprintin (“green”); break; case ,b": Systemoutprintln (“blue”); break; case Systemoutprintin (“yellow”); break; case ,,w": Systemoutprintin (white”); break; default: Systemoutprintin (“No Color Selected”); } t Output: Sees Sees street Java’s Iteration Statements: Java's iteration statements are for, while and do-while These statements are used to repeat same set of instructions specified number of times called loops A loop repeatedly executes the same set of instructions until a termination condition is met while Loop: while loop repeats a group of statements as long as condition is true Once the condition is false, the loop is terminated In while loop, the condition is tested fi if it is true, then only the statements are executed while loop is called as entry control loop Syntax:while (condition) t statements; }wv Program 3: Write a program to generate numbers from 1 to 20 [Program to generate numbers from | to 20 class Natural {public static void main(String args{]) fint i=1; while (i <= 20) {Systemoutprint (i + “\t”); i+; do...while Loop: do... while loop repeats a group of statements as long as condition is true In dowhile loop, the statements are executed first and then the condition is tested do....while loop is also called as exit control loop Synta: statements; } while (condition); Program 4: Write a program to generate numbers from 1 to 20 [Program to generate numbers from 1 to 20 class Natural {public static void main(String args{]) fint 1; do {Systemoutprint (i+ “\"); } while (i <= 20); } } Output: See a Asa CCST Pees So18 The for loop is also same as do...while or while loop, but it is more compact syntactically The for loop executes a group of statements as long as a condition is true Syntax: for (expression! ; expression2; expression3) { statements; 3 Here, expression is used to initialize the variables, expression2 is used for condition checking and expression’ is used for increment or decrement variable value Program 5: Write a program to generate numbers from 1 to 20 [Program to generate numbers from I to 20 class Natural {public static void main(String args{]) flint is for (i=1; i<=20; i++) Systemoutprint (i+ “\t”); Java’s Jump Statements: Java supports three jump statements: break, continue and return These statements transfer control to another part of the program © break: break can be used inside a loop to come out of it break can be used inside the switch block to come out of the switch block break can be used in nested blocks to go to the end of a block Nested blocks represent a block written within another block Syntax: break; (or) _break Jabely//here label represents the name of the block Program 6: Write a program to use break as a civilized form of goto Musing break as a civilized form of goto class BreakDemo {public static void main (String args[]) {boolean t = true; first: { second: third: {19 Systemoutprintin (“Before the break”); if (0) break second; // break out of second block SystemoutprintIn (“This won't execute”); SystemoutprintIn (“This won't execute”); } ‘Systemoutprintin (“This is after second block”); TEC see I ee ee aes ae nd Bl This statement is useful to continue the next repetition of a loop/ iteration When continue is executed, subsequent statements inside the loop are not executed Syntax:continue; Program 7: Write a program to generate numbers from 1 to 20 J/Program to generate numbers from I to 20 class Natural {public static void main (String args[]) fint i=l; while (true) {Systemoutprint (i+ “\t”); i++; if G <= 20) continue else break; Javac Natural.Java TO Sere ste ier20 return statement: return statement is usefull to terminate a method and come back to the calling method return statement in main method terminates the application return statement can be used to return some value from a method to a calling method Syntax:return; (or) return value; // value may be of any type Program 8: Write a program to demonstrate return statement (Demonstrate return class ReturnDemo {public static void main(String args[]) {boolean t = true; Systemoutprintin (“Before the return”); if (t) return; Systemoutprintin (“This wont execute”); Tee ee one eee TOC ea Lees aera or tement is not available in java, because it leads to confusion and forms infinite Accepting Input from Keyboard A stream represents flow of data from one place to other place Streams are of two types in java Input streams which are used to accept or receive data Output streams are used (o display or write data Streams are represented as classes in javaio package Systemin: This represents InputStream object, which by default represents standard input, device that is keyboard Systemout: This represents PrintStream object, which by default represents standard output device that is monitor Systemerr: This field also represents PrintStream object, which by default represents monitor Systemout is used to display normal messages and results whereas Systemerr is used to display error messages To accept data from the keyboard: Connect the keyboard to an input stream object Here, we can use InputStreamReader that can read data from the keyboarda InputSteamReader obj = new InputStreamReader (Systemin); Connect InputStreamReader to BufferReader, which is another input type of stream We are using BufferedReader as it has got methods to read data properly, coming from the stream BufferedReader br = new BufferedReader (obj); The above two steps can be combined and rewritten in a single statement as: BufferedReader br = new BufferedReader (new InputStreamReader (Systemin)); Now, we can read the data coming from the keyboard using read () and readLine () methods available in BufferedReader class Data BufferedReader InputStreamReader Keyboard keyboard Accepting a Single Character from the Keyboard: Create a BufferedReader class object (br) Then read a single character from the keyboard using read() method as: char ch = (char) brread(); ‘The read method reads a single character from the keyboard but it returns its ASCII number, which is an integer Since, this integer number cannot be stored into character type variable ch, we should convert it into char type by writing (char) before the method int data type is converted into char data type, converting one data type into another data type is called type casting. Figure: Accepting a String from Keyboard: Create a BufferedReader class object (br) Then read a string from the keyboard using readLine() method tring str = brreadL ine (); readLine () method accepts a string from keyboard and returns the string into str In this case, casting is not needed since readLine () is taking a string and returning the same data type Accepting an Integer value from Keyboard: First, we should accept the integer number from the keyboard as a string, using readLine () as: String str = brreadL ine (); Now, the number is in str, ie in form of a string This should be converted into an int by using parselnt () method, method of Integer class as: int n= Integer.parselnt (str); Ifneeded, the above two statements can be combined and written as: int n = Integerparselnt (br.readLine() );22 parselnt () is a static method in Integer class, so it can be called using class name as Integerparselnt () We are not using casting to convert String type into int type The reason is String is a class and int is a fundamental data type Converting a class type into a fundamental data type is not possible by using casting It is possible by using the method IntegerparseInt() Accepting a Float value from Keyboard: We can accept a float value from the keyboard with the help of the following statement: float n = FloatparseFloat (br.readLine() ); We are accepting a float value in the form of a string using brreadLine () and then passing the string to FloatparseFloat () to convert it into float parseFloat () is a static method in Float class Accepting a Double value from Keyboard: We can accept a double value from the keyboard with the help of the following statement: double n= DoubleparseDouble (br.readLine() ); We are accepting a double value in the form of a string using brreadLine () and then passing the string to DoubleparseDouble () to convert it into double parseDouble () is a static method in Double class Accepting Other Types of Values: + To accept a byte value: byte n= ByteparseByte (brreadLine () ); To accept a short value: short n= ShortparseShort (brreadL ine () ); To accept a long value: long n= LongparseLong (brreadL ine () ); boolean x = BooleanparseBoolean (brreadLine () To accept a boolean value: ); If read () / readLine () method could not accept values due to some reason (like insufficient memory or illegal character), then it gives rise to a runtime error which is called by the name IOException, where IO stands for Input/Output and Exception represents runtime errorBut we do not know how to handle this exception, in Java we can use throws command to throw the exception without handling it by writing:23, throws IOException at the side of the method where read ()/ readLine () is used Program 1: Write a program to accept and display student details ‘Accepting and displaying student details import javaio*; class StudentDemo {public static void main(String args[]) throws IOException {l/ Create BufferedReader object to accept data BufferedReader br new BufferedReader (new InputStreamReader (Systemin)); //Accept student details Systemoutprint ("Enter roll number: "); int mo = Integerparselnt (brreadLine()); Systemoutprint (“Enter Gender (M/F): “); char gender = (charbrread(); brskip (2); Systemoutprint ("Enter Student name: " String name = brreadLine () Systemoutprintin ("Roll No: " + mo); Systemoutprintin ("Gender: " + gender); Systemoutprintin ("Name: " + name); In the above program after accepting gender of the student, brskip (2) is used The reason is that we used read () method to accept the gender value and then readLine () is used to accept the name When we type M for gender and press enter, then it releases a \n code So at gender column, we are giving two characters M and \n But, read () method takes only the first character and rejects the next character, ie \n, which is trapped by the next readLine () method and name will accept \n For this purpose, we can use skip () method of BufferedReader, which helps in skipping a specified number of characters Suppose we take \n as two characters; now to skip them, we can write brskip (2);4 Arrays and Strings Arrays: An array represents a group of elements of same data type Arrays are generally categorized into (wo types Single Dimensional arrays (or | Dimensional arrays) Multi-Dimensional arrays (or 2 Dimensional arrays, 3 Dimensional arrays, ...) Single Dimensional Arrays: A one dimensional array or single dimensional array represents 2 row or a column of elements For example, the marks obtained by a student in 5 different subjects can be represented by a 1D array We can declare a one dimensional array and directly store elements at the time of its declaration, a int marks{] = {50, 60, 55, 67, 70}; We can create a 1D array by declaring the array first and then allocate memory for it by using new operator, as: int marks} fideclare marks array marks = new int{5]; //allot memory for storing 5 elements These two statements also can be written int marks [] = new int [5]; Program 1: Write a program to accept elements into an array and display the same program to accept elements into an array and display the same import javaio*; class ArrayDemol {public static void main (String args{]) throws IOException {i/Create a BufferedReader class object (br) BufferedReader br = new BufferedReader (new InputStreamReader (Systemin)); Systemoutprintin (“How many elements: “); int n = IntegerparseInt (brreadL ine ()); create a 1D array with size n int a[] = new int[n]; Systemoutprint ("Enter elements into array :"); for (int i= 0; i
0) Systemoutprintin (b1 + "is bigger"); else Systemoutprintin (b2 +" is bigger");54 Short Class: Short class wraps a value of primitive data type ‘short’ in its object Short class object contains a short type field that stores a short number Construetors: Short (short num) Short (String str) Methods: Method Description int compareTo (Short obj) This method compares the numerical value of two Short class objects and retums 0,-ve, +ve value Boolean equals ( Object obj) This method compares the Short object with any other object obj and retums true if both have same content Static short parseShont (String str) This method returns int equivalent of the String sir String toString Q) This method returns a String form of the Short object static Short valueOf (String str) This method converts a String str that contains a short number into Short class object and returns that object Integer Class: Integer class wraps a value of the primitive type ‘int’ in an object An object of type Integer contains a single field whose type is int Constructors: Integer (int num) Integer (String str) Methods: Method Description int mtViaue 0) Tetumns the value of the invoking object as an int int compareTo (Integer obj) ‘compares the numerical value of the invoking object with that of ‘obj’ returns zero or -ve value or +ve value static int parseint (String str) Tetums int equivalent of the String str String toString 0 Teturns a String form of the invoking obje static Integer valueOf (String str) returns an Integer object that contains the value shown by str static String toBinaryString (int i) returns a String representation of the integer argument in base2 static String toHexString (int i) returns a String representation of the integer argument in base 16 static String toOctalString (int i) returns a String representation of the integer argument in base 8 Float Clas: Float class wraps a value of primitive type float in an object An object of type float contains a single field whose type is float Constructor: Float (float num)Float (String str) Methods: 5S ‘Method Description float floatVaiue returns the value of the invoking object as a float double doubleValue 0. Tetumns the value of the invoking object as a double int compareTo (Float f) ‘Compares the numerical value of the invoking object with that of '? returns zero or +ve or -ve value Static float parseFloat (String str) Tetums the float equivalent of the String str String toString Q) returns the String equivalent of invoking object static Float valueOf (String str) returns the Float object with the value specified by String str Long Class: The Long class contains a primitive long type data The object of Long class contains a field where we can store a long value Construetors: Long has two constructors Long (long num): Long object can be created as: Long obj = new Long (123000); Long(String str): String str = "12300044", Long obj = new Long (str); Methods: Method Description int compareTo(Long obj) This method compares the numerical value of two Long class objects and retums ),-ve,tve value Satie Tong parseLong( String st) This method returns Tong equivalent of the String str String toString() This method converts Long object into String object and returns the String object Static Long valueO{String str) This method converts a string str that contains some long number into Long object and retums that object Boolean class: The Boolean class object contains a primitive ‘boolean’ type data The object of Boolean class contains a field where we can store a boolean value Constructors: Boolean obj = new Boolean (true); String str ="false" Boolean obj = new Boolean (str); Methods: Method Description int compareTo(Boolean obj) This method compares the numerical value of two Boolean class objects and retums 0,-ve,*ve value static boolean parseBoolean(String str This method returns boolean equivalent of the String str ‘String toString) This method converts Boolean object into a String56 object and returns the String object static Boolean valueOf(String str) This method converts a String str that contains @ boolean value into Boolean object and returns that object, Constructors: Double (double num) Double (String str) Methods: Double Class: Double class wraps a value of primitive type Double in an Object ‘Method Description double doubleValueQ, returns the value of the invoking object asa double Toat floatValue() Tetums the value of the invoking object as a float int compareTo(Double d) This method compares the numerical value of two Double class objects and returns 0,-ve,+ve value static double parseDouble(String sth) returns the double equivalent of the String str String toString() This method converts Double object into a String object and returns the String object statie Double valueO{(String str) returns the Double object with the value specified by String str7 Math class: The class Math contains methods for performing basic numeric operations Methods: Method Description Static double sin(double arg) Tetums the sine value of the arg arg is in radians static double cos(double arg) Tetums the cosine value of the arg static double tan(double arg) Tetumns the tangent value of the arg static double log(double arg) Tetums the natural fogarithm value or arg Static double pow(double x, double n)| returns x to the power ofn value static double sqrt(double arg) Tetums the square root of arg, Static double abs(double arg) Tetums the absolute value of arg static double ceil(double arg) Tetums the smallest integer which is greater or equal] to arg, static double floor(double arg) returns the greatest integer which is lower or equal to arg, Static double min(argl,arg2) Tetums the minimum of argl and arg2 static double max(argarg2) [retums the maximum of argl and arg2 Static Tong round(arg) returns the rounded value of arg static double random( returns a random number between 0 and 1 Static double toRadians(double angle)| converts angle in degrees into radians Static double toDegrees(double angle) converts angle in radians mto degrees Program 3: Write a program to print random numbers using Math class //Generating random numbers class Rand { public static void main(String args[]) throws Exception { while(true) { double d= 10 * Mathrandom(); int i= (int) d; Systemoutprint ("\t" + i); if(i=0) Systemexit (0);58 Generic Types > Generic type represents classes, interfaces and methods in a type safe manner > Generic types can act on any type of data > All Generic types are subclasses of Object class, it acts on Objects only > Generic types act on advanced data type only > It is not possible to create an object to Generic type itself > Using generic types, we can avoid casting in many cases Generic Class: When we create a class with an instance variable to store an Integer object, it can be used to store Integer type data only We cannot use that instance variable to. store a Float class object or a String type Object To store different types of data into a class, we have to write the same class again and again by changing the data type of the variables This can be avoided using a generic class A generic class represents a class that is type-safe This means a generic class can act upon any data type Generic classes and generic interfaces are also called »parameterized types” because they use a parameter that determines which data type they should work upon Program 1: Write a program that has a class which stores any type of data //Example for Generic Class class MyClass
{T obj; MyClass (T obj) { 3 T getObj () { thisobj = obj; return obj; } } class Gent {public static void main(String args(]) { Integer il = new Integer (10); MyClass
obj = new MyClass
(il); Systemoutprintin ("U stored "+ objl getObj() ); Double dl = new Double(3066); MyClass
obj2 = new MyClass
(d1); Systemoutprintin ("U Stored :" + obj2getObj() ); MyClass
obj3 = new MyClass
("Suresh Kumar"); Systemoutprintin ("U Stored : " + obj3getObi() )s59 Generic Method: We can make a method alone as generic method by writing the generic parameter before the method return type as:
returntype methodname () { Method code; } eg:
void display_data () { Method bod; Program 2: Write a program with generic method which displays any type of data //Generic method example class MyClass {
t ‘method that accepts any object return_type method_name (T object_name ); Here, T represents any data type which is used in the interfac implementation class for the above interface as: class class_name
implements interface_name
{ public return_type method_name (T object_name ) { + We can write an /iprovide body of the method } Program 3: Write an example program for generic interface /JA generic interface interface inter
{ I class AnyClass
implements inter
{public void displayData (T tl) { } void displayData (T obj); Systemoutprintin ("Entered value is :" + (1); } class Gen3 {public static void main (String args[]) {AnyClass
ob] = new AnyClass
(); obldisplayData (new Integer. (10) ); ‘AnyClass
ob2 = new AnyClass
0; ob2displayData (new String ("Hari") );
You might also like
Oop Java
PDF
No ratings yet
Oop Java
139 pages
KG College of Arts and Science Affiliated by Bharathiar University and Accredited by Naac Kgisl Campus, Saravanampatti, Coimbatore, Tamilnadu, India
PDF
No ratings yet
KG College of Arts and Science Affiliated by Bharathiar University and Accredited by Naac Kgisl Campus, Saravanampatti, Coimbatore, Tamilnadu, India
62 pages
Unit2 JWFILES
PDF
No ratings yet
Unit2 JWFILES
111 pages
JAVA unit1
PDF
No ratings yet
JAVA unit1
92 pages
Object Oriented Programming With Java
PDF
No ratings yet
Object Oriented Programming With Java
59 pages
CS175 Lecture 2
PDF
No ratings yet
CS175 Lecture 2
20 pages
Chapter 1
PDF
No ratings yet
Chapter 1
81 pages
Unit 2
PDF
No ratings yet
Unit 2
111 pages
Object Oriented Programming-Java
PDF
No ratings yet
Object Oriented Programming-Java
51 pages
22cs202-Unit 1 - PPT
PDF
No ratings yet
22cs202-Unit 1 - PPT
153 pages
OOP Through Java Programming Unit-1
PDF
No ratings yet
OOP Through Java Programming Unit-1
61 pages
java ppt
PDF
No ratings yet
java ppt
12 pages
Prkjava 1 PDF
PDF
0% (1)
Prkjava 1 PDF
169 pages
Lecture 2
PDF
No ratings yet
Lecture 2
20 pages
Java Week1a
PDF
No ratings yet
Java Week1a
19 pages
JAVA UNIT I
PDF
No ratings yet
JAVA UNIT I
51 pages
Untitled
PDF
No ratings yet
Untitled
247 pages
CSP 45 Java B1 1568720246
PDF
No ratings yet
CSP 45 Java B1 1568720246
104 pages
1 Java Intro
PDF
No ratings yet
1 Java Intro
32 pages
JAVA-Notes
PDF
No ratings yet
JAVA-Notes
181 pages
23000322023_CA2_OE-EC704A
PDF
No ratings yet
23000322023_CA2_OE-EC704A
11 pages
Unit 1 - Java
PDF
No ratings yet
Unit 1 - Java
57 pages
Abstract Class in Java
PDF
No ratings yet
Abstract Class in Java
86 pages
About The Java Technology
PDF
No ratings yet
About The Java Technology
5 pages
Java Unit 1 Final
PDF
No ratings yet
Java Unit 1 Final
33 pages
Core Java - Part1
PDF
No ratings yet
Core Java - Part1
21 pages
JAVA
PDF
No ratings yet
JAVA
43 pages
Tanya Srivastava - 1619213115
PDF
No ratings yet
Tanya Srivastava - 1619213115
41 pages
Tanya Srivastava - 1619213115
PDF
No ratings yet
Tanya Srivastava - 1619213115
41 pages
lecture 1
PDF
No ratings yet
lecture 1
6 pages
Java
PDF
No ratings yet
Java
44 pages
Computer Programming 1 NCII Notes and Lesson Summary
PDF
No ratings yet
Computer Programming 1 NCII Notes and Lesson Summary
2 pages
Day1 Javaintro
PDF
No ratings yet
Day1 Javaintro
31 pages
Java Complete II I
PDF
No ratings yet
Java Complete II I
116 pages
Java Introduction
PDF
No ratings yet
Java Introduction
265 pages
Java Notes: by Vinay Kumar
PDF
No ratings yet
Java Notes: by Vinay Kumar
49 pages
Kts Java Programming Notes
PDF
No ratings yet
Kts Java Programming Notes
3 pages
Lecture I (Introduction to Java Programming)
PDF
No ratings yet
Lecture I (Introduction to Java Programming)
28 pages
Chapter One: Structure Programming
PDF
No ratings yet
Chapter One: Structure Programming
12 pages
DPP Java
PDF
No ratings yet
DPP Java
78 pages
Java History: Us06Ccsc01 Unit - I OOP Using Java
PDF
No ratings yet
Java History: Us06Ccsc01 Unit - I OOP Using Java
69 pages
Wa0020
PDF
No ratings yet
Wa0020
90 pages
Secrets of Java
PDF
100% (2)
Secrets of Java
102 pages
Lesson1 - Introduction To Java
PDF
No ratings yet
Lesson1 - Introduction To Java
3 pages
Oopm 2013 Demo
PDF
No ratings yet
Oopm 2013 Demo
182 pages
133777718703310563
PDF
No ratings yet
133777718703310563
313 pages
Unit-1 Introduction To Java
PDF
No ratings yet
Unit-1 Introduction To Java
86 pages
Ict2215 Computer Programming 4
PDF
No ratings yet
Ict2215 Computer Programming 4
81 pages
Basics of Java Programming Language
PDF
No ratings yet
Basics of Java Programming Language
32 pages
VXL It-Java-1
PDF
No ratings yet
VXL It-Java-1
41 pages
Oop Handout All Chapters
PDF
No ratings yet
Oop Handout All Chapters
96 pages
Project File
PDF
No ratings yet
Project File
52 pages
Java Notes (Nep Syllabus)
PDF
100% (1)
Java Notes (Nep Syllabus)
133 pages
UNIT-1 Notes
PDF
No ratings yet
UNIT-1 Notes
55 pages
Complete Java-JSP NOTES
PDF
No ratings yet
Complete Java-JSP NOTES
279 pages
Java Complete Notes
PDF
No ratings yet
Java Complete Notes
191 pages
Internship report 2
PDF
No ratings yet
Internship report 2
30 pages
OOP in Java
PDF
No ratings yet
OOP in Java
151 pages
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
Oop Java
PDF
Oop Java
KG College of Arts and Science Affiliated by Bharathiar University and Accredited by Naac Kgisl Campus, Saravanampatti, Coimbatore, Tamilnadu, India
PDF
KG College of Arts and Science Affiliated by Bharathiar University and Accredited by Naac Kgisl Campus, Saravanampatti, Coimbatore, Tamilnadu, India
Unit2 JWFILES
PDF
Unit2 JWFILES
JAVA unit1
PDF
JAVA unit1
Object Oriented Programming With Java
PDF
Object Oriented Programming With Java
CS175 Lecture 2
PDF
CS175 Lecture 2
Chapter 1
PDF
Chapter 1
Unit 2
PDF
Unit 2
Object Oriented Programming-Java
PDF
Object Oriented Programming-Java
22cs202-Unit 1 - PPT
PDF
22cs202-Unit 1 - PPT
OOP Through Java Programming Unit-1
PDF
OOP Through Java Programming Unit-1
java ppt
PDF
java ppt
Prkjava 1 PDF
PDF
Prkjava 1 PDF
Lecture 2
PDF
Lecture 2
Java Week1a
PDF
Java Week1a
JAVA UNIT I
PDF
JAVA UNIT I
Untitled
PDF
Untitled
CSP 45 Java B1 1568720246
PDF
CSP 45 Java B1 1568720246
1 Java Intro
PDF
1 Java Intro
JAVA-Notes
PDF
JAVA-Notes
23000322023_CA2_OE-EC704A
PDF
23000322023_CA2_OE-EC704A
Unit 1 - Java
PDF
Unit 1 - Java
Abstract Class in Java
PDF
Abstract Class in Java
About The Java Technology
PDF
About The Java Technology
Java Unit 1 Final
PDF
Java Unit 1 Final
Core Java - Part1
PDF
Core Java - Part1
JAVA
PDF
JAVA
Tanya Srivastava - 1619213115
PDF
Tanya Srivastava - 1619213115
Tanya Srivastava - 1619213115
PDF
Tanya Srivastava - 1619213115
lecture 1
PDF
lecture 1
Java
PDF
Java
Computer Programming 1 NCII Notes and Lesson Summary
PDF
Computer Programming 1 NCII Notes and Lesson Summary
Day1 Javaintro
PDF
Day1 Javaintro
Java Complete II I
PDF
Java Complete II I
Java Introduction
PDF
Java Introduction
Java Notes: by Vinay Kumar
PDF
Java Notes: by Vinay Kumar
Kts Java Programming Notes
PDF
Kts Java Programming Notes
Lecture I (Introduction to Java Programming)
PDF
Lecture I (Introduction to Java Programming)
Chapter One: Structure Programming
PDF
Chapter One: Structure Programming
DPP Java
PDF
DPP Java
Java History: Us06Ccsc01 Unit - I OOP Using Java
PDF
Java History: Us06Ccsc01 Unit - I OOP Using Java
Wa0020
PDF
Wa0020
Secrets of Java
PDF
Secrets of Java
Lesson1 - Introduction To Java
PDF
Lesson1 - Introduction To Java
Oopm 2013 Demo
PDF
Oopm 2013 Demo
133777718703310563
PDF
133777718703310563
Unit-1 Introduction To Java
PDF
Unit-1 Introduction To Java
Ict2215 Computer Programming 4
PDF
Ict2215 Computer Programming 4
Basics of Java Programming Language
PDF
Basics of Java Programming Language
VXL It-Java-1
PDF
VXL It-Java-1
Oop Handout All Chapters
PDF
Oop Handout All Chapters
Project File
PDF
Project File
Java Notes (Nep Syllabus)
PDF
Java Notes (Nep Syllabus)
UNIT-1 Notes
PDF
UNIT-1 Notes
Complete Java-JSP NOTES
PDF
Complete Java-JSP NOTES
Java Complete Notes
PDF
Java Complete Notes
Internship report 2
PDF
Internship report 2
OOP in Java
PDF
OOP in Java