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)
72 views
OOP in Java
oop
Uploaded by
liracam748
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save OOP in java For Later
Download
Save
Save OOP in java For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
72 views
OOP in Java
oop
Uploaded by
liracam748
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save OOP in java For Later
Carousel Previous
Carousel Next
Save
Save OOP in java For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 151
Search
Fullscreen
OOP in Java BCA THIRD OY} SEMESTER Mechi Multiple Campus Bhadrapur eM Teor eo 7 LCI sole} MCA, Purbanchal UniversityUn Introduction to Java [2 Hrs. Java is an object-oriented, cross platform, multi-purpose programming language produced by Sun Microsystems. It is 2 combination of features of C and C++ with some essential additional concepts. Java is well suited for both standalone and web application development and is designed to provide solutions to most of the problems faced by users of the internet era. It was originally designed for developing programs for set-top boxes and handheld devices, but later became a popular choice for creating web applications. The Java syntax is similar to C++, but is strictly an object-oriented programming language. For example, most Java programs contain classes, which are used to define objects, and methods, which are assigned to individual classes. Java is also known for being stricter than C++, meaning variables and functions must be explicitly defined, This means Java source code may produce errors or "exceptions" more easily than other languages, but it also limits other types of errors that may be caused by undefined variables or unassigned types. Unlike Windows executables (.€XE files) or Macintosh applications (. APP files), Java programs are not run directly by the operating system. Instead, Java programs are interpreted by the Java Virtual Machine, or JVM, which runs on multiple platforms. This means all Java programs are multiplatform and can run on different platforms, including Macintosh, Windows, and Unix computers. However, the JVM must be installed for Java applications or applets to run at all. Fortunately, the JVM is included as part of the Java Runtime Environment (RE. Oracle acquired Sun Microsystems in January, 2010. Therefore, Java is now maintained and distributed by Oracle. Features of Java a) Object-Oriented - Java supports the features of object-oriented programming. Its object model is simple and easy to expand. b) Platform independent - C and C++ are platform dependency languages hence the application programs written in one Operating system cannot run in any other Operating system, but in platform independence language like Java application programs written in one Operating system can able to run on any Operating system c) Simple - Java has included many features of C / C ++, which makes it easy to understand. d) Secure - Java provides a wide range of protection from viruses and malicious programs. It ensures that there will be no damage and no security will be broken. ) Portable - Java provides us the concept of portability. Running the same program with Java on different platforms is possible. f) Robust - During the development of the program, it helps us to find possible mistakes as soon as possible. g) Multithreaded - The multithreading programming feature in Java allows you to write a program that performs several different tasks simultaneously. Prepared by: Raju Poudel [MCA] 2h) Distributed - Java is designed for distributed Internet environments as it manages the TCP/IP protocol. The most striking feature of the language is that itis a platform-neutral language. Java is the first programming language that is not tied to any particular hardware or operating system. Programs developed in Java can be executed anywhere on any stream. We can call Java as a revolutionary technology because it has brought in a fundamental shift in how we develop and use programs. Nothing like this has happened to the software industry before. History of Java Java is a general-purpose, object-oriented programming language developed by Sun Microsystems of USA in 1991. Originally called Oak by James Gosling, one of the inventors of the language, Java was designed for the development of software for consumer electronic devices like TVs, VCRs and such other electronic machines. The goal had a strong impact on the development team to make the language simple, portable and highly reliable. The Java team which included Patrick Naughton discovered that the existing languages like C and C++ had limitations in terms of both reliability and portability. However, they modelled their new language Java on C and C++ but removed a number of features of Cand C++ that were considered as sources of problems and thus made Java a really simple, reliable, portable and powerful language. Java Milestones Year Development 1990 Sun Microsystems decided to develop special software that could be used to manipulate consumer clectronic devices. A team of Sun Microsystems programmers headed by James Gosling was formed to undertake this task. 1991 After exploring the possiblity of using the most popular object-oriented language C++, the team announced a new language named “Oak” 1992 The team, known as Green Project team by Sun, demonstrated the application of their new language to contro! alist of home appliances using a hand-held device with a tiny touch-sensitive screen 1993 The World Wide Web (WWW) appeared on the Internet and transformed the text-based Intemet into a graphical-nch environment. The Green Project team came up with the idea of developing Web applets (tiny peograms) using the new language that could run on all types of computers connected to Internet 1994 The team developed a Web browser called "HoUava” to locate and run applet programs on Internet. HoUlva demonstrated the power of the new language, thus making it instantly popular among the Internet users 1995 Oak was renamed “Java”, due to some legal snags. Java is just a name and is not an acronym. Many Popular companies including Netscape and Microsoft announced their support to Java. 1996 Java established itself not only as a leader for Internet programming but also as a general-purpose, object-oriented programming language. Sun releases Java Development Kit 1.0. 1997 Sun releases Java Development Kit 1.1 JDK 1.1). 1998 Sun relases the Java 2 with version 1.2 of the Software Development Kit (SDK 1.2). 1999 Sun releases Java 2 Platform, Standard Edition (J2SE) and Enterprise Edition (J2EE). 2000 J2SE with SDK 1.3 was released. 2002 12SE with SDK 1.4 was released. 2004 _J2SE with JDK 5.0 (instead of IDK 1.5) was released. This is known as J2SE 5.0. Prepared by: Raju Poudel [MCA] 2The Internet and Java’s Place in IT Earlier Java was only used to design and program small computing devices, but it was later adopted as one of the platform-independent programming languages, and now according to. Sun, 3 billion devices run Java. Java is one of the most important programming languages in today's IT industries. * JSP In Java, JSP (Java Server Pages) is used to create dynamic web pages, such as in PHP and ASP. * Applets - Applets are another type of Java programs that are implemented on Internet browsers and are always run as part of a web document. + IZEE - Java 2 Enterprise Edition is a platform-independent environment that is a set of different protocols and APIs and is used by various organizations to transfer data between each other. © JavaBeans - This is a set of reusable software components that can be easily used to create new and advanced applications. © Mobile - in addition to the above technology, Java Is widely used in mobile devices nowadays, many types of games and applications are being made in Java. Types of Java Applications and Applets a) Web Application - Java is used to create server-side web applications. Currently, Servlet, JSP, Struts, JSF, etc. technologies are used. b) Standalone Application - It is also known as the desktop application or window- based application. An application that we need to install on every machine or server such as media player, antivirus, etc. AWT and Swing are used in java for creating standalone applications. c) Enterprise Application - An application that is distributed in nature, such as banking applications, etc. It has the advantage of the high-level security, load balancing, and clustering. in Java, EJB is used for creating enterprise applications. d) Mobile Application - Java is used to create application software for mobile devices. Currently, Java ME is used for building applications for small devices, and also Java is a programming language for Google Android application development. Java Virtual Machine Java Virtual Machine, or JVM as its name suggest is a “virtual” computer that resides in the “real” computer as a software process. JVM gives Java the flexibility of platform independence. Java code is written in java file. This code contains one or more Java language attributes like Classes, Methods, Variable, Objects etc. Javac is used to compile this code and to generate .class file. Class file is also known as “byte code “. The name byte code is given may be because of the structure of the instruction set of Java program. Java byte code is an input to Java Virtual Machine. !VM read this code and interpret it and executes the program. Prepared by: Raju Poudel [MCA] 4Java Code (,java) Java class is written in Unicode characters. JAVAC i i in Java compiler convert these Se Unicode characters into Byte code. Java Byte code can only be understandable by JVM. The JVM has two primary functions: to allow Java programs to run on any device or ‘operating system (known as the "Write once, run anywhere” principle), and to manage and optimize program memory. When Java was released in 1995, all computer programs were written to a specific operatin; developer. So the VM was a ig system, and program memory was managed by the software revelation. Java Program "Source Code Viewal Machine ‘aR, Real Mache Process of converting bytecode into machine code Prepared by: Raju Poudel [MCA] 5Byte Code — not an Executable Code Java bytecode is the resulting compiled object code of a Java program. This bytecode can be run in any platform which has a Java installation in it. The Java bytecode gets processed by the Java virtual machine (JVM) instead of the processor. It is the job of the JVM to make the necessary resource calls to the processor in order to run the bytecode. The Java bytecode is not completely compiled, but rather just an intermediate code sitting in the middle because it still has to be interpreted and executed by the JVM installed on the specific platform such as Windows, Mac or Linux. Upon compile, the Java source code is converted into the .class bytecode. Procedure-Oriented vs. Object-Oriented Programming Object-Oriented Programming (OOP) is 2 high-level programming language where a program is divided into small chunks called objects using the object-oriented model, hence the name. This paradigm is based on objects and classes. © Object - An object is basically a self-contained entity that accumulates both data and procedures to manipulate the data. Objects are merely instances of classes. © Glass ~ A class, in simple terms, Is a blueprint of an object which defines all the commen properties of one or more objects that are associated with it. A class can be used to define multiple objects within a program The OOP paradigm mainly eyes on the data rather than the algorithm to create modules by dividing a program into data and functions that are bundled within the objects. The modules cannot be modified when a new object is added restricting any non-member function access to the data. Methods are the only way to assess the data Objects can communicate with each other through same member functions. This process is known as message passing. This anonymity among the objects is what makes the program secure. A programmer can create a new object from the already existing objects by taking most of its features thus making the program easy to implement and modify. Procedure-Oriented Programming (POP) follows a step-by-step approach to break down a task into a collection of variables and routines (or subroutines) through a sequence of instructions. Each step is carried out in order in a systematic manner so that a computer can understand what to do. The program is divided into small parts called functions and then it follows a series of computational steps to be carried out in order. It follows a top-down approach to actually solve 2 problem, hence the name. Procedures correspond to functions and each function has its own purpose. Dividing the program into functions is the key to procedural programming. So a number of different functions are written in order to accomplish the tasks. Prepared by: Raju Poudel [MCA] 6Difference between OOP and POP is shown below: Procedure Oriented Programming Object Oriented Programming In POP, program is divided into small parts called functions. In OOF, program is divided into parts called objects. In POP, Importance is not given to data but to functions as well as sequence of actions to be done. In OOP, Importance is given to the data rather than procedures or functions because it works as a real world. POP follows Top Down approach. OOP follows Bottom Up approach. POP does not have any access specifier. OOP has access specifiers named Public, Private, Protected, etc. In POP, Data can move freely from function to function in the system. In OOP, objects can move and communicate with each other through member functions. To add new data and function in POP is not so easy. OOP provides an easy way to add new data and function. In POP, Most function uses Global data for sharing that can be accessed freely from function to function in the system. In OOP, data cannot move easily from function to function, it can be kept public or private so we can control the access of data. POP does not have any proper way for OOP provides Data Hiding so provides more hiding data so itis less secure. security, In POP, Overloading isnot possible. In OOP, overloading is possible in the form of Function Overloading and Operator Overloading. Example of POP are : C, VB, FORTRAN, Pascal. Example of OOP are : C++, JAVA, VB.NET, CH.NET. Prepared by: Raju Poudel [MCA] 7Unit — 2 Tokens, Expressions and Control Structures [5 Hrs.] Primitive Data Types Primitive types are the most basic data types available within the lava language. There are 8 primitive cata types: boolean, byte, char, short, int, long, float and double. These types serve as the building blocks of data manipulation in Java. Such types serve only one purpose — containing pure, simple values of a kind. Because these data types are defined into the Java type system by default, they come with a number of operations predefined. Data types are divided into two groups: * Primitive data types - includes byte, short, int, long, float, double, boolean and char + Non-primitive(Derived) data types - such as String, Arrays and Classes Data Type | Size _| Description byte Lbyte | Stores whole numbers from -128 to 127 short Zbytes_| Stores whole numbers from -32,768 to 32,767 int Abytes_| Stores whole numbers from -2,147,483,648 to 2,147,483,647 long Bbytes [Stores whole numbers from -9,223,372,036,854,775,808 to 9,223.372,036,854,775,808 float bytes | Stores fractional numbers from 3.4e-038 to 3.4e+038, Sufficient for storing 6 to 7 decimal digits double | Sbytes | Stores fractional numbers from 1.7e-308 to 1.7e+038. Sufficient for storing 15 decimal digits boolean | 1byte _| Stores true or false values char 2bytes | Stores a single character/letter User Defined Data Types User defined data types are those that user / programmer classes, interfaces. For example: imself defines. For example, MyClass obj Here obj is a variable of data type MyClass and we call them reference variables as they can be used to store the reference to the object of that class. Declaration of Variables and Assignment In Java, variables are the names of storage locations. After designing suitable variable names, we must declare them to the compiler. Declaration does three things: 1. It tells the compiler what the variable name is. 2. It specifies what type of data the variable will hold. 3. The place of declaration (in the program) decides the scope of the variable. A variable can be used to store a value of any data type. That is, the name has nothing to do with the type. Java allows any properly formed variable to have any declared data type. The general form of declaration of a variable is: type variable!, variable2,..... variable Prepared by: Raju Poudel [MCA] 8A simple method of giving value to a variable is through the assignment statement as follows variableName = value; For Example: abe = 100; xyz = 10.2; It is also possible to assign a value to a variable at the time of its declaration. This takes the form: type vartableName = value: | Examples: int finalValue = 100 char yes ° i double total = 75.36 Type Conversion and Casting Conversion of one data type to another data type is called type casting. If the two types are compatible, then Java will perform the conversion automatically. For example, it is always possible to assign an int value to a Jong variable. However, not all types are compatible, and thus, not all type conversions are implicitly allowed. For instance, there is no automatic conversion defined from double to byte. Fortunately, it is still possible to obtain a conversion between incompatible types. To do so, you must use a cast, which performs an explicit conversion between incompatible types Java's Automatic Conversions When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are mi * The two types are compatible. * The destination type is larger than the source type. When these two conditions are met, a widening conversion takes place. For example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is required. For widening conversions, the numeric types, including integer and floating-point types, are compatible with each other. However, there are no automatic conversions from the numeric types to char or boolean. Also, char and boolean are not compatible with each other. As mentioned earlier, Java also performs an automatic type conversion when storing a literal integer constant into variables of type byte, short, long, or char. Casting Incompatible Types Although the automatic type conversions are helpful, they will not fulfill all needs. For example, what if you want to assign an int value toa byte variable? This conversion will not be performed automatically, because a byte is smaller than an int. This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the value narrower so that it wil fitinto the target type. Prepared by: Raju Poudel [MCA] 9To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. It has this general form: (target-type) value Here, target-type specifies the desired type to convert the specified value to. For example, the following fragment casts an int to a byte. If the integer’s value is larger than the range of, a byte, it will be reduced modulo (the remainder of an integer division by the) byte’s range. int a; byte b; I]. b= (byte) 0; The following program demonstrates some type conversions that require casts: // Demonstrate casts class Conversion { b= (byte) i; System.out.printin("i and bt +44" "+ BI; System.out .print1n(*\aConver: i= (int) a; System.out.printin("d and it yds" t+ on of double to System.out .print1n(*\nConversion of double to byte."); b= (byte) dy System.out.printin("d and bt + ds" "4 b); ) , This program generates the following output: Conversion of int to byte. i and b 257 1 Conversion of double to int @ and i 323.142 323 conversion of double to byte 4 and b 323.142 67 Let’s look at each conversion. When the value 257 is cast into a byte variable, the result is the remainder of the division of 257 by 256 (the range of a byte), which is 1 in this case. When the d is converted to an int, its fractional component is lost. When d is converted to a byte, its fractional component is lost, and the value is reduced modulo 256, which in this case is 67. Prepared by: Raju Poudel [MCA] 10Garbage Collection Java garbage collection is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory. In C/C++, programmer is responsible for both creation and destruction of objects. Usually programmer neglects destruction of useless objects. Due to this negligence, at certain point, for creation of new objects, sufficient memory may not be available and entire program will terminate abnormally causing OutOfMemoryErrors. But in Java, the programmer need not to care for all those objects which are no longer in use. Garbage collector destroys these objects. Main objective of Garbage Collector is to free heap memory by destroying unreachable objects. Generally, an object becomes eligible for garbage collection in Java on following cases: 1. All references to that object explicitly set to null e.g. object = null 2. The object is created inside a block and reference goes out scope once control exit: that block, 3. Parent object set to null if an object holds the reference to another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection. Operators in Java ‘An operator, in Java, is a special symbols performing specific operations on one, two or three operands and then returning a result. Arithmetic Operators Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators. Assume integer variable A holds 10 and variable B holds 20, then ~ Operator Description Example + (Addition) ‘Adds values on either side of the operator. A+ B will give 30 ~ (Subtraction) Subiracts right-hand operand from left-hand operand. A- B will give -10 * (Multiplication) | Multiplies values on either side of the operator. A* Bwill give 200 7 (Division) Divides left-hand operand by right-hand operand B/ A will give 2 % (Modulus) Divides left-hand operand by right-hand operand and | 6% A will returns remainder. give 0 ++ (Increment) increases the value of operand by 1. B++ gives 21 ~ (Decrement) Decreases the value of operand by 1. B- gives 19 Prepared by: Raju Poudel [MCA] 1Relational Operators There are following relational operators supported by Java language. ‘Assume variable A holds 10 and variable B holds 20, then — Operator Description Example (equal to) _| Checks if the values of two operands are equal or not, | (A == 8) is yes then condition becomes true. not true. not equal to) | Checks if the values of two operands are equal or not, if| (A = B) is values are not equal then condition becomes true. true. > (greater than) | Checks if the value of left operand is greater than the | (A > B) is value of right operand, if yes then condition becomes true. | not true. = (less than) Checks if the value of left operand is less than the value of [(A < 8) is right operand, if yes then condition becomes true. true. (greater than | Checks if the value of left operand is greater than or equal | (A >= B) is or equal to) to the value of right operand, if yes then concition | not true. becomes true. <= (less than or | Checks if the value of left operand is less than or equal to | (A <= B) is equal to) the value of right operand, if yes then condition becomes | true. true. Bi Operators Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows ~ a=0011 1100 b = 0000 1101 1000 1100 a&b a|b= 00111101 ab = 00110001 a =11000011 The following table lists the bitwise operators. ‘Assume integer variable A holds 60 and variable B holds 13 then — Operator Description Example & (bitwise and) Binary AND Operator copies a bit to the result if it | (A & B) will give 12 exists in both operands, which is 0000 1100 | (bitwise or) Binary OR Operator copies a bit ifit exists in either | (A | 8) will give 61 operand. which is 0011 1101 Prepared by: Raju Poudel [MCA] 12* (bitwise XOR) Binary XOR Operator copies the bit if it is set in one operand but not both (A* B) will give 49 which is 0011 0001 = (bitwise | Binary Ones Complement Operator is unary and compliment) has the effect of 'flipping' bits. (A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number. << (left shift) Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. ‘A << 2 will give 240 which is 1111 0000 >> (right shift) Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. ‘A >> 2 will give 15 which is 1111 >>> (uero fill shift) right | Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. ‘A >>>2 will give 15 which is 0000 1111 Logical Operators The following table lists the logical operators. ‘Assume Boolean Variables A holds true and variable B holds false, then — Operator Description Example && (logical and) Called Logical AND operator. if both the operands | (A && B) is false are non-zero, then the condition becomes true. TT (logical or) Called Logical OR Operator. If any of the two | (A]| 6)istrue operands are non-zero, then the condition becomes true. 1 (logical not) Called Logical NOT Operator. Use to reverses the | (A && B)is true logical state of its operand. If a condition is true then Logical NOT operator will make false. Assignment Operators Following are the assignment operators supported by Java language — Operator _| Description Example = ‘Simple assignment operator. Assigns values from right side operands | C= A+B will to left side operand. assign value of A+B into c = ‘Add AND assignment operator. it adds right operand to the left|C += A is operand and assign the result to left operand. equivalent toC=C+A = Subtract AND assignment operator. It subtracts right operand fromthe |C -= A is left operand and assign the result to left operand. equivalent toC=C-A Propared by: Raju Poudel [MCA] 33Multiply AND assignment operator. It multiplies right operand with the |C *= A is left operand and assign the result to left operand. equivalent toC=C*A 7: Divide AND assignment operator. It divides left operand with the right |C /= A is operand and assign the result to left operand. equivalent toC=C/A Modulus AND assignment operator. It takes modulus using two Ais operands and assign the result to left operand. equivalent toC=C%A <= Left shift AND assignment operator. C <= 21s same as C = C2 >>= Right shift AND assignment operator. C >= 2 is same as C = Co>2 Bitwise AND assignment operator. Cc & 2 is same as C = Ca2 bitwise exclusive OR and assignment operator. C= 21s same as C = cr2 = bitwise inclusive OR and assignment operator. c i= 2 is same as C = c\2 Conditional Operator (? Conditional operator is also known as the ternary operator. This operator consists of three ‘operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as — variable x = (expression) ? value if true : value if false Following is an example — public class Test { public static void main(String args[]) { int a, bs 1) ? 20: 30; System.out.println( "Value of bis : "+ b): Output b= (a == 10) ? 20: 30; System.out.println( "Value of bis : "4b ): Velue of b is : 30 Velue of b is : 20 Prepared by: Raju Poudel [MCA] 14Control Statements A programming language uses control statements to cause the flow of execution to advance and branch based on changes to the state of a program. Java’s program control statements can be put into the following categories: selection, iteration, and jump. - Selection statements allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable. - Iteration statements enable program execution to repeat one or more statements (that is, iteration statements form loops). - Jump statements allow your program to execute in a nonlinear fashion. Java’s Selection Statements Java supports two selection statements: if and switch. These statements allow you to control the flow of your program's execution based upon conditions known only during run time. The if statement is Java's conditional branch statement. It can be used to route program ‘execution through two different paths. Here is the general form of the if statement: if (condition) statement1; else statement2; The if works like this: If the condition is true, then statementi is executed. Otherwise, statement2 (if it exists) is executed. In no case will both statements be executed. For example, consider the following: ifla
100) c = 4; // this it else a= cy 7/ associated with this else eis 4 to i£(4 == 10) q // this else rege Asthe comments indicate, the final else is not associated with if(}<20) because itis not in the same block (even though it is the nearest if without an else). Rather, the final else is associated with iffi==10). The inner else refers to if(k>100) because itis the closest if within the same block. Prepared by: Raju Poudel [MCA] 15The if-else-if Ladder ‘A common programming construct that is based upon a sequence of nested ifs is the if-else- if ladder. It looks like this: if(condition) statement; else if(condition) statement; else if(condition) statement; else statement; Here is a program that uses an if-else-if ladder to determine which season a particular month is in. // Demonstrate if-else-if statements clase IfElee ( Public static void main(string argell) ( int month = 4; // April if (month 32 || month swinter*; 2 || month else if (month {| month == 4 || month season = "Spring™ else if (month || month == 7 || month else if (month I] mos 20 || month == 13) ‘season = "Autumn"; else ‘eason = "Bogus Month'; Systen.out.printin(*April is in the * + season + * ) Here isthe output produced by the program: April is in the Spring, switch The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. As such, it often provides a better alternative than a large series of if-else-if statements. Here is, the general form of a switch statement: Prepared by: Raju Poudel [MCA] 16‘switch (expression) { ‘case valet: // statement sequence break; ‘case vulue2: // statement sequence break; ‘case nalueN: // statement sequence break; default: // default statement sequence : Here isa simple example that uses a switch statement: // ® simple example of the switch. class Sampleswiten public static void main(String arge(]) ( for(int i=0; i<6; ite) switch(i) { ‘case 0 System.out.printin("i is zero." break: ‘System.out.printin(*i is one.*); case 2: ‘System.out.printin(*i is two."); break: case 3 System.out_printin(*i is three.*); break: System.out.printin(*i is greater than 3.*); } ) ‘The output produced by this program is shown here: i is two. i is three. i is greater than 3 i is greater than 3. Iteration mi Java's iteration statements are for, while, and do-while. These statements create what we commonly call loops. As you probably know, 2 loop repeatedly executes the same set of instructions until a termination condition is met. A loop statement allows us to execute a statement or group of statements multiple times. Prepared by: Raju Poudel [MCA] 17for loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times. A for loop is useful when you know how many times a taskis to be repeated. The syntax of a for loop is— for(initialization; Boolean_expression; update) { // Statements Following is an example code of the for loop in Java. public class Test { public static void main(String ergs[]) { for(int x = 10; x < 20; x =x +1) { System.out.print("value of x: " System.out.print("\n"); +5 } Output value of x: 10 value of x: 11 value of x: 12 value of x: 13, value of x : 14 value of x: 15 value of x: 16 value of x: 17 velue of x: 18 value of x: 29 while Loop ‘A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true. The syntax of a while loop is ~ wniie (Goolean_expression) { I/ Statements r Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Prepared by: Raju Poudel [MCA] 18Example: public cless Test { public static void main(String args[]) { int x = 10; while( x < 20) { System.out.print(*value of x xtts system.out .print("\n™ +5 , ? Output value of x: 10 value of x: 12 value of x: 12 vale of x13 velue of x: 4 value of x + 15 value of x: 16 value of x: 37 value of x: 18 value of x: 19 do while loop A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Following is the syntax of a do...while loop — aot 11 Statements Jwhie(Boolean_expression) 5 Example public class Test { public static void main(String args[]) { int x = 10; do { systen.out.print("value of x "+x )3 Systen.out.print("\n"); Jwhile( x'< 20 ); + t Prepared by: Raju Poudel [MCA] 19Output value of x: 10 value of x: 1 value of x: 12 value of x: 23 value of x: 14 value of x: 15 value of x: 16 value of x: 17 value of x: 18 value of x: 19 Nested Loops Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another. For example, here is a program that nests for loops: J/ tops may be nested class Nested ( Public static void main(String arge(]) ( system out print (*.* System. out .printin() The output produced by this program is shown here: Prepared by: Raju Poudel [MCA] 20Jump Statements Java supports three jump statements: break, continue, and return. These statements transfer control to another part of your program. Using break In Java, the break statement has three uses. First, as you have seen, it terminates a statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used asa “civilized” form of goto. Using break to Exit a Loop By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Here is a simple example: /] Using break to exit a loop class Breaktoop { public static void main(String args{}) { for(int 4<200; i++) { £4 We tem.out .printin("i: "+ 4); ystem.out.printIn(*Loop complete. *) ; This program generates the following output woraueunno Loop complete. ‘As you can see, although the for loop is designed to run from 0 to 99, the break statement causes it to terminate early, when i equals 10. Using continue Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue statement performs such an action In awhile and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In a for loop, control goes first to the Prepared by: Raju Poudel [MCA] 21iteration portion of the for statement and then to the conditional expression. For all three loops, any intermediate code is bypassed. Here isan example program that uses continue to cause two numbers to be printed on each line: // Demonstrate continue class Continue { public static void main(String args{]) { for(int i=0; ici0; it+) { System.out print (i +" "); if (482 == 0) continue, System.out .printin("*) ; } } } This code uses the % operator to check if i is even. If it is, the loop continues without printing a newline. Here is the output from this program: ol 23 45 67 89 Using return The last control statement is return. The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. As such, itis categorized as a jump statement. Example: class AC int a,b, sum; public int add() { ‘9-105 bet sum=atb; return sum; + } class 8 { public static void main(String[] orgs) ( A objenew AC); int resmobj..add(); Systen.out.printin("Sun of two numbers="#res); } 2 Output: Sum of two numbers=25 Prepared by: Raju Poudel [MCA] 22Unit — 3 Object Oriented Programming Concepts [9 Hrs.] Fundamentals of a Class A class, in the context of Java, are templates that are used to create objects, and to define object data types and methods. Core properties include the data types and methods that may be used by the object. All class objects should have the basic class properties. Classes are categories, and objects are items within each category. A dass is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: 1. Modifiers : A class can be public or has default access. 2. Class name: The name should begin with a initial letter (capitalized by convention). 3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. 4, Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. 5. Body: The class body surrounded by braces, { } General form of a class is shown below: Access Modifier Class Name public class & { String breed; int age; 3
Default Constructor The default constructor is a constructor that is automatically generated in the absence of explicit constructors (ie. no user defined constructor). The automatically provided constructor is called sometimes a nullary constructor. Constructor with no Arguments class BOX{ double 1,b,h,vol; Box(){ 1-105 bss i 235 y void calculate() { vol=1"b"h; Systen.out.println("Volume of a box is "+vol): public class Constructor { public static void main(String[] arg=) { Box obj=new Box()5 obj.calculate(); + + Outpu' Volume of a box is 165.0 Prepared by: Raju Poudel [MCA] 27Parameterized Constructor The constructor which has parameters or arguments is known as parameterized constructor. In this type of constructor, we should supply/pass arguments while defining object of a class. The values of arguments are assigned to data members of the class. class B0x{ double 1,b,h,vols Box(double x, double y, double 2){ Lexs + void calculate() { vol=1*b*h; System.out.printIn("Volume of a box is *+vol); + + public class Constructor { public static void main(String[] args) { Box objenew Box(10,5,3-3)3 obj.-calculate(); + y Output: Volume of a box is 165.0 The this Keyword Keyword this is a reference variable in Java that refers to the current object. The various usages of ‘THIS’ keyword in Java are as follows: * It can be used to refer instance variable of current class + Itcan be used to invoke or initiate current class constructor + It'can be passed as an argument in the method call + It can be passed as argumentin the constructor call + Itcan be used to return the current dass instance Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. You can use this anywhere a reference to an object of the current class’ type is permitted. // ® redundant use of this. Box (double w, double h, double d) { this.width = w; this.height = h Prepared by: Raju Poudel [MCA] 28/Tlava code for using ‘this’ keyword to //eefer current class instance variables class Test { int a; int b; // Parameterized constructor Test(int a, int b) { this. = a5 this.b = b5 } void display() { //Displaying value of variables a and b System.out.printin("a =" +a+" b=" +b); 3 public static void main(String[] args) { Test object = new Test(1@, 20); object.display(); Output: a=10 b=20 Propared by: Raju Poudel [MCA] 29Four Main Features of Object Oriented Programming: 1. Abstraction 2. Encapsulation 3. Polymorphism 4, Inheritance Abstraction Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information ‘on what the object does instead of how it does it. In Java, abstraction is achieved using Abstract classes and interfaces. Abstract Class ‘A class which contains the abstract keyword in its declaration is known as abstract class. * Abstract classes may or may not contain abstract methods, i.e., methods without body (public void get();) + But, if a class has at least one abstract method, then the class must be declared abstract. + Ifaclass is declared abstract, it cannot be instantiated (We cannot create object). * To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it. + If you inherit an abstract class, you have to provide implementations to all the abstract methods in it. abstract class Box{ int 1,b,h,vol5 void getdata() { 1-105 void calculate() { bth ut.println(“Volume of a box is “+vol); public class Abstraction extends Box { public static void main(String[] args) { Abstraction obj-new Abstraction(); obj.getdata(); obj-ealeulate(); Output: Volume of a box is 100 Prepared by: Raju Poudel [MCA] 20Encapsulation Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, itis also known as data hiding. To achieve encapsulation in Java- * Declare the variables of a class as private. * Provide public setter and getter methods to modify and view the variables values. Benefits of Encapsulation + The fields of a class can be made read-only or write-only. + Aclass can have total control over what is stored in its fields. class Test{ private String name; private int age; public String getname() { return name; ¥ public int getage() { return ages + public void setnane(String nm)|if names + public void setage(int ag) { age=2gs } + public class Encapsulation { public static void main(String args) { Test objenew Test( obj -setname("Raaju Poudel”); obj. setage (27; System.out-printLn("Name: "“+obj-getname()); System.out.printLn("Age: “+obj.getage()); Output: Name: Raaju Poudel Age: 27 Here, we cannot access private data members name and age directly. So we have created public getter and setter methods to access private data members. Prepared by: Raju Poudel [MCA] anPolymorphism Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms. There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding. Polymorphism in Java ‘Compile Time Runtime (Method Overloading)| (Method Overiding) Method Overloading Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different. It is similar to constructor overloading in Java, that allows a class to have more than one constructor having different argument lists. In order to overload a method, the argument lists of the methods must differ in either of these: a) Number of parameters. add(int, int) add(int, int, int) b) Data type of parameters. add(int, int) add(int, float) ¢) Sequence of Data type of parameters. add(int, float) add{float, int) Prepared by: Raju Poudel [MCA] 22Example of method overloading: class Overload { void demo (int a) { system.out.println ("a: " + a); } void demo (int a, int b) { System.out.println ("a and b: "+a + "," +b); ? double demo(double a) { System.out.printIn("double a: " + a); return a + Class MethodOverloading { public static void main (string args []) t Overload 0bj double result; Obj .demo(10); Obj .demo(10, 20); bj -demo(5.5 System.out.print1n("0/P : new Overload()s result + result); Output: a: 10 a and b: 10,20 double a: 5.5 O/P : 30.25 Here the method demo() is overioaded 3 times: first method has 1 int parameter, second method has 2 int parameters and third one is having double parameter. Which method is to be called is determined by the arguments we pass while calling methods. This happens at compile time so this type of polymorphism is known as compile time polymorphism. Prepared by: Raju Poudel [MCA] 33Method Overriding Declaring @ method in sub class which is already present in parent class is known as method overriding. Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class. In this cese the method in parent class is called overridden method and the method in child class is called overriding method Let's take a simple example to understand this. We have two classes: A child class Boy and a parent class Human. The Boy class extends Human class. Both the classes have a common method void eat (). Boy class Is giving its own Implementation to the eat () method or in other words it is overriding the eat () method. class Hunan{ //overridden method public void eat() { Systen.out.print1n("Human is eating”); Hy class Boy extends Human{ //overriding method public void eat(){ systen.out.print1n("Boy is eating"); + public static void main( string args{]) { Boy obj = new Boy(); This will ca: obj.eat(); the child class version of eat() Output: Boy is eating Rules of method overriding in Java 1. Argument list: The argument list of overriding method (method of child class) must match the Overridden method (the method of parent class). The data types of the arguments and their sequence should exactly match. 2. Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class. For e.g. if the Access Modifier of parent class method is public then the overriding method (child class method) cannot have private, protected and default Access modifier, because all of these three access modifiers are more restrictive than public. Prepared by: Raju Poudel [MCA] 34Another Example: AnimaLjava public class Animal{ public void sound(){ Systen.out.printIn(“Animal is making a sound"); Horse.java class Horse extends Aninal{ @override public void sound(){ System.out.println("Neigh’ + public static void main(String args[]){ Aninal obj = new Horse(); obj.sound(); Output: Neigh Recursion Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to Java programming, recursion is the attribute that allows a method to call itself. ‘A method that calls itself is said to be recursive. The classic example of recursion Is the computation of the factorial of @ number. The factorial of a number N is the product of all the whole numbers between 1 and N. For example, 3 factorial is 1 x 2 x 3, or 6. Here is how a factorial can be computed by use of a recursive method: Prepared by: Raju Poudel [MCA] as// ® simple example of recursion clase Factorial { // this is a recursive method int fact(int n) ( int result; if(n==1) return 1; result = fact(n-1) * n; return result; } } class Recursion { public static void main(String args{J) { Factorial f = new Factorial (); system.out.printin(*"Factorial of 3 is * + £.fact(3)); System.out .printIn("Factorial of 4 is " + £.fact (4); System.out.print1n(*"Factorial of 5 is * + £.fact (5)); } The output from this program is shown here: Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120 Introducing Nested and Inner Classes It is possible to define a class within another class; such classes are known as nesied classes. The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is defined within class A, then B does not exist independently of A. A nested class has access to the members, including private members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class. A nested class that is declared directly within its enclosing class scope is a member of its enclosing class. It is also possible to declare a nested class that is local to a block. There are two types of nested classes: static and non-static. A static nested class is one that has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used. The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. The following program illustrates how to define and use an inner class. The class named Outer has one instance variable named outer_x, one instance method named test{ ), and defines one inner class called Inner. Prepared by: Raju Poudel [MCA] 36// Demonstrate an inner class. class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner display (); } // this is an inner class class Inner { void display() { System. out .printIn(*display: outer_x = " + outer_x); } } } clase InnerClaseDemo { public static void main(String args{]) { Outer outer = new Outer(); outer.test(); } } Output from this application is shown here: display: outer_x = 100 In the program, an inner class named Inner is defined within the scope of class Outer. Therefore, any code in class Inner can directly access the variable outer_x. An instance method named display( ) is defined inside Inner. This method displays outer_x on the standard output stream. The main( ) method of InnerClassDemo creates an instance of class Outer and invokes its test{ ) method. That method creates an instance of class Inner and the display( ) method is called. Access Control ‘As you know, encapsulation links data with the code that manipulates it. However, encapsulation provides another important attribute: access control. Through encapsulation, you can control what parts of a program can access the members of a class. By controlling access, you can prevent misuse. For example, allowing access to data only through a well- defined set of methods, you can prevent the misuse of that data. Java’s access specifiers are public, private, and protected. Java also defines a default access level. protected applies only when inheritance is involved. Prepared by: Raju Poudel [MCA] a7Unit — 4 Inheritance & Packaging [3 Hrs. Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in java by which one class is allow to inherit the features (fields and methods) of another class. The process by which one class acquires the properties (dato members) and functionalities(methods) of another class is called inheritance. The aim of inheritance is to provide the reusability of code so that a class has to write only the unique features and rest of the common properties and functionalities can be extended from the another class. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also Inheritance represents the IS-A relationship which is also known as aparent- child relationship. inheritance is used in java for the following: © For Method Overriding (so runtime polymorphism can be achieved). © For Code Reusability. Terms used in Inheritance Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. © Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. © Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. Itis also called a base class or a parent class. © Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. The syntax of Java Inheritance class Subclass-name extends Superclass-name { //methods and fields + The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. In the terminology of Java, a class which is inherited Is called a parent or superclass, and the new class is called child or subclass. Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. Prepared by: Raju Poudel [MCA] a8Single Inheritance [crea | public class A ) public class B extends A { ca Multi Level inheritances = public class A{ d Clase 8 public class B extends A (. } public class Cextends 8 { } Multiple Inheritance public class A... public class B extends A (. public class C extends A {..ncnnnnnm) public class A ( ) public class B (. } public class Cextends A,B ( 11 Java does not support mutiple inheritance gle Inheritance Single Inheritance refers to @ child and parent class relationship where a class extends the another class. class Animal{ void eat(){ ‘System.out.printin("eating..."); 3 + class Dog extends Animal{ void bark(){ System.out.printin("barking..."); 3 + class TestInheritance{ public static void main(String args(]){ Dog d.bark(); dveat(); jew Dog(); Prepared by: Raju Poudel [MCA] 29eating. 2. Multilevel Inheritance Multilevel inheritance refers to a child and parent class relationship where a class extends the child class. For exemple, class C extends class B and class B extends class A. class Animal{ void eat(){ System.out.printin(“eating 3 + class Dog extends Animal{ void bark(){ System,out.printin("barking...” oa + class BabyDog extends Doot void weep(){ System.out.printin("weeping. 3 + class Testinheritance2{ public static void main(String args[1)< BabyDog d=new BabyDog(); d.weep(); dabark(); d.eat(); eating. Prepared by: Raju Poudel [MCA] 403. Hierarchical Inheritance Hierarchical inheritance refers to a child and parent class relationship where more than one classes extends the same class. For example, classes B, C & D extends the same class A. class Animal{ void eat(){ System.out.printin("eating..."); 3 } class Dog extends Animal{ void bark(){ System.out.printin("barking..."); 3 + class Cat extends Animal{ void meow(){ System.out.printin("meowina..."); 3 + class Testinheritance3{ public static void main(String args{])}{ Cat c=new Cat(); c.meow(); c.eat(); /Ic.bark(); //Etror //To access property of class Dog create object of class Dog Dog d=new Dog(); d.bark(); Multiple Inheritance When one class extends more than one classes then this is called multiple inheritance. For example: Class C extends class A and B then this type of inheritance is known as multiple inheritance. Java doesn't allow multiple inheritance. We can use interfaces instead of classes to achieve the same purpose. Prepared by: Raju Poudel [MCA] a1Interface in Java Like a class, an interface can have methods and variables, but the methods declared in interface are by default abstract (only method signature, no body) Interfaces specify what a class must do and not how. It is the blueprint of the class. ‘ An Interface Is about capabilities like @ Player may be an interface and any class implementing Player must be able to (or must implement] move (). So it specifies a set of methods that the class has to implement. ‘If a class implements an interface and does not provide method bodies for all functions speci the interface, then class must be declared abstract Syntax interface
{ // declare constant fields // declare methods that abstract // by default. To deciare an interface, use interface keyword. It is used to provide total abstraction. That means all the methods in interface are declared with empty body and are public and all fields are public, static and final by default. A class that implement interface must implement all the methods declared in the interface. To implement interface use implements keyword. Why do we use interface? + Itisused to achieve total abstraction. * Since java does not support multiple inheritance in case of cass, but by using interface it can achieve multiple inheritance. // & simple interface interface Player final int id = 10; int move(); Prepared by: Raju Poudel [MCA] a2Example of Interface // Java program to demonstrate working of // interface. import java.io.*; J/ & simple interface interface inl { // public, static and final final int a = 10; // public and abstract void display(); 3 J] A class that implements interface. class testClass implements ind { // Implementing the capabilities of I) interface. public void display() { System. out. printin(“Geek"); } // Driver Code public static void main (String[] args) { testClass t = new testClass(); t.display(); System. out .printin(a); 3 + Output: Geek 10 Prepared by: Raju Poudel [MCA]Use of Interface to achieve multiple inheritance Let us say we have two interfaces A & B and two classes C & D. Then we can achieve multiple inheritance using interfaces as follows: interface A{ } interface B{ } class C{ } class D extends C implements A,B { } Example Program interface interfacel{ void display1(); t interface interface2f] void display2(); W class A{ void display3() { System.out.print1n("I am inside class"); } } class B extends A implements interface1, interface2{ public void display1() { System.out.println("I am inside interfacei"); + public void display2() { System.out.print1n("I am inside interface2"); + } public class Multilevel { public static void main(String[] args) { B obj=new B(); obj-display1(); obj.display2(); obj. display3();| } } Output I am inside interfacel I am inside interface2 I am inside class Prepared by: Raju Poudel [MCA] a4Another Example interface interfacel{ int o=20,b=10; void add(); + class Ax{| int diff; void subtract (int x,int y) { diff=x-y; System.out.print1n("Subtraction= "+diff); ) q class Bx extends Ax implements interfacel{ int sum; public void add() { sum=a+b; System. out. print1n("Addition= "+sum) 5 + public class Multilevel { public static void main(String[] args) { Bx obj=new Bx()5 obj.add(); obj.subtract(50, f1);| Prepared by: Raju Poudel [MCA] 4sDynamic Method Dispatch Method overriding forms the basis for one of Java’s most powerful concepts: dynamic method dispatch. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism. Here is an example that illustrates dynamic method dispatch: // Dynamic Method Dispatch class A { void callme() { System.out .printIn("Inside A's callme method"); } 4 class B extends A { // override calime() void callme() { System.out .printin("Inside B's callme method") ; } ' class C extends A { // override calime() void callme() { System.out.printin("Inside C's callme method") ; } } class Dispatch { public static void main(String args{}) { Aa = new A(); // object of type A Bb = new B(); // object of type B Cc = new C(); // object of type C Ar; // obtain a reference of type A r =a; // x refers to an A object r.callme(); // calls A's version of callme x= b; // x refers to a B object r.callme(); // calls B's version of callme r=; // x refers to a C object r.callme(); // calls C's version of callme } } The output from the program is shown here: Inside A’s callme method Inside B’s callme method Inside C’s callme method Prepared by: Raju Poudel [MCA] 46This program creates one superclass called A and two subclasses of it, called B and C. Subclasses B and C override callme( ) declared in A. Inside the main( ) method, objects of type A,B, and C are declared. Also, a reference of type A, called r, is declared. The program then in turn assigns a reference to each type of object to r and uses that reference to invoke callme{ ). As the output shows, the version of callme( ) executed is determined by the type of object being referred to at the time of the call. Had it been determined by the type of the reference variable, r, you would see three calls to A’s callme( ) method. Super Keyword The super keyword in java is @ reference variable that is used to refer parent class objects. The keyword “super” came into the picture with the concept of Inheritance. It is majorly used in the following contexts: 1, Use of super with variables: This scenario occurs when a derived class and base class has same data members. In that case there is a possibility of ambiguity for the JVM. We can understand it more clearly using this code snippet: /* Base class vehicle */ class Vehicle { + int maxSpeed - 120; /* sub class Car extending vehicle */ class Car extends Vehicle { int maxSpeed = 180; void display() { /* print naxSpeed of base class (vehicle) */ System.out.printIn( "Maximum Speed: " + super.maxSpeed) ; } } /* Driver program to test */ class Test { public static void main(String[] args) { Car small = new Car()5 small.display(); Output: Maximum Speed: 120 Prepared by: Raju Poudel [MCA] a7In the above example, both base class and subclass have a member maxSpeed. We could access maxSpeed of base class in subclass using super keyword. 2. Use of super with methods: This is used when we want to call parent class method. So whenever a parent and child class have same named methods then to resolve ambiguity we use super keyword. This code snippet helps to understand the said usage of super keyword. /* Base class Person */ class Person { void message() System.out.println(“This is person class"); } /* Subclass Student */ class Student extends Person { void message() { System.out.printin("This is student class" + J] Note that display() is only in Student class void display() J/ will invoke or call current class message() method message(s 1/ will invoke or call parent class message() method super.message(); + } /* Driver program to test class Test t public static void main(String args[]) { Student s = new Student()5 I/ calling displey() of Student s.display(); + t Output This is student class This is person class In the above example, we have seen that if we only call method message () then, the current class message () is invoked but with the use of super keyword, message () of superclass could also be invoked. Prepared by: Raju Poudel [MCA] 483. Use of super with constructors: super keyword can also be used to access the parent class constructor. One more important thing is that, ‘super’ can call both parametric as well as non-parametric constructors depending upon the situation. Following is the code snippet to explain the above concept: /* superclass Person */ class Person t Person() { System. out.printIn("Person class Constructor } } /* subclass Student extending the Person class */ class Student extends Person t Student() { // invoke or call parent class constructor super()5 System.out.printIn("Student class Constructor"); } + /* Driver program to test*/ class Test { public static void main(String[] args) { Student s = new Student(); t } Output: Person class Constructor Student class Constructor In the above example we have called the superclass constructor using keyword ‘super’ via subclass constructor. Prepared by: Raju Poudel [MCA] 49Abstract and Final Classes Abstract class has been discussed already in Unit-3 (Abstraction). The keyword final has three uses. First, it can be used to create the equivalent of anamed constant. The other two uses of final apply to inheritance. Using final to Prevent Overriding While method overriding is one of Java’s most powerful features, there will be times when you will want to prevent it from occurring, To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. The following fragment illustrates final: class A { final void meth() { System.out .printin(*This is a ) ) 1 method.) ; class B extends a { void meth() { // ERROR! Can’ System. out .print1n(*Tilegal!*) ; } } Because meth () is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-time error will result. Using final to Prevent Inheritance Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as, final, too. As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations. Here is an example of a final class: final W ) ase A { // The following class class B extends A { / Wi ) 2 {2legal ROR! Can't subclass A As the comments imply, itis illegal for B to inherit A Since A is declared as final. Prepared by: Raju Poudel [MCA] 50The Object Class There is one special class, Object, defined by Java. All other classes are subclasses of Object. That is, Object is a superclass of all other classes. This means that a reference variable of type Object can refer to an object of any other class. Also, since arrays are implemented as classes, a variable of type Object can also refer to any array. Object defines the following methods, which means that they are available in every object Method Jobject clone( ) boolean equais(Object object) void finalize ) Class getClass( ) int hashCode( ) void notify( ) [void nouityAlK ) String toString( ) [void wait) void wait(long milliseconds) |void waitiiong milisecones, int nanoseconds) Purpose Creates new object that is the same as the object being cloned. Determines whether one object is equal to another. Called before an unused object is recycled. Obtains the class of an object at run time. Returns the hash code associated with the invoking object. Resumes execution of a thread waiting on the invoking abject. Resumes execution of all threads waiting on the invoking object. Returns a string that describes the object. ‘Waits on another thread of execution, The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may override the others. However, notice two methods now: equals( ) and toString( ). The equals( ) method compares the contents of two objects. It returns true if the objects are equivalent, and false otherwise. Package A Java package Is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Advantage of Java Package 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision. The package keyword is used to create 2 package in java. //save as Simple.java package mypack; public class Simple< public static void main(String args[]){ System.out.printin("Welcome to package"); + + Prepared by: Raju Poudel [MCA] 51There are three ways to access the package from outside the package. 1. import package.*; 2. import package.classname; 3. fully qualified name. If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages. The import keyword is used to make the classes and interface of another package accessible to the current package. //save by A.java package pack; public class At public void msg(){System.out.printin(“Hello");} ? I/save by Bjava package mypack; import pack.A; class BE public static void main(String args[]){ A obj = new A(); obj.msg(); + > Output :Helle ‘Subpackage in java Package inside the package Is called the subpackage. package java.util. Scanner; class Simplet public static void main(String args[]){ ‘Scanner scan=new Scanner(System. ‘System.out.printin("Enter a number"); int a = scan.nextint(); ‘System.out.printin(“Inputted number is: “+a); +} Prepared by: Raju Poudel [MCA] 52Unit — 5 Handling Error/Exceptions [2 Hr: ‘An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e. atrun time, that disrupts the normal flow of the program's instructions. Error vs Exception Error: An Error indicates serious problem that a reasonable application should not try to catch. Exception: Exception indicates conditions that a reasonable application might try to catch. ‘An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled ‘An exception can occur for many different reasons. Following are some scenarios where an exception occurs. + Auser has entered an invalid data. + file that needs to be opened cannot be found. + Anetwork connection has been lost in the middle of communications or the JVM has run out of memory. Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. Based on these, we have three categories of Exceptions. You need to understand them to know how exception handling works in Java. * Checked exceptions - A checked exception is an exception that is checked (notified) by the compiler at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply be ignored; the programmer should take care of (handle) these exceptions. * Unchecked exceptions - An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. «Errors - These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise, They are also ignored at the time of compilation. Prepared by: Raju Poudel [MCA] 53Hierarchy of Java Exception classes The java.lang, Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below: Prepared by: Raju Poudel [MCA] saJava Exception Keywords There are 5 keywords which are used in handling exceptions in Java. Keyword |Description try The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone. catch The “catch” block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. finally ‘The “finally” block Is used to execute the Important code of the program. It is executed whether an exception is handled or not. throw The "throw" keyword is used to throw an exception. throws | The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies thet there may occur an exception in the method. It is always used with method signature. Java Exception Handling Example Let's see an example of Java Exception Handling where we using a try-catch statement to handle the exception. public class JavaExceptionExample{ void main(String args[])< //code that may raise exception int data=100/0; }eatch(ArithmeticException e) { ‘System.out.printin(e); + /irest code of the program System.out.printin("rest of the cod. > + Output: Exception in thread main java.lang.A rest of the co hmeticException:/ by zero Prepared by: Raju Poudel [MCA] 55Common Scenarios of Java Exceptions There are given some scenarios where unchecked exceptions may occur. They are as follows 1) A scenario where ArithmeticException occurs If we divide any number by zero, there occurs an ArithmeticException int a=50/0;//Arithmeticexception 2) A scenario where NullPointertxception occurs If we have a null value in any variable, performing any operation on the variable throws a NuliPointerException String s=null; System. out.printin(s.length());//NullPointerException 3) A scenario where NumberFormat€xception occurs The wrong formatting of any value may occur NumberFormatException. Suppose | have a string variable that has characters, converting this variable into digit will occur NumberFormatException. String "5 int i=Integer.parseint(s);//NumberFormatéxception ‘abc’ 4) A scenario where ArrayindexOutOfBoundsException occurs If you are inserting any value in the wrong index, it would result in ArrayindexOutOfBoundsException as shown below: int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException Java finally block Java finally block is a block that is used to execute important code such as closing connection, stream etc. Java finally block is always executed whether exception is handled or not. Java finally block follows try or catch block. public class TestFinallyBlock2{ public static void main(String args[]){ try{ int data=25/0; ‘System.out.printin(data);, > catch(ArithmeticException e){ System.out.printin(e); 3 finally{ ‘System.out. printin("finally block is always executed"); Prepared by: Raju Poudel [MCA] 56+ ‘System.out.printin(“rest of the code..."); Exception in thread main java.lang.Arithmeticaxception:/ by zero finally block is always executed rest of the code... Java Multi-catch block A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block. At a time only one exception occurs and at a time only one catch block is executed. All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception. public class MultiplecatchBiock1 { public static void main(String[] args) { try{ int a[]=new int[5]; a[5]=30/0; + catch(Arithmeticexception e) < System.out.printin("Arithmetic Exception occurs"); 3 catch (ArrayIndexOutOfBoundsException e) { ‘System.out printin("ArrayindexOutOfBounds Exception occurs"); + catch(Exception e) { System.out:printin("Parent Exception occurs"); 3 System.out.printin("rest of the code"); Qutput: Arithmetic Exception occurs rest of the code Prepared by: Raju Poudel [MCA] 87public class MultipleCatchBlock2 { public static void main(String[] args) { tryt int a[]=new int[5]; System.out.printin(a[10}); + catch (ArithmeticException e) { ‘System.out.printin("Arithmetic Exception occurs"); + catch (ArrayIndexOutofBoundsExceotion e) { ‘System.out.printin("ArrayindexOutOfBounds Exception occurs"); + catch(Exception e) t ‘System.out.printin("Parent Exception occurs"); 3 System.out.printin("rest of the code"); + > Output: ArraylndexOutofBounds Exception occurs rest of the code Java Nested try block The try block within a try block is known as nested try block in java. Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested. Syntay try { statement 1; statement 2; try { statement 1 statement 2; } Prepared by: Raju Poudel [MCA] 58catch(Exception e) } } catch(Exception e) { } Example: class Excep6{ public static void main(String args[])< try{ try System.out.printin("going to divide"); int b =39/0; }eatch(Arithmeticexception e){ System.out.printin(e); 3 try{ int a[]=new int[5]; a[S]}=4; }eatch (ArrayIndexOutOfBoundsException e){ System. out.printin(e); > System out printin(“other statement); }eatch(Exception e){ System.out.printin("handeled"); + System.out.printin("normal flow.."); + + Prepared by: Raju Poudel [MCA] 59Java throw keyword The Java throw keyword is used to explicitly throw an exception. We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. The syntax of java throw keyword is given below. throw new lOException("sorry device error); Example: In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote. public class TestThrow1{ static void validate(int age){ if(age<18) throw new Arithmeticexception( "not valid"); else System.out.printin("welcome to vote"); 3 public static void main(String args[]){ validate( 13); System.out.printin("rest of the code..."); thread main java.lang.ArithneticException:not valid Java throws keyword The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained. Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing checkup before the code being used. Syntax of java throws return_type method_name() throws exception_class_neme{ //method code + Prepared by: Raju Poudel [MCA] 60Example of Java throws import java.io.IOException; class Testthrowsi{ void m()throws IOException{ throw new IOException("device error");//checked exception y void n()throws IOException{ m0; } void p(){ try{ nQ; }catch(Exception e){ System.out.printin(“exception handled"); y } public static void main(String aras[]){ Testthrows1 obj=new Testthrows1(); 0bj-p0;, System.out printin(“normal flow. + + Output: exception handled nozmal flow... Difference between throw and throws in Java No. | throw throws 1)| Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception. 2)| Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws. 3) |__ Throw is followed by an instance. ‘Throws is followed by class. 4)| Throw is used within the method. Throws is used with the method signature. 5)| You cannot throw ~— multiple |_ You can declare multiple exceptions e.9. exceptions. public void method()throws IOException, SQLException. Prepared by: Raju Poudel [MCA] 61Unit — 5 Handling Strings [2 Hrs. String Creation Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object. In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example: char] ch={'j'a',V',a','t,'py'0''7'0','t 5 String s=new String(ch); is same as: String s="Javatpoint"; There are two ways to create String object: 1._By string literal 2. By new keyword 4) String Li Java String literal is created by using double quotes. For Example: String s="welcome"; Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. For example: String st String s2="Welcome";//It doesn't create a new instance 2) By new keyword String s=new String("Welcome');//creates two objects and one reference variable 'Welcome"; Java String Example public class StringExample( public static void main(String aras{]{ String s1="java";//creating string by java string literal char ch{J={'s't"y''/10,'94's'}; String s2=new String(ch);//converting char array to string String s3=new String(“example");//creating java string by new keyword ‘System.out.printin(s1); System.out.printin(s2); System.out.printin(s3); » Output java strings example Prepared by: Raju Poudel [MCA] 62String Length The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, shown here: int length() The following fragment prints “3”, since there are three characters in the string s: char chars{] = {'a', 'b', 'c' }; String s = new String(chars); System,out.printin(s.iength()); Concatenation of String The following fragment concatenates three strings: String age = "9"; String s= "He is " + age + years old.”; System.out.printin(s); This displays the string “He is 9 years old.” One practical use of string concatenation is found when you are creating very long strings. Instead of letting long strings wrap around within your source code, you can break them into smaller pieces, using the + to concatenate them. Here is an example: // Using concatenation to prevent long lines. class ConCat { static void main(String args[]) { String longstr = "This could have been " + "a very long line that would have" + “wrapped around. But string concatenation " + “prevents this."; System.out printin(longstr); } } String Concatenation with Other Data Types You can concatenate strings with other types of data. For example, consider this slightly different version of the earlier example: intage String s= "He is" + age +" years old.”; System.out.printin(s); In this case, age is an int rather than another String, but the output produced is the same as before. This is because the int value in age is automatically converted into its string representation within a String object. This string is then concatenated as before. Be careful when you mix other types of operations with string concatenation expressions, however, you might get surprising results. Consider the following: String s= "four." +2 +2; System.out.printin(s); This fragment displays four: 22 rather than the four: 4 Prepared by: Raju Poudel [MCA] 63To complete the integer addition first, you must use parentheses, like this: String s = "four: " + (2+ 2); Now s contains the string “four: 4”. Conversion of String Conversion of any type to String use, a. String.valueOf( ) b. toString( ) + Conversion of String to any type use, a. any_type.parse() Converting any type to String: public class Conversion { public static void main(String[] args) { int a=10; double b=5.5; //Converting other types to String String s1=String.valueof(a); String s2-String.valueOf(b); //concatination of tuo strings String s3=s1+s2; System. out. println(s3) ; t + Output: 105.5 Converting String to any type: public class Conversion { public static void main(String[] args) { String si= String s2. //converting String to Integer int a=Integer.parseInt(s1); //converting String to Double double ouble. parseDoubLe(s2) ; double F8S=(double)a+b; System.out.printin("Result= "#Pes); Prepared by: Raju Poudel [MCA] 6aChanging case of String The method toLowerCase( } converts all the characters in a string from uppercase to lowercase. The toUpperCase( ) method converts all the characters in a string from lowercase to uppercase. Non alphabetical characters, such as digits, are unaffected. Here isan example that uses toLowerCase( } and toUpperCasel ): // Demonstrate toUpperCase() and toLowerCase() class ChangeCase { public static void main(String args{]) { String s = "This is a test."; System.out.println("Original: " + s); string upper = s,touppercase(); String lower = s.toLowerCase(); System.out.print1n("Uppercase: " + upper); System.out.printin("Lowercase: " + lower); } + Output Original: This is a test. Uppercase: THIS IS A TEST. Lowercase: this is a test. Character Extraction The String class provides a number of ways in which characters can be extracted from a String object. Although the characters that comprise a string within a String object cannot be indexed as if they were a character array, many of the String methods employ an index (or offset) into the string for their operation. Like arrays, the string indexes begin at zero. charAt() To extract a single character from a String, you can refer directly to an individual character via the charAt() method. It has this general form: char charAt(int where) Here, where is the index of the character that you want to obtain. The value of where must be nonnegative and specify a location within the string. charAt{ ) returns the character at the specified location. For example, char ch; ch = “abe".charAt(1); assigns the value “b” to ch. Prepared by: Raju Poudel [MCA] 6s.getChars| If you need to extract more than one character at a time, you can use the getChars( ) method. Ithas this general form: void getChars(int sourceStart, int sourcetnd, char target{ ], int targetStart) Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. Thus, the substring contains the characters from sourceStart through sourceEnd1. The array that will receive the characters — is specified by target. The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring. class getCharsDeno { public static void main(String args[]) { String s = "This is a demo of the getChars method."; int start = 10; int end = 14; char buf[] = new char[end - start]; s.getChars(start, end, buf, @); System.out.println(buf); t Output demo String Comparison There are three ways to compare string in java: 1. By equals() method 2. By == operator 3. By compareTo() method 1) String compare by equals() method The String equals() method compares the original content of the string. it compares values of string for equality. String class provides two methods: © public boolean equals(Object another) compares this string to the specified object. © public boolean equalslgnoreCase(String another) compares this String to another string, ignoring case class Teststringcomparison1{ public static void main(String args{})< String s1="Sachin’ String s2="Sachin"; String s3=new String("Sachin"); String s4="Saurav"; ‘System.out.printin(s1.equals(s2));//true Prepared by: Raju Poudel [MCA] 66System.out.printin(s1.equals(s3));//true ‘System.out.printin(s1.equals(s4)); //false + + ‘Output true true false class Teststringcomparison2{ public static void main(String args[]){ System.out.printin(s1.equals(s2)); //false System.out.printIn(s1.equalsignoreCase(s2));//true compare by compareTo() method The java string compareTo() method compares the given string with current string lexicographically. It returns positive number, negative number or 0. It compares strings on the basis of Unicode value of each character in the strings. if s1 > s2, it returns positive number si < 52, it returns negative number if st == 52, itreturns 0 public class CompareToExample{ public static void main(String args[]){ String 53 ‘System.out.printin(s1.compareTo(s2));//0 because both are equal ‘System.out. printin(s1.compareTo(s3));//- 5 because "h" is 5 times lower than "m’ 3} Output Prepared by: Raju Poudel [MCA] 67Searching Strings The String class provides two methods that allow you to search a string for a specified character or substring: * indexOf{ ) Searches for the first occurrence of a character or substring. + lastIndexOf( ) Searches for the last occurrence of a character or substring To search for the first occurrence of a character, use int indexOffint ch) To search for the last occurrence of a character, use int lastindexOf(int ch) Here, ch is the character being sought. To search for the first or last occurrence of a substring, use int indexOf(String str) int lastindexOfString str) Here, str specifies the substring. You can specify a starting point for the search using these forms: int indexOf(int ch, int startindex) int lastindexOf{int ch, int startindex) int indexOf(String str, int startIndex) int lastindexOf{String str, int startindex) Here, startindex specifies the index at which point the search begins. For indexof( ), the search runs from startIndex to the end of the string. For lastindexOf( }, the search runs from startindex to zero. // Demonstrate indexOf() and lastIndex0f(). class indexofpemo { public static void main(String args[]) { String § = "Now is the time for all good men "to come to the aid of their country."; System. out.printin(s); System.out.printIn("indexOf(t) = 5. indexoF('t')); Systen.out.printin("lastIndexOF(t) = " 5.lastIndexOF('t')); System.out.printin(” 5.indexOf("the")); System.out.printin("lastIndexOf(the) = " + §.lastIndexOf("the")) System.out.printin("indexOf(t, 1¢) = "+ S.indexOf('t', 10)); System.out.println("lastIndexOf(t, 6@) S.lastIndexOf('t', 6@)); + + ndexOf(the) = * + System. out.printIn("indexOf(the, 10) + S.indexOF("the", 10)); System.out.println("lastIndexOf(the, 60) = "+ §.lastIndexOF("the", 60)); Prepared by: Raju Poudel [MCA] 68Output Now is the time for all good men to come to the aid of their country. indexOf(t) = 7 lastIndexOf(t) = 65 indexOf(the) = 7 lastindexOf(the) = 55 indexOf(t, 10) = 11 lastIndexOf(t, 60) = 55 indexOf(the, 10) = 44 lastIndexOf(the, 60) = 55 Modifying a String substring) The java string substring() method returns a part of the string. We pass begin index and end index number position in the java substring method where start index is inclusive and end index is exclusive. In other words, start index starts from 0 whereas end index starts from 1. There are two types of substring methods in java string, substring(int startindex) and substring(int startindex, int endindex) Examples public class SubstringExample{ public static vold main(String aras[]){ String s1="javatpoint"; System.out.printin(s1.substring(2,4));//returns va System.out. printin(s1.substring(2));//returns vatpoint oe class SubstringExample2 { public static void main(String[] args) { String s1="Javatpoint"; String substr = s1.substring(0); // Starts with 0 and goes to end System.out.printin(substr); String substr2 = s1.substring(5,10); // Starts from 5 and goes to 10 System.out.printIn(substr2); String substr3 = si.substring(5,15); // Returns Exception Prepared by: Raju Poudel [MCA] 69Output Javatpoint Exception in thread "main" Java. lang. StringindexoutOzBoundszxception: begin 5, end 15, length io concat() You can concatenate two strings using coneat( ), shown here: String concat(string str) This method creates a new object that contains the invoking string with the contents of str appended to the end. concat( ) performs the same function as +. For example, String s1 = "one" String s2 = s1.concat("two"); puts the string “onetwo” into s2. It generates the same result as the following sequence: String s1 = "one" String s2 = si +"two"; replace| The java string replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence. There are two type of replace methods in java string. 1. repiace(char oldChar, char newChar) and 2. repiace(CharSequence target, CharSequence replacement) Java String replace(char old, char new) method example class Replaceexample1{ stati main(String args{]){ String s1="javatpoint is a very good website"; String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e" System.out.printIn(replaceString); 3} Output Jevetpoint is © very good website Java String replace(CharSequence target, CharSequence replacement) method example public class ReplaceExample2{ public static void main(String args[]){ String s1="my name is khan my name is java"; String replaceString=s1..replace("is","was");//replaces all occurrences of "is" to" was" System,out.printin(replaceString); 3} Output my name was khan my nane was java Prepared by: Raju Poudel [MCA] 70trim| The java string trim() method eliminates leading and trailing spaces. The unicode value of space character is "\u0020'. The trim() method in java string checks this unicode value before and after the string, if it exists then removes the spaces and returns the omitted string. public class StringTrimExample { public static void main(String[] args) { String s1 =" hello java string"; System.out.printin(s1.length()); system.out.printin(s1); //Without trim() String tr = si.trim(Q); System.out.printin(tr-length()); System.out.printin(tr); //With trim() hello java string v hello java string String Buffer Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable ie. it can be changed. A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string. Important Constructors of StringBuffer class Constructor Description StringBuffer() creates an empty string buffer with the initial capacity of 16. StringBuffer(String str) creates a string buffer with the specified string. StringBuffer(int creates an empty string buffer with the specified capacity) capacity as length. Prepared by: Raju Poudel [MCA] aImportant methods of StringBuffer class Method Description append(String s) is used to append the specified string with this string, The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc. insert(int offset, String s) is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc. replace(int startindex, int endindex, String str) is used to replace the string from specified startIndex and endindex. delete(int startindex, int is used to delete the string from specified startIndex and endindex) endindex. reverse() Is used to reverse the string. capacity() Is used to return the current capacity. ensureCapactty(int minimumCapacity) Is used to ensure the capacity at least equal to the given minimum. charAt(int index Is used to return the character at the specified position. length() Is used to return the length of the string i.e. total number of characters. substring(int beginIndex) is used to return the substring from the specified beginIndex. substring(int beginIndex, int endIndex) is used to return the substring from the specified beginIndex and endIndex. 1) St Buffer append() method The append() method concatenates the given argument with this string. class StringBufferExample¢ public static v StringBuffer st id main(String args[]){ new StringBuffer("Hello "); sb.append("Java");//now original string is changed System.out.printin(sb);//prints Hello Java + Prepared by: Raju Poudel [MCA] 722) StringBuffer insert() method The insert() method inserts the given string with this string at the given position. class StringBufferExample2{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello "); sb.insert(1,"Java");//now original string is changed System.out.printin(sb);//prints HJavaello + 3 3) StringBuffer replace() method The replace() method replaces the given string from the specified beginindex and endindex. class StrinaBufferExample3{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello"); sb.replace(1,3,"Java"); System.out.printin(sb);//prints HJavalo + i 4) StringBuffer delete() and deleteCharAt() method The delete|) method of StringBuffer class deletes the string from the specified beginindex to endindex. class StringBufferExample4{ public static void main(String args{]){ StringBuffer sb=new StringBuffer("Hello"); sb.delete(1,3); System.out.printin(sb);//prints Hlo fate delete() and deleteCharat ebemo ( Public static void main(String args{l) ( sb.delete(4, 7); Systen.out .printin(*After delete: " + eb); sb.deletecharat (0); Systen.out .printin( , ) ‘The following output is produced: fer deleteCharAt: * + sb); After delete: This a test After deleteCharAt: his a test. Prepared by: Raju Poudel [MCA] 73
You might also like
Oop in Java Note
PDF
No ratings yet
Oop in Java Note
150 pages
Chapter 2-Introduction To Java
PDF
No ratings yet
Chapter 2-Introduction To Java
31 pages
Java_Notes_Complete_year 2
PDF
No ratings yet
Java_Notes_Complete_year 2
149 pages
JAVA
PDF
No ratings yet
JAVA
43 pages
Chapter 1 Java Platform Overview
PDF
No ratings yet
Chapter 1 Java Platform Overview
26 pages
What Is Java Lecture1
PDF
No ratings yet
What Is Java Lecture1
14 pages
Javanotes
PDF
No ratings yet
Javanotes
50 pages
Java - Unit I
PDF
No ratings yet
Java - Unit I
41 pages
Introduction To JAVA
PDF
No ratings yet
Introduction To JAVA
24 pages
Java book
PDF
No ratings yet
Java book
124 pages
Java Notes
PDF
No ratings yet
Java Notes
95 pages
Class IX Chapter 2
PDF
No ratings yet
Class IX Chapter 2
36 pages
Java Platform Overview
PDF
No ratings yet
Java Platform Overview
44 pages
Introduction
PDF
No ratings yet
Introduction
36 pages
1.java Introduction
PDF
No ratings yet
1.java Introduction
30 pages
Week 1
PDF
No ratings yet
Week 1
219 pages
Unit-1 Java
PDF
No ratings yet
Unit-1 Java
49 pages
Doc Lm Unit1
PDF
No ratings yet
Doc Lm Unit1
20 pages
Java Basics
PDF
No ratings yet
Java Basics
130 pages
Chapter 1
PDF
No ratings yet
Chapter 1
10 pages
java overview-unit I
PDF
No ratings yet
java overview-unit I
48 pages
A Project Report of ISM On Role of Java in Market
PDF
No ratings yet
A Project Report of ISM On Role of Java in Market
17 pages
Core Java Unit 1
PDF
No ratings yet
Core Java Unit 1
30 pages
9.introduction To Java
PDF
No ratings yet
9.introduction To Java
46 pages
Chap1introduction To Java
PDF
No ratings yet
Chap1introduction To Java
13 pages
JAVA Unit 1 Java Material
PDF
No ratings yet
JAVA Unit 1 Java Material
63 pages
Installing Eclipse
PDF
No ratings yet
Installing Eclipse
236 pages
Fundamental Concept For Java Programming
PDF
93% (14)
Fundamental Concept For Java Programming
904 pages
Core Java
PDF
No ratings yet
Core Java
27 pages
Chapter 1 Java
PDF
No ratings yet
Chapter 1 Java
25 pages
Cbcs b.sc. Vi Sem Paper i
PDF
No ratings yet
Cbcs b.sc. Vi Sem Paper i
62 pages
Unit-I 1JavaBAsic Intro
PDF
No ratings yet
Unit-I 1JavaBAsic Intro
48 pages
Java Notes
PDF
No ratings yet
Java Notes
27 pages
Core Java
PDF
No ratings yet
Core Java
550 pages
JAVA Notes-1 PDF
PDF
No ratings yet
JAVA Notes-1 PDF
122 pages
Java OOPS Notes
PDF
No ratings yet
Java OOPS Notes
136 pages
Brick Game: Midterm Report ON
PDF
No ratings yet
Brick Game: Midterm Report ON
12 pages
What Is Java
PDF
No ratings yet
What Is Java
20 pages
Java Core
PDF
No ratings yet
Java Core
123 pages
5_6251230375687750711
PDF
No ratings yet
5_6251230375687750711
59 pages
Java Training Report
PDF
No ratings yet
Java Training Report
44 pages
KCA 202 OOP Unit 1 - 240429 - 111726
PDF
No ratings yet
KCA 202 OOP Unit 1 - 240429 - 111726
24 pages
Java-Ref. Notes
PDF
No ratings yet
Java-Ref. Notes
59 pages
Introduction to Java
PDF
No ratings yet
Introduction to Java
15 pages
Object Oriented Programming Language Using Java: Bca 5 Sem - Prepared by Roopa S
PDF
No ratings yet
Object Oriented Programming Language Using Java: Bca 5 Sem - Prepared by Roopa S
23 pages
Chapter One: Structure Programming
PDF
No ratings yet
Chapter One: Structure Programming
12 pages
Java Tutorial
PDF
No ratings yet
Java Tutorial
145 pages
CSP 45 Java B1 1568720246
PDF
No ratings yet
CSP 45 Java B1 1568720246
104 pages
963.introduction To Java
PDF
No ratings yet
963.introduction To Java
15 pages
Java Basics
PDF
No ratings yet
Java Basics
8 pages
About The Java Technology
PDF
No ratings yet
About The Java Technology
5 pages
JAVA1
PDF
No ratings yet
JAVA1
42 pages
Java Notes (Nep Syllabus)
PDF
100% (1)
Java Notes (Nep Syllabus)
133 pages
Lecture 1
PDF
No ratings yet
Lecture 1
22 pages
Java Programming Basics-Min
PDF
No ratings yet
Java Programming Basics-Min
68 pages
2-Introduction To Java Basics, Types of Java Application and Features-14-Jul-2020Material - I - 14-Jul-2020 - Lecture1-Features - of - Java
PDF
No ratings yet
2-Introduction To Java Basics, Types of Java Application and Features-14-Jul-2020Material - I - 14-Jul-2020 - Lecture1-Features - of - Java
11 pages
Unit 1_Chapter1
PDF
No ratings yet
Unit 1_Chapter1
11 pages