Summary

This document contains lecture notes on module 1 of a Java programming course. It covers fundamental concepts like object-oriented programming (OOP), features of Java, and types of Java Applications. The notes are from SNDP Yogam College.

Full Transcript

Sahodaran Ayyappan Smaraka SNDP Yogam College, Konni, Pathanamthitta Reaccredited by NAAC with A Grade (Aided College Affiliated to Mahatma Gandhi University, Kottayam) Department of Computer Science...

Sahodaran Ayyappan Smaraka SNDP Yogam College, Konni, Pathanamthitta Reaccredited by NAAC with A Grade (Aided College Affiliated to Mahatma Gandhi University, Kottayam) Department of Computer Science LECTURE NOTE Programme Name : Master of Computer Science Course Name : Advanced Java Programming Course Code : CA500102 Semester : First MODULE – 1 Syllabus Object Oriented Programming Concepts and Basics of Java. Java Programming Environment – JDK, Java Virtual Machine, Bytecode, Features of Java Flow Control Statements – Conditional Statements, Iteration Statements, Jump Statements Arrays –One Dimensional Array, Multi-dimensional Array , Object Oriented Programming Concepts- ( Objects and Classes, Encapsulation, Inheritance, Polymorphism) , Type of Inheritance , Method Overloading, Method Overriding, Dynamic Method Despatch. Book of Study 1. Herbert Schildt,Java 2 The Complete Reference, Tata McGraw Hill (5thEdn.) 2. James. P. Cohoon,Programming java5.0, , Jack. W. Davison (Tata McGraw Hill) 3. C Thomas Wu, An introduction to Object Oriented Programming with Java, , Tata McGraw Hill, (2006) 4. Wigglesworth and McMillan ,Java Programming: Advanced Topics, , Cengage Learning India, 3rdEdn. 5. Bernard Van Haecke, JDBC:Java Database Connectivity, , IDG Books India (2000) 1 INTRODUCTION TO JAVA Java is a high-level, robust, object-oriented, and secure programming language. Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling is known as the father of 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. Java makes writing, compiling, and debugging programming easy. It helps to create reusable code and modular programs. Java is a general-purpose programming language made for developers to write once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is similar to C/C++. Types of Java Applications There are four types of Java applications that can be created using Java programming: Standalone Applications: Java standalone applications uses GUI components such as AWT, Swing, and JavaFX. These components contain buttons, list, menu, scroll panel, etc. It is also known as desktop alienations. Enterprise Applications: An application which is distributed in nature is called enterprise applications. Web Applications: An applications that run on the server is called web applications. We use JSP, Servlet, Spring, and Hibernate technologies for creating web applications. Mobile Applications: Java ME is a cross-platform to develop mobile applications which run across smartphones. Java is a platform for App Development in Android. Features of Java 1. Platform Independent: Compiler converts source code to bytecode and then the JVM executes the bytecode generated by the compiler. This bytecode can run on any platform be it Windows, Linux, macOS which means if we compile a program on Windows, then we can run it on Linux and vice versa. Each operating system has a different JVM, but the output produced by all the OS is the same after the execution of bytecode. That is why we call java a platform-independent language. 2. Object-Oriented Programming Language: Organizing the program in the terms of collection of objects is a way of object-oriented programming, each of which represents an instance of the class. The four main concepts of Object-Oriented programming are: Abstraction Encapsulation Inheritance Polymorphism 3. Simple: Java is one of the simple languages as it does not have complex features like pointers, operator overloading, multiple inheritances, Explicit memory allocation. 4. Robust: Java language is robust which means reliable. It is developed in such a way that it puts a lot of effort into checking errors as early as possible, that is why the java compiler is able to detect even those errors that are not easy to detect by another programming language. The main features of java that make it robust are garbage collection, Exception Handling, and memory allocation. 5. Secure: 2 In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like stack corruption or buffer overflow are impossible to exploit in Java. 6. Distributed: We can create distributed applications using the java programming language. Remote Method Invocation and Enterprise Java Beans are used for creating distributed applications in java. The java programs can be easily distributed on one or more systems that are connected to each other through an internet connection. 7. Multithreading: Java supports multithreading. It is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. 8. Portable: As we know, java code written on one machine can be run on another machine. The platform-independent feature of java in which its platform-independent bytecode can be taken to any platform for execution makes java portable 9. High Performance: Java architecture is defined in such a way that it reduces overhead during the runtime and at some time java uses Just In Time (JIT) compiler where the compiler compiles code on-demand basics where it only compiles those methods that are called making applications to execute faster. 10. Dynamic flexibility: Java being completely object-oriented gives us the flexibility to add classes, new methods to existing classes and even create new classes through sub-classes. Java even supports functions written in other languages such as C, C++ which are referred to as native methods. 11. Sandbox Execution: Java programs run in a separate space that allows user to execute their applications without affecting the underlying system with help of a bytecode verifier. Bytecode verifier also provides additional security as its role is to check the code for any violation of access. 12. Write Once Run Anywhere: As discussed above java application generates a ‘.class’ file which corresponds to our applications(program) but contains code in binary format. It provides ease t architecture-neutral ease as bytecode is not dependent on any machine architecture. It is the primary reason java is used in the enterprising IT industry globally worldwide. 13. Power of compilation and interpretation: Most languages are designed with purpose either they are compiled language or they are interpreted language. But java integrates arising enormous power as Java compiler compiles the source code to bytecode and JVM executes this bytecode to machine OS-dependent executable code. Java Programming Environment Java is a recently developed, concurrent, class-based, object-oriented programming and runtime environment, consisting of: Java Language — used by programmers to write the application The Java Virtual Machine (JVM) — used to execute the application The Java Ecosystem — provides additional value to the developers using the programming language Java Language It is a human-readable language which is generally considered easy to read and write (albeit a bit verbose at times). 3 It is class-based and object-oriented in nature. Java is intended to be easy to learn and to teach. There are many different implementations of Java available, both proprietary and open source. The Java Language Specification (JLS) defines how a confirming Java application must behave. (Also write Features of Java here also) The Java Virtual Machine (JVM) The Java Virtual Machine is a program which provides the runtime environment to execute Java programs. Java programs cannot run if a supporting JVM is not available. On running a Java program from the command line like — java the OS would bring up the JVM as a process and then execute the program in the freshly started (and empty) Virtual Machine. JVM does not take Java source files as input. The java source code is first converted to bytecode by javac program. Javac takes in source files as input and outputs bytecode in the form of class files with.class extension. These class files are then interpreted (stepped through one at a time) by the JVM interpreter and the program is executed. JVM makes the programmer’s life easier by- providing a container for the Java program to run in creating a secure execution environment as compared to C/C++ taking memory management out of the hands of the developer allowing class files from one platform to run on a different environment without any modification or recompilation This property is known as “write once, run anywhere” (WORA) and thus make Java an easily portable language. Another important aspect of JVM is the Just-in-Time (JIT) compiler. Researches done is the 1970’s and 1980’s revealed that the runtime behaviour of programs has some interesting patterns. There are some portions of code which are executed far more often than other. The Java Ecosystem Java has emerged to be a robust, portable and high performing language and has been widely adopted globally. One of the major reasons for the success of Java is the immense number of third party libraries and components written in Java. Today it is rare to a find a component which does not have a supporting Java connector. From traditional MySQL to NoSQL, monitoring frameworks, network components all have a Java connector readily available. JDK (Java Development Kit) The Java Development Kit (JDK) is a cross-platformed software development environment that offers a collection of tools and libraries necessary for developing Java-based 4 software applications and applets. It is a core package used in Java, along with the JVM (Java Virtual Machine) and the JRE (Java Runtime Environment). Beginners often get confused with JRE and JDK, if you are only interested in running Java programs on your machine then you can easily do it using Java Runtime Environment. However, if you would like to develop a Java-based software application then along with JRE you may need some additional necessary tools, which is called JDK. JDK=JRE + Development Tools The Java Development Kit is an implementation of one of the Java Platform: Standard Edition (Java SE), Java Enterprise Edition (Java EE), Micro Edition (Java ME), Contents of JDK The JDK has a private Java Virtual Machine (JVM) and a few other resources necessary for the development of a Java Application. JDK contains: Java Runtime Environment (JRE), An interpreter/loader (Java), A compiler (javac), An archiver (jar) and many more. The Java Runtime Environment in JDK is usually called Private Runtime because it is separated from the regular JRE and has extra contents. The Private Runtime in JDK contains a JVM and all the class libraries present in the production environment, as well as additional libraries useful to developers, e.g, internationalization libraries and the IDL libraries. Some Important Components of JDK Below there is a comprehensive list of mostly used components of Jdk which are very much useful during the development of a java application. Component Use javac Java compiler converts source code into Java bytecode java The loader of the java apps. javap Class file disassembler, javadoc Documentation generator, jar Java Archiver helps manage JAR files. appletviewer Debugging of Java applets without a web browser, jdb Debugger 5 JVM (Java Virtual Machine) Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the Java Code or applications. It converts Java bytecode into machines language. JVM is a part of Java Runtime Environment (JRE). In other programming languages, the compiler produces machine code for a particular system. However, Java compiler produces code for a Virtual Machine known as Java Virtual Machine. The JVM performs the following operation: Loads code Verifies code Executes code Provides runtime environment JVM provides definitions for the: Memory area Class file format Register set Garbage-collected heap Fatal error reporting etc. JVM Architecture It contains classloader, memory area, execution engine etc. 1) Classloader Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes etc. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory. 6 System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the classfiles from classpath. By default, classpath is set to current directory. You can change the classpath using "-cp" or "-classpath" switch. It is also known as Application classloader. 2) Class(Method) Area Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods. 3) Heap It is the runtime data area in which objects are allocated. 4) Stack Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes. 5) Program Counter Register PC (program counter) register contains the address of the Java virtual machine instruction currently being executed. 6) Native Method Stack It contains all the native methods used in the application. 7) Execution Engine It contains: 1. A virtual processor 2. Interpreter: Read bytecode stream then execute the instructions. 3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here, the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU. 8) Java Native Interface Java Native Interface (JNI) is a framework which provides an interface to communicate with another application written in another language like C, C++, Assembly etc. Java uses JNI framework to send output to the Console or interact with OS libraries. Bytecode Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an assembler which is an alias representation of a C++ code. As soon as a java program is compiled, java bytecode is generated. In more apt terms, java bytecode is the machine code in the form of a.class file. With the help of java bytecode we achieve platform independence in java. Working of Bytecode When we write a program in Java, firstly, the compiler compiles that program and a bytecode is generated for that piece of code. When we wish to run this.class file on any other platform, we can do so. After the first compilation, the bytecode generated is now run by the Java Virtual Machine and not the processor in consideration. This essentially means that we only need to have basic java installation on any platforms that we want to run our code on. Resources required to run the bytecode are made available by theJava Virtual Machine, which calls the processor to allocate the required resources. JVM's are stack-based so they stack implementation to read the codes. 7 Advantage of Java Bytecode Platform independence is one of the soul reasons for which James Gosling started the formation of java and it is this implementation of bytecode which helps us to achieve this. Hence bytecode is a very important component of any java program.The set of instructions for the JVM may differ from system to system but all can interpret the bytecode. A point to keep in mind is that bytecodes are non-runnable codes and rely on the availability of an interpreter to execute and thus the JVM comes into play. Bytecode is essentially the machine level language which runs on the Java Virtual Machine. Whenever a class is loaded, it gets a stream of bytecode per method of the class. Whenever that method is called during the execution of a program, the bytecode for that method gets invoked.Javac not only compiles the program but also generates the bytecode for the program. Thus, we have realized that the bytecode implementation makes Java a platform- independent language. This helps to add portability to Java which is lacking in languages like C or C++. Portability ensures that Java can be implemented on a wide array of platforms like desktops, mobile devices, severs and many more. Supporting this, Sun Microsystems captioned JAVA as "write once, read anywhere" or "WORA" in resonance to the bytecode interpretation. FLOW CONTROL STATEMENTS Java compiler executes the code from top to bottom. The statements in the code are executed according to the order in which they appear. However, Java provides statements that can be used to control the flow of Java code. Such statements are called control flow statements. It is one of the fundamental features of Java, which provides a smooth flow of program. Java provides three types of control flow statements. Decision Making statements (Conditional Statements) if statements switch statement Loop statements (Iteration Statements) do while loop while loop for loop for-each loop Jump statements break statement continue statement Decision Making statements (Conditional Statements) As the name suggests, decision-making statements decide which statement to execute and when. Decision-making statements evaluate the Boolean expression and control the program flow depending upon the result of the condition provided. There are two types of decision-making statements in Java, i.e., If statement and switch statement. I. If Statement: 8 In Java, 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. if-else-if ladder 4. Nested if-statement 1) 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. Syntax of if statement is given below. if(condition) { statement 1; //executes when condition is true } Consider the following example in which we have used the if statement in the java code. class If_Exa { public static void main(String args[]) { int i = 10; if (i < 15) { System.out.println("10 is less than 15"); } System.out.println("Outside if-block"); } } Output: 10 is less than 15 Outside if-block 2) if-else statement The if-else statement s 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; } else{ statement 2; } Consider the following example. class IfElse_Exa { public static void main(String args[]) { int i = 20; if (i < 15) System.out.println("i is smaller than 15"); else System.out.println("i is greater than 15"); System.out.println("Outside if-else block"); 9 } } Output i is greater than 15 Outside if-else block 3) if-else-if ladder: The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say that 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 of if-else-if statement is given below. if(condition 1) { statement 1; } else if(condition 2) { statement 2; } else { statement 2; } Consider the following example. class IfElseLadder_Exa { public static void main(String[] args) { int i = 20; if (i == 10) System.out.println("i is 10\n"); else if (i == 15) System.out.println("i is 15\n"); else if (i == 20) System.out.println("i is 20\n"); else System.out.println("i is not present\n"); System.out.println("Outside if-else-if"); } } Output: i is 20 Outside if-else-if 4. 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 of Nested if-statement is given below. if(condition 1) { statement 1; if(condition 2) { statement 2; } else{ statement 2; } 10 } Consider the following example. public class NestedIf_Exa { public static void main(String args[]) { int x = 30; int y = 10; if( x == 30 ) { if( y == 10 ) { System.out.print("X = 30 and Y = 10"); } } } } Output X = 30 and Y = 10 II. Switch Statement: In Java, 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 syntax to use the switch statement is given below. switch (expression){ case value-1: statement1; break; …………………………………… …………………………………… case value-N: statementN; break; default: default statement; } Consider the following example to understand the flow of the switch statement. public class Student implements Cloneable { public static void main(String[] args) { int num = 2; switch (num){ case 0: System.out.println("number is 0"); break; case 1: System.out.println("number is 1"); break; default: System.out.println(num); } } } Output: 2 11 Iteration Statements (Loop Statements) In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to true. However, 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 similarly. However, there are differences in their syntax and condition checking time. for loop while loop do-while loop for loop In Java, for loop is similar to C and C++. 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. for(initialization, condition, increment/decrement) { //block of statements } The flow chart for the for-loop is given below. Example: Consider the following example to understand the proper functioning of the for loop in java. class forLoopExa { public static void main(String args[]) { for (int i = 1; i

Use Quizgecko on...
Browser
Browser