0% found this document useful (0 votes)
2 views51 pages

Java Programming Unit 1 Notes

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995. It supports various types of applications including standalone, web, enterprise, and mobile applications, and is known for its portability, security, and dynamic features. Java's architecture includes the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), which facilitate the execution and development of Java applications.

Uploaded by

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

Java Programming Unit 1 Notes

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995. It supports various types of applications including standalone, web, enterprise, and mobile applications, and is known for its portability, security, and dynamic features. Java's architecture includes the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), which facilitate the execution and development of Java applications.

Uploaded by

kokilasmile16178
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
UNIT: 1 Introduction to Java Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure programming language. Java was developed by Sun Microsystems in the year 1995, James Gosling is known as the fatherof Java. Before Java, its name was Oak. Since Oak was already a registered company, so James Gosling and his team changed the name from Oak to Java. Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java has a runtime environment (JRE) and API, itis called a platform. Example: [Link] class Simple { public static void main(String args{]) { ‘[Link](""Hello Java" t } ‘There are many devices where Java is currently used. Some of them are as follows: 1. Desktop Applications such as acrobat reader, media player, antivirus, etc. Web Applications such as [Link], [Link], etc. Enterprise Applications such as banking applications. Mobile Embedded System ‘Smart Card Robotics 8 Games, etc, Noyawn Types of Java Applications There are mainly 4 types of applications that can be created using Java programming: Standalone Application ‘Standalone applications are also known as desktop applications or window-based applications. These are traditional software that we need to install on every machine. Examples of standalone application are Media player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications. ‘Web Application An application that runs on the server side and creates a dynamic page is called a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web applications in Java. Enterprise Application An application that is distributed in nature, such as banking applications, etc. is called an enterprise application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is used for creating enterprise applications. Mobile Ap; ‘An application which is created for mobile devices is called a mobile application. Currently, Android and Java ME are used for creating mobile applications. ion Java Platforms / Editions There are 4 platforms or editions of Java: Java SE (Java Standard Edition) It is a Java programming platform. It includes Java programming APIs such as [Link], [Link] [Link], [Link], [Link], [Link] etc. It includes core topics like OOPs, String, Regex, n, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc. Java EE (Java Enterprise Edition) It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built on top of the Java SE platform. It includes topics like Servlet, ISP, Web Services, EJB, JPA, ete. Java ME (Java Micro Edition) It is a micro platform that is dedicated to mobile applications. JavaFX It is used to develop rich internet applications. It uses a lightweight user interface API. Features of Java The primary objective of Java programming language creation was to make it portable, simple and secure programming language. Apart from this, there are also some excellent features which play an important role in the popularity of this language. The features of Java are also known as Java buzzwords. 1. Simple 2. Object-Oriented 3. Portable 4, Platform independent 5. Secured 6. Robust 7. Architecture neutral 8. Interpreted 9. High Performance 10. Multithreaded 11. Distributed 12. Dynamic simple Java is very easy to learn, and its syntaxis simple, clean and easy to understand. According to Sun Microsystem, Java language is a simple programming language because: © Java syntax is based on C++ (so easier for programmers to learn it after C+). © Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc. 9 There isno need to remove unreferenced objects because there is an Automatic Garbage Collection in Java. Object-oriented Java is an object-oriented programming language. Everything in Java is an object. Object- oriented means the software is organized as a combination of different types of objects that incorporate both data and behavior. Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules. Basic concepts of OOPs are: 1. Object 2. Class 3. Inheritance 4. Polymorphism 5. Abstraction 6. Encapsulation Portable Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't, require any implementation Platform Independent Java is platform independent because itis different from other languages like C, C++, etc, which are compiled into platform specific machines while Java is a write once, run anywhere language. platforms the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based, Java provides a software- based platform. The Java platform differs from most other platforms in the sense that it is 2 software-based platform that runs on top of other hardware-based platforms. It has two components: 1. Runtime Environment 2. API(Application Programming Interface) Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, ete. Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere (WORA). Secured Java is best known for its security. With Java, we can develop virus-free systems, Java is secured because: © No explicit pointer © Java Programs run inside a virtual machine sandbox © Classloader: Classloader in Java is a part of the Java Runtime Environment (IRE) which is Used to load Java classes into the Java Virtual Machine dynamically. it adds security by separating the package for the classes of the local file system from those that are imported from network sources. © Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects. © Security Manager: It determines what resources a class can access such as reading and writing to the local disk. Java language provides these securities by default. Some security can also be provided by an application developer explicitly through SSL, JAAS, Cryptography, etc. Robust The English meaning of Robust is strong. Java is robust because: © Ituses strong memory management. © There isa lack of pointers that avoids security problems, © Java provides automatic garbage collection which runs on the Java Virtual Machine to get 6 rid of objects which are not being used by a Java application anymore. © There are exception handling and the type checking mechanism in Java. All these points make Java robust. Architecture-neutral Java is architecture neutral because there are no implementation dependent features, for ‘example, the size of primitive types is fixed. In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64- bit architectures in Java High-performance Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc. Distributed Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet. Multi-threaded A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading, is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc. Dynamic Java is a dynamic language. It supports the dynamicloading of classes. It means classes are loaded ‘on demand. It also supports functions from its native languages, i.e., Cand C+, Java supports dynamic compilation and automatic memory management (garbage collection). C++ vs Java The basic differences between c++ and Java are: Comparison Index Platform- independent Mainly used for Goto Multiple inheritance Operator Overloading Pointers Compiler and Interpreter Call by Value and Call by reference cH C++ is platform-dependent. C++ is mainly used for system programming, C+ supports the goto statement. C++ supports multiple inheritance. CH overloading. supports operator C++ supports pointers. You can write a pointer program in C++ C++ uses compiler only. CH is compiled using the compiler which converts source code into machine code so, C++ is platform dependent. and run (C++ supports both call by value and call by reference. Java Java is platform-independent. Java is mainly used for application programming, It is widely used in Windows- based, web-based, enterprise, and mobile applications. Java doesn't support the goto statement. Java doesn't support multiple inheritance through class. It can be achieved by using interfaces in java. Java doesn't support operator overloading. Java supports pointer internally. However, you can't write the pointer program in java. It means java has restricted pointer support in java. Java uses both compiler and interpreter. Java source code is converted into bytecode at compilation time. The interpreter executes this bytecode at runtime and produces output. Java is interpreted that is why it is platform-independent. Java supports call by value only. There is no call by reference in java. Structure and C++ supports structures and Union unions. Documentation CH doesn't support comment documentation comments. Object-oriented C++ is an object-oriented language. However, in the C language, a single root hierarchy not possible. is Note © Java doesn't support default arguments like C++. © Java does not support header files like C++, Java different classes and methods. C++ Program Example File: [Link] Java doesn't support structures and unions. Java supports documentation comment (/** . */) to create documentation for java source code, Java is also an object-oriented language. However, everything (except fundamental types) is an object in Java. It is a single root hierarchy as everything gets derived from [Link]. uses the import keyword to include Java Program Example File: Simple java Hinclude class Simple using namespace std; { int main() publicstatic void main(String args(]) { { cout << "Hello C++ Programming’; [Link]("Hello Java"); retum 0; } t } First Java Program | Hello World Example class Simple { public static void main(String args[] [Link]("Hello Java"); } i Save the above file as Simple java To compile: javac [Link] ple class keyword is used to declare a class in Java. To execute: java public keyword is an access modifier that represents visibility. It means it is visible to all. static is a keyword. If we declare any method as static, it is known as the static method. ‘The core advantage of the static method is that there is no need to create an object to invoke the static method. The m: ) method is executed by the JVM, so it doesn't require creating an object to invoke the main() method. So, it saves memory. Void is the return type of the method. It means it doesn't return any value. main represents the starting point of the program. String[] args or String args[] is used for command line argument [Link]() is used to print statement. Here, System is a class, out is an object of the PrintStream class, printin() is a method of the PrintStream class. To write java program,open notepad by start menu -> All Programs -> Accessories -> Notepad and write a simple program. JVM JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist, It is a specification that provides a runtime environment in which Java bytecode can be executed. It can also run those programs which are written in other languages and compiled to Java bytecode. JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent because the configuration of each OS is different from each other. However, Java is platform independent. There are three notions of the JVM: specification, implementation, and instance. The JVM performs the following main tasks: © Loads code Verifies code © Executes code 2 Provides runtime environment JVM (lava Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed. JVMIS 1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Oracle and other companies. 2. An implementation Its implementation is known as JRE (Java Runtime Environment). 3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created. JVM provides definitions for the 2 Memory area © Class file format co Register set © Garbage-collected heap ©. Fatal error reporting ete. JRE JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries and other files that JVM uses at runtime. JDK JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE and development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation: © Standard Edition Java Platform © Enterprise Edition Java Platform © Micro Edition Java Platform The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to complete the development of a Java Application. Java Variables A variable is a name given to the memory location which holds the value while the Java program is executed. Avariable is assigned with a data type. int data=50;//Here data is variable There are three types of variables in Java: © local variable © instance variable © static variable Local Variable Avariable declared inside the body of the method is called local variable. You can use this variable only wit exists. Alocal variable cannot be defined with "static" keyword. jin that method and the other methods in the class aren't even aware that the variable Instance Variable A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static. It is called an instance variable because its value is instance-specific and is not shared among instances. Static variable Avariable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory. Data Types Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java: 1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double. 2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays Primitive Data Types Primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java language. There are 8 types of primitive data types: © boolean data type byte data type © chardata type ©. short data type © int data type © long data type © float data type © double data typ Non-Primitive String Boolean Numeric 7 Array ee, —— ete Character | Integer Floating-point / oS * a boolean char byte short int long float double Data Type Default Value Default size boolean false bit char "\uoo00' 2byte byte 0 Lbyte short 0 2byte int 0 4 byte long ou Bbyte float oof byte double 0.04 Bbyte Boolean Data Type The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that track true/false conditions. ‘The Boolean data type specifies one bit of information, but its "size" can't be defined precisely. Example: Boolean one = false Byte Data Type The byte data type is an example of primitive data type. It is an 8-bit signed two's complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value Is -128 and maximum value is 127. Its default value is 0. The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type. Example: byte a= 10, byte b Short Data Type The short data type is a 16-bit signed two's complement integer. Its value-range lies between - 32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0. The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller than an integer. Example: short s = 10000, short r = -5000 Int Data Type The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-2931) to 2,147,483,647 (2431 -1) (inclusive). ts minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0. The int data type is generally used as a default data type for integral values unless if there is no problem about memory. Example: int a= 100000, b= -200000 Long Data Type The long data type is a 64-bit two's complement integer. Its value-range lies between - 9,223,372,036,854,775,808(-2°63) to 9,223,372,036,854,775,807(2%63 -1)(inclusive). Its minimum value is = ~—_‘9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a range of values more than those provided by int. Example: long a = 100000L,, long b = -200000L, Float Data Type The float data type is a single-precision 32-bit floating point. Its value range is unlimited. It is recommended to use a float (instead of double) if you need to save memory in large arrays of floating point numbers. The float data type should never be used for precise values, such as currency. Its default value is 0.0F. Example: float {1 = 234.5f Double Data Type The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type is generally used for decimal values just like float. The double data type also should never be used for precise values, such as currency. Its default value is 0.0d. Example: double di = 12.3 Char Data Type The char data type is 2 single 16-bit Unicode character. Its value-range lies between "\u0000' (or 0) to '\uffff' (or 65,535 inclusive). The char data typ Example le: char letterA = 'A’ used to store characters. Note: Java uses Unicode system not ASCII code system. The \u0000 is the lowest range of Unicode system. Operat tors in Java Operator is a symbol that is used to perform operations. There are many types of operators in Java which are given below: Operat Unary Operator, Arithmetic Operator, Shift Operator, Relational Operator, Bitwise Operator, Logical Operator, Ternary Operator and Assignment Operator. ‘or Precedence Opera Category tor Type Unary postfix prefix Arithmetic _ multiplicative shift additive shift Relational comparison equi expr++ expr Hexpr expr +expr= expr~ 1 "1% = <<>> >>> <> <= >= instanceof Bitwise & bitwise exclusive * oR bitwise inclusive | oR Logical logical AND BR logical OR Ul Ternary ternary 2 Assignment assignment Java Unary Operator The Java unary operators require only one operand. Unary operators are used to perform various operations i. © incrementing/decrementing a value by one 9 negating an expression © inverting the value of a boolean Example1: ++ and ~ Public class OperatorExample { public static void main(String argst]) { int x=10; System. [Link](x+);//10 (11) [Link](++x);//12 ‘[Link](x--);//12 (11) ‘[Link](—x);//10 } } Example2: ~ and ! public class OperatorExample { public static void main(String args) { int a=10; int b=-10; boolean c=true; boolean d=false; ‘[Link](~a);//-11 (minus of total positive value which starts from 0) ‘[Link](~b);//9 (positive of total minus, positive starts from 0) ‘[Link](!c);//false (opposite of boolean value) [Link](Id);//true }} Arithmetic Operators Arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic mathematical operations. Example: class OperatorExample { public static void main(String args(]) { int a int b- ‘[Link](a+b);//15, [Link](a-b);//S [Link](a*b);//50_ ‘[Link](a/b);//2 [Link](a%b);//0 t } Left Shift Operator Left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times. Example: class OperatorExample { public static void main(String args(]) { [Link](10<<2);//10*2" [Link](10<<3);//10*2": System. [Link](15<<4);//15*244=15*16=240 t } Right Shift Operator Right shift operator >> is used to move the value of the left operand to right by the number of bits specified by the right operand. Example: class OperatorExample { Public static void main(String argst]) { System. [Link](10>>2);//10/2% ‘[Link](20>>2);//20/2%2=20/4=5 System. [Link](20>>3);//20/2"3=20/8=2 } } Java AND Operator Example: Logical && and Bitwise & ‘The logical && operator doesn't check the second condition if the first condition is false. It checks the second condition only if the first one is true. The bitwise & operator always checks both conditions whether first condition is true or false. Example: class OperatorExample { public static void main(String argst]) [Link](acb&&a++b| |ab|acc);//true | true = true [Link](a>b | |a+#b|a++. void: Java void keyword is used to specify that a method does not have a return value. vol : Java volatile keyword is used to indicate that a variable may change asynchronously. le loop. This loop iterates a part of the program several times, If the number of iteration is not fixed, it is recommended to use the while loop. m4 Java Control Statements Java provides three types of control flow statements. 1. Decision Making statements ©. ifstatements © switch statement 2. Loop statements © dowhile loop © while loop © forloop © for-each loop 3. Jump statements © break statement © continue statement De n-Making statements: As the name suggests, decision-making statements decide which statement to execute and when. 1) If Statement: The "if" statement is used to evaluate a condition, The control of the program is diverted depending upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. In Java, there are four types of if-statements given below. 1. Simple if statement 2. if-else statement 3. ifelse-if ladder 4, Nested if-statement Simple if statement: It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates to true. 25 Syntax: if(condition) { statement 1; //executes when condition is true } if-else statement The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The else block is executed if the condition of the if-block is evaluated as false. Syntax: if(condition) { statement 1; //executes when condition is true } else { statement 2; //executes when condition is false ¥ 3) ifelse-if ladder: The if-else-if statement contains the if-statement followed by multiple else-if statements. It is the chain of if-else statements that create a decision tree where the program may enter in the block of code where the condition is true. We can also define an else statement at the end of the chain Syntax : if(condition 1) { statement 1; //executes when condition 1 is true I else if(condition 2) { statement 2; //executes when condition 2 is true 26 else { statement 2; //executes when all the conditions are false } Nested if-statement In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement. Syntax: if(condition 1) { statement 1; //executes when condition 1 is true if(condition 2) { statement 2; //executes when condition 2 is true ¥ Else { statement 2; //executes when condition 2 is false t t ‘Switch Statement: Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable which is being switched, The switch statement is easier to use instead of if-else-if statements, It also enhances the readability of the program. © The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java © Cases cannot be duplicate © Default statement is executed when any of the case doesn't match the value of expression. It is optional. © Break statement terminates the switch block when the condition is satisfied. It is optional, if not used, next case is executed. ‘© While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value. 28 ‘Syntax: switch (expression) { case value1: statement]; break; case valueN: statementN; break; default: default statement; ‘While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value. The switch permits only int, string, and Enum type variables to be used. Looping Statements Loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions depends upon a particular condition. In Java, we have three types of loops that execute sit larly. 1. for loop 2. while loop, 3. do-while loop for loop It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code. We use the for loop only when we exactly know the number of times, we want to execute the block of code. 29 Syntax: for(initialization, condition, increment/decrement) { //block of statements } while loop The while loop is also used to iterate over the number of statements multiple times. However, if ‘we don't know the number of iterations in advance, itis recommended to use a while loop. Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop statement in while loop. It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed. ‘Syntax: while(condition) { /Nooping statements } do-while loop The do-while loop checks the condition at the end of the loop after executing the loop statements. When the number of iteration is not known and we have to execute the loop at least ‘once, we can use do-while loop. It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-while loop is given below. Jump Statements Jump statements are used to transfer the control of the program to the specific statements. In other words, jump statements transfer the execution control to the other part of the program, There are two types of jump statements in Java, ie., break and continue. 30 Java break statement ‘As the name suggests, the break statement is used to break the current flow of the program and transfer the control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in the case of the nested loop. The break statement cannot be used independently in the Java program, i.e., it can only be written inside the loop or switch statement. Java continue statement Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part of the loop and jumps to the next iteration of the loop immediately. Differences between for, while and do-while Comparison Introduction When to use Syntax for loop The Java for loop is a control flow statement that iterates a part of the programs multiple times. If the number of iteration is fixed, it is recommended to use for loop. tscondition;incr/decr){ // code to be executed } while loop The Java while loop is a control flow statement that executes a part of the programs repeatedly on the basis of given boolean condition If the number of iteration is not fixed, it is recommended to use while loop. while(condition){ I{code to be executed } 31 do-while loop The Java do while loop is a control flow statement that executes a part of the programs at least once and the further execution depends upon the given boolean condition. If the number of iteration is not fixed and you must have to execute the loop at least onee, it is recommended to use the do-while loop. dot /fcode to be executed Jwhile(condition}; Example Iifor loop —//while loop //do-while loop int for(int int System. out. printin(); while(ic=10){ dof } [Link](i); [Link](i); ie } Jwhile(i<=10); syntax for for(;:{ while(true){ dot infinitiveloop //code to be executed //code to be executed //code to be executed } } Jwhile(true); 32, Naming Convention Java naming convention is a rule to follow as you decide what to name the identifiers such as class, package, variable, constant, method, etc. But, it is not forced to follow. So, it is known as convention not rule. Naming Conventions of the Different Identifiers The following table shows the popular conventions used for the different identifiers. identifi Naming Rules Examples ersType Class It should start with the public class Employee uppercaseletter: { It should be a noun such as /{code snippet Color, Button, System, } Thread, ete. Use appropriate words, instead ofacronyms. Interface It should start with the interface Printable uppercaseletter. { It should be an adjective /{code snippet such as Runnable, Remote, } [Link] appropriate words, instead of acronyms. Method It should start with lowercase _class Employee [Link] should bea verb such { as main(), print(), printin(). W if the name contains multiple meth words start it with a od lowercase letter followed by void an uppercase letter suchas draw( actionPerformed(). ) 33 Variable Package It should start with a lowercase lettersuch as id, name. It should not start with the specialcharacters like & {ampersand), $ (dollar), _ (underscore). IF the name contains multiple words, start it with the lowercase letter followed by an uppercase letter suchas firstName, lastName. ‘Avoid using one-character variablessuch as x, y, 2. Itshould be a lowercase letter suchas java, lang. Ifthe name contains multiple words, it should be separated by dots (.) such as [Link], [Link]. class Employee { W vari able int id; I/code snippet } Iipackage package comjavatpoint; class Employee { /code snippet } Constant It should be in uppercase class Employee letters suchas RED, YELLOW. { lfthename contains multiple —_//constant words,it should be separated _ static final int MIN_AGE = by an underscore(_) such as [/code snippet MAX_PRIORITY. t Itmay contain digits but not as thefirst letter. ‘Advantage of Naming Conventions in Java By using standard Java naming conventions, the code becomes easier to read for the programmers, Readability of Java program is very important, It indicates that less time is spent to figure out what the code doe ‘CamelCase in Java naming conventions Java follows camel-case syntax for naming the class, interface, method, and variable. If the name is combined with two words, the second word will start with uppercase letter always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc. 35 Objects and Classes ‘An object in Java is the physical as well asa logical entity, whereas, a class in Java is a logical entity only. Object ‘An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. itcan be physical or logical (tangible and intangible). The example of an intangible object is the banking system. An object has three characteristic © State: represents the data (value) of an object. © Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, ete, © Ident ‘An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely. Example: Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so writing is its behavior. An object is an instance of a class. A class is a template or blueprint from which objects are created, So, an object is the instance(result) of a class. Object Definitions: 9 An object is a real-world entity. © An object is a runtime entity. 2 The objer is an entity which has state and behavior. © The object is an instance of a class. Class [Link] is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical. Acclass in Java can contain: 36 © Fields Methods © Constructors © Blocks 0 Nested class and interface Declaration of class: class { field; method; + Instance variable in Java A variable which is created inside the class but outside the method is known as an instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when ‘an object or instance is created. That is why it is known as an instance variable. Method in Java In Java, a method is like a function which is used to expose the behavior of an object. Advantage of Method © Code Reusability © Code Optimization new keyword in Java ‘The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area. ‘Object Initialization There are 3 ways to initialize object in Java. 1. By reference variable 2. By method 3. By constructor 37 Creating multiple objects ‘We can create multiple objects by one type only as we do in case of primitives. Initialization of primitive variables: int Initialization of refernce variables: Rectangle r=new Rectangle(), (creating two objects of one class type) Method in Java In general, a method is a way to perform some task. Similarly, the method in Java is a collection of instructions that performs a specific task. It provides the reusability of code. We can also easily, modify code using methods. A method is a block of code or collection of statements or a set of code grouped together to perform a certain task or operation. It is used to achieve the reusability of code. Method can be written once and used many times. We do not require to write code again and again. It also provides the easy modification and readability of code, just by adding or removing a chunk of code. The method is executed only when we call or invoke it. The most important method in Java is the main() method. Method Declaration The method declaration provides information about method attributes, such as visibility, return- type, name, and arguments. it has six components that are known as method header, as, Shown below. Method Dectaration Return Type. limethod body Method Signature 7.6Msstions on Structures Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list. ‘Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the method, Java provides four types of access specifier: 38 © Publ The method is accessible by all classes when we use public specifier in our application. © Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined © Protected: When we use protected access specifier, the method is accessible within the same package or subclasses in a different package. © Default: When we do not use any access specifier in the method declaration, Java uses default access specifier by default. Itis visible only from the same package only. Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword, Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method name must be subtraction(). A method is invoked by its name. Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank. Method Body: It is a part of the method declaration. It contains all the actions to be performed. Itis enclosed within the pair of curly braces. Naming a Method While defining @ method, remember that the method name must be averb and start with a lowercase letter. If the method name has more than two words, the first name must be a verb followed by adjective or noun. In the multi-word method name, the first letter of each word must be in uppercase except the first word. For example: Single-word method name: sum(), area() Multi-word method name: areaOfCircle(), stringComparision() It is also possible that a method has the same name as another method name in the same class, it is known as method overloading. Static Method ‘A method that has static keyword is known as static method. In other words, a method that belongs to a class rather than an instance of a class is known as a static method. We can also create a static method by using the keyword static before the method name. 39 The main advantage of a static method is that we can call it without creating an object. It can access static data members and also change the value of it. It is used to create an instance method. Its invoked by using the class name. The best example of a static method is the main() method. Abstract Method The method that does not have method body is known as abstract method. In other words, without an implementation is known as abstract method. It always declares in the abstract class. It means the class itself must be abstract if it has abstract method. To create an abstract method, we use the keyword abstract. syntax abstract void method_name(); Constructors Constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. It isa special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called. It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default. Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any. Rules for creating Java constructor There are two rules defined for the constructor. 1. Constructor name must be the same as its class name 2. AConstructor must have no explicit return type not even void. 3. A Java constructor cannot be abstract, static, final, and synchronized Types of Java constructors ‘There are two types of constructors in Java: 1. Default constructor (no-arg constructor) 2. Parameterized constructor Default Constructor Aconstructor is called "Default Constructor" when it doesn't have any parameter. The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type. Syntax of default constructor: () t Note: If there is no constructor in a class, compiler automatically creates a default constructor. Parameterized Constructor Aconstructor which has a specific number of parameters is called a parameterized constructor. The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also. Constructor Overloading in Java In Java, a constructor is just ike a method but without return type. It can also be overloaded like Java methods. Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types. 4 Difference between constructor and method in Java A constructor is used to initialize the state of A method is used to expose the behavior of an object. an object. constructor must not have areturn type. A method must have a return type. The constructor is invoked implicitly. ‘The method is invoked explicitly. The Java compiler provides a default The method is not provided by the compiler in any case. constructor if you don't have any constructor ina class. The constructor name must be same as the The method name may or may not be same as the class name class name. 42 Java static keyword The static keyword in Java is used for memory management mainly. Static keyword can be applied with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class. The static can be: 1. Variable (also known as a class variable) 2. Method (also known as a class method) 3. Block 4. Nested class Java static variable Ifany variable declared as static, it is known asa static variable. ©The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, ete. © The static variable gets memory only once in the class area at the time of class loading. Advantages of static variable It makes the program memory efficient (i, it saves memory). Java static method If static keyword is applied with any method, itis known as static method. ©. Astatic method belongs to the class rather than the object of a class. ‘9 Astatic method can be invoked without the need for creating an instance of a class. © Astatic method can access static data member and can change the value of it. 43 Restrictions for the static method ‘There are two main restrictions for the static method. They are: 1, The static method can not use non static data member or call non-static method directly. 2. this and super cannot be used in static context. Note: Java main method is static because the object is not required to call a static method, if it were ‘a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation. Java static block © 1S used to initialize the static data member. 9 Itis executed before the main method at the time of classloading. this keyword in Java ‘There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the current object. behaviour object Usage of this keyword 1. this can be used to refer current class instance variable 2. this can be used to invoke current class method (implicitly) 3. this() can be used to invoke current class constructor. 1) this: to refer current class instance variable The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity. Note: If local variables(formal arguments) and instance variables are different, there is no need to use this keyword. Inheritance in Java Inheritance is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). 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 a parent-child relationship. Advantages Method Overriding (so runtime polymorphism can be achieved) 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. Itis 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. It is also called a base class or a parent class. © Reusability: As the name specifies, reusabi 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. 15M 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. 45 ClassA ClassA Class fF ft “\N\ ClassB ClassB Classe Classc ¥ 1) Single 3) Hierarchical Class 2) Multilevel ClassA ClassB ClassA ClassB Class Classc X 2 4) Multiple Cees 5) Hybrid Single Inheritance When a class inherits another class, it is known as a single inheritance. Multilevel inheritance ‘When there isa chain of inheritance, it is known as multilevel inheritance. Hierarchical Inheritance ‘When two or more classes inherits a single class, it is known as hierarchical inheritance. 46 Note: To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Ex: Consider a scenario where A, B, and Care three classes. The C class inherits A and B classes. if A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error. Method Overloading in Java Ifa class has multiple methods having same name but different in parameters, it is known as Method Overloading. If only one operation is performed having same name of the methods increases the readability of the program. Advantage of method overloading Method overloading increases the readability of the program. Different ways to overload the method There are two ways to overload the method in java 1. By changing number of arguments 2. By changing the data type In Java, Method Overloading is not possible by changing the return type of the method only. java main() method Java main() method can also be overloaded. Any number of main methods can be created in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Example: class MainOverloading { public static void main(String{] args) { a7 [Link]("main with Stringf]"); } public static void main(String args) {[Link]-printin("main with String"); } public static void main() {[Link]-printin("main without args"); } } Output: main with Stringt]. Method Overriding in Java If subclass (child class) has the same method as declared in the parent class, it is known ‘as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding, Usage of Java Method Overriding © Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. © Method overriding is used for runtime polymorphism Rules for Java Method Overriding 1. The method must have the same name as in the parent class 2. ‘The method must have the same parameter as in the parent class. 3. There must be an IS-A rel: tionship (inheritance), Note: Static method and main method cannot be overridden. Super Keyword in Java The super keyword in Java is a reference variable which is used to refer immediate parent class object. Whenever the instance of subclass is created, an instance of parent class is created implicitly which is referred by super reference variable. Usage of Java super Keyword 48 1. super can be used to refer immediate parent class instance variable. 2. super can be used to invoke immediate parent class method. 3. super() can be used to invoke immediate parent class constructor. 1) super is used to refer immediate parent class instance variable, ‘Super keyword can be used to access the data member or field of parent class. It is used if parent class and child class have same fields. 2) super can be used to invoke parent class method ‘The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden. 3) super is used to invoke parent class constructor. The super keyword can also be used to invoke the parent class constructor. Access Modifiers in Java There are two types of modifiers in Java: access modifiers and non-access modifiers. The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it. There are four types of Java access modifiers: 1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class. 2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. 3. Protected: The access level of a protected modifier is within the package and outside the package through child class. if you do not make the child class, it cannot be accessed from outside the package. 49 4, Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we are going to learn the access modifiers only.54.2MC+ vs Java Access within within outside package by outside Modifier class package subclass only package Private Y N N N Default Y Y N N Protected Y Y Y N Public nt Y Y Y 1) Private ‘The private access modifier is accessible only within the class. 2) Default If any modifier is not used, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and publi 3) Protected The protected access modifier is accessible within package and outside the package but throughinheritance only. The protected access modifier can be applied on the data member, method and constructor. Itcan't be applied on the class. It provides more accessibility than the default modifer. 4) Public The public access modifier is accessible everywhere. It has the widest scope among all other modifiers. 51 Unit-2 Inheritance and Polymorphism Inheritance and Polymorphism: Inheritance in java, Super and sub class, Overriding, Object class, Polymorphism, Dynamic binding, Generic programming, Casting objects, Instance of operator Abstract class, Interface in java, Package in java, UTIL package. Multithreading in java: Thread life cycle and methods, Runnable interface, Thread synchronization, Exception handling with try catch-finally, Collections in java, Introduction to JavaBeans and Network Programming. INHERITANCE AND POLYMORPHISM. OBJECT CLASS IN JAVA Object class is present in [Link] package. The Object class is the parent class of all the classes in java bydefault. In other words, itis the top most class of java. The Object class is beneficial if you want to refer anyobject whose type you don't know. Notice that parent class reference variable can refer thechild class object, known as upcasting, All the methods of Object class can be used by all the subclasses and arrays. The Object class providesdifferent methods to perform different operations on objects. Every class in Java is directly or indirectly derived from the Object class. Ifa class does not extend anyother class then its a direct child class of Object and if extends another class then it is indirectly derived. Therefore the Object class methods are available to all Java classes. Hence Object class acts as a root of inheritance hierarchy in any Java Program. Let's take an example, there is getObject() method that returns an object but it can be ofany type like Employee, Student etc, we can use Object class reference to refer that object. For example: Object obj=getObject); The Object class provides some common behaviors to all the objects such as object can be compared, objectcan be cloned, object can be notified etc. Methods of Object class The Object class provides many methods. They are as follows: * toStringl) Method ‘© hashCode() Method © equals(Object obj) Method © getClass() method + finalize() method © clone() method ‘© wait(), notify() notifyAll() Methods 2 toString() Method: it's provide string representation or convert object to string form. you can override toString) methodto get your own String representation of objects. public String toString() { // Can override and give own definition } hashCode() Method: It’s generate unique hashcode for each object. The main advantage of saving objects. It's used tooverride for user defined objects for better performance like searching equals(Object obj) Method: It's used to compare the two objects dynamically. getClass() Method: It's return runtime class object and used to get metadata information as well. finalize() method: This method call required to perform garbage collector. clone() method: It used to create the copy or clone of object. wait(), notify() notifyAll() Methods: These are used in multithreading, 53

You might also like