Java Programming Notes PDF
Document Details
![AmpleBambooFlute](https://quizgecko.com/images/avatars/avatar-2.webp)
Uploaded by AmpleBambooFlute
Kirti M. Doongursee College
Tags
Summary
These notes provide an overview of Java programming. They cover the language's history, including its development at Sun Microsystems and its initial aims. The notes also summarize key features, like platform independence and object-oriented principles.
Full Transcript
(Java Logo) (Old Java Logo) The original Java logo features a steaming coffee cup. The steaming cup symbolized the idea of energy and the widespread use of Java, much like coffee is consumed worldwide. The coffee cup logo was designed t...
(Java Logo) (Old Java Logo) The original Java logo features a steaming coffee cup. The steaming cup symbolized the idea of energy and the widespread use of Java, much like coffee is consumed worldwide. The coffee cup logo was designed to represent both the name "Java" (from Java coffee) and the dynamic, powerful, and globally relevant nature of the language. Over the years, the logo has evolved slightly, but the essence of the coffee cup and steam has remained as a symbolic representation of Java's core qualities. Founder of Java Programming Language Java was developed by James Gosling and his team at Sun Microsystems (now owned by Oracle Corporation). The development of Java began in 1991, and it was initially part of a project called "The Green Project" with the aim of creating software for embedded systems, such as cable TV set-top boxes. Gosling, who is often called the "father of Java," played a central role in its design and creation. The original version of Java was called Oak, but it was later renamed to Java. Why Was Java Named "Java"? The language was initially named Oak, after an oak tree that stood outside Gosling's office, but the name was already trademarked. The team needed to find a new name, and after considering several alternatives, they chose "Java." The name Java was inspired by Java coffee, which is a type of coffee that comes from the island of Java, Indonesia. The name was chosen because it was short, fun, and had an association with energy, which fit the goals of the programming language. Additionally, Java was meant to be dynamic, portable, and powerful, much like the Java coffee beans that are consumed worldwide. It also reflects the language's global appeal. Java was officially released on May 23, 1995, by Sun Microsystems. This was the date when Java 1.0 was introduced to the public, marking the beginning of its widespread adoption. Key Milestones: 1991: Development of Java began under the project code-named "The Green Project" at Sun Microsystems, led by James Gosling and his team. 1995: Java 1.0 was released to the public, accompanied by the slogan "Write Once, Run Anywhere," emphasizing Java's platform independence—allowing applications to run on any system that supports the Java Virtual Machine (JVM), regardless of the underlying hardware or operating system. 1996: The first public release of the Java Development Kit (JDK) and Java 1.1 were launched, adding significant features and improvements. Java frameworks are pre-built sets of libraries, tools, and APIs that provide a structured way to develop applications. They simplify the development process by handling common tasks like security, database integration, and UI rendering, allowing developers to focus on the unique aspects of their applications. What is Java ? Java is a high-level, general-purpose programming language that is widely used for building software applications. It was developed by James Gosling and Mike Sheridan at Sun Microsystems in 1991 and was officially released in 1995. Java is known for its "Write Once, Run Anywhere" (WORA) philosophy, which means that code written in Java can run on any device or operating system that has a Java Virtual Machine (JVM). Here are some key characteristics of Java: 1. Object-Oriented: Java follows the object-oriented programming (OOP) paradigm, meaning it organizes software design around data (objects) and methods (functions) that operate on the data. This encourages code reusability and modularity. 2. Platform Independence: Java programs are compiled into bytecode, which can be executed on any system that has a JVM. The JVM translates bytecode into machine code for the specific platform, allowing Java applications to run on a wide range of devices (from servers to mobile phones). 3. Syntax: Java has a syntax that is similar to other C-based languages (like C++ and C#), making it relatively easy to learn for developers familiar with those languages. 4. Memory Management: Java handles memory management automatically through garbage collection, which helps manage memory by removing objects that are no longer in use. 5. Multithreading: Java supports multithreading, which allows multiple tasks to run concurrently within a single program. This makes it suitable for applications that need to perform many operations simultaneously. 6. Security: Java includes a set of built-in security features, including a security manager and bytecode verification, which help protect users and systems from malicious code. 7. Libraries and Frameworks: Java comes with a rich set of libraries and frameworks, such as the Java Standard Library, Spring, Hibernate, and JavaFX, which provide developers with tools to build everything from web applications to desktop and mobile applications. 8. Applications: Java is used in a wide range of applications, including: o Web applications (via technologies like Servlets and JSP) o Mobile apps (especially Android) o Enterprise systems (using frameworks like Spring and Java EE) o Embedded systems o Desktop applications Java Platforms / Editions There are 4 platforms or editions of Java: 1) Java SE (Java Standard Edition) It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc. 2) 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, JSP, Web Services, EJB, JPA, etc. 3) Java ME (Java Micro Edition) It is a micro platform that is dedicated to mobile applications. 4) JavaFX It is used to develop rich internet applications. It uses a lightweight user interface API. Types of Java Applications There are mainly 4 types of applications that can be created using Java programming: 1) 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. 2) 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. 3) 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. 4) Mobile Application An application which is created for mobile devices is called a mobile application. Currently, Android and Java ME are used for creating mobile applications. Hello Java Program: class Simple{ public static void main(String args[]){ System.out.println("Hello Java"); } } 1. class Simple {: class: This keyword is used to define a class in Java. A class is a blueprint for creating objects (instances). In this case, the class is named Simple. Simple: This is the name of the class. It's a convention in Java to start class names with an uppercase letter, though this is not mandatory. 2. public static void main(String args[]) {: public: This is an access modifier. It means that the main method is accessible from anywhere (outside the class). This is necessary because the Java runtime needs to call the main method to start the program. static: This means that the main method belongs to the class itself, not to instances of the class. This is important because Java calls the main method before creating any objects (instances of the class). Therefore, static allows the method to be invoked without creating an object of Simple. void: This is the return type of the main method. void means the method doesn’t return any value. main: This is the name of the method. In Java, the main method is the entry point for any standalone Java application. When you run a Java program, the Java Virtual Machine (JVM) looks for this main method to begin execution. String args[]: This is a parameter for the main method. It’s an array of strings that allows you to pass command-line arguments to the Java program when running it. The args[] array can hold values that the user may provide when running the program from the command line, though in this code, the array isn't used. 3. System.out.println("Hello Java");: System: This is a built-in class in Java that provides access to system resources. It has several predefined fields, including out, which represents the standard output stream (typically the console). out: This is a static field in the System class that refers to the standard output stream. It’s used to print data to the console. println: This is a method of the out object that prints the text to the console. The println method also moves the cursor to the next line after printing the message, so any subsequent output will be on a new line. "Hello Java": This is a string literal, the message that will be printed to the console. 4. Closing the class (}): This closing curly brace marks the end of the Simple class. How the code works: 1. When you run the program, the JVM looks for the main method to start execution. 2. Inside the main method, the statement System.out.println("Hello Java"); is executed, which prints the string "Hello Java" to the console. 3. The program finishes executing after printing the message because there is no further code in the main method. Compilation Flow: When we compile Java program using javac tool, the Java compiler converts the source code into byte code. Note: Class name in java program and file name must be same. Features of Java Simple Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language is a simple programming language because: o Java syntax is based on C++ (so easier for programmers to learn it after C++). o Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc. o There is no 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 we organize our software as a combination of different types of objects that incorporate both data and behaviour. 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 Platform Independent Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform specific machines while Java is a write once, run anywhere language. A platform is 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 a 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, etc. 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 o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) 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. o Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects. o Security Manager: It determines what resources a class can access such as reading and writing to the local disk. Robust Java is robust because: o It uses strong memory management. o There is a lack of pointers that avoids security problems. o Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore. o 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. Portable Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation. 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 dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++. Java supports dynamic compilation and automatic memory management (garbage collection). What happens at compile time? At compile time, the Java file is compiled by Java Compiler (It does not interact with OS) and converts the Java code into bytecode. What happens at runtime? At runtime, the following steps are performed: Classloader: It is the subsystem of JVM that is used to load class files. Bytecode Verifier: Checks the code fragments for illegal code that can violate access rights to objects. Interpreter: Read bytecode stream then execute the instructions. Can you save a Java source file by another name than the class name? Yes, if the class is not public. It is explained in the figure given below: To compile: javac Hard.java To execute: java Simple Observe that, we have compiled the code with file name but running the program with class name. Therefore, we can save a Java program other than class name. Can you have multiple classes in a java source file? Yes, like the figure given below illustrates: Difference between JDK, JRE, and JVM 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: o Loads code o Verifies code o Executes code o Provides runtime environment JRE o 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 + other files that JVM uses at runtime. o The implementation of JVM is also actively released by other companies besides Sun Micro Systems. 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. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation: o Standard Edition Java Platform o Enterprise Edition Java Platform o 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 container which holds the value while the Java program is executed. A variable is assigned with a data type. Variable is a name of memory location. There are three types of variables in java: local, instance and static. There are two types of data types in Java: primitive and non-primitive. Variable A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location. It is a combination of "vary + able" which means its value can be changed. Example: int data=50; Types of Variables There are three types of variables in Java: o local variable o instance variable o static variable 1) Local Variable A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists. A local variable cannot be defined with "static" keyword. 2) 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. 3) Static variable A variable 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. Example: public class A { static int m=100; //static variable void method() { int n=90; //local variable } public static void main(String args[]) { int data=50; //instance variable } } //end of class Example Add two numbers: public class Add{ public static void main(String[] args){ int a=10; int b=10; int c=a+b; System.out.println(c); } } Data Types in Java 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. Let's understand in detail about the two major data types of Java in the following paragraphs. Java Primitive Data Types In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java language. Java Primitive data types: 1. boolean data type 2. byte data type 3. char data type 4. short data type 5. int data type 6. long data type 7. float data type 8. double data type Data Type Default Value Default size boolean false 1 bit char '\u0000' 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0L 8 byte float 0.0f 4 byte double 0.0d 8 byte 1. Boolean a = false; 2. Boolean b = true; 3. byte a = 10, byte b = -20 4. short s = 10000, short r = -5000 5. int a = 100000, int b = -200000 6. long a = 100000L, long b = -200000L 7. float f1 = 234.5f 8. double d1 = 12.3 9. char letterA = 'A' Non-Primitive Data Types in Java Class One common non-primitive data type in Java is the class. Classes are used to create objects, which are instances of the class. A class defines the properties and behaviors of objects, including variables (fields) and methods. For example, you might create a Person class to represent a person, with variables for the person's name, age, and address, and methods to set and get these values. Interface Interfaces are another important non-primitive data type in Java. An interface defines a contract for what a class implementing the interface must provide, without specifying how it should be implemented. Interfaces are used to achieve abstraction and multiple inheritance in Java, allowing classes to be more flexible and reusable. Arrays Arrays are a fundamental non-primitive data type in Java that allow you to store multiple values of the same type in a single variable. Arrays have a fixed size, which is specified when the array is created, and can be accessed using an index. Arrays are commonly used to store lists of values or to represent matrices and other multi-dimensional data structures. Enum Java also includes other non-primitive data types, such as enums and collections. Enums are used to define a set of named constants, providing a way to represent a fixed set of values. Collections are a framework of classes and interfaces that provide dynamic data structures such as lists, sets, and maps, which can grow or shrink in size as needed. Overall, non-primitive data types in Java are essential for creating complex and flexible programs. They allow you to create and manipulate objects, define relationships between objects, and represent complex data structures. By understanding how to use non-primitive data types effectively, you can write more efficient and maintainable Java code. Operators in Java Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc. There are many types of operators in Java which are given below: o Unary Operator, o Arithmetic Operator, o Shift Operator, o Relational Operator, o Bitwise Operator, o Logical Operator, o Ternary Operator and o Assignment Operator. Java Operator Precedence Operator Type Category Precedence postfix expr++ expr-- Unary ++expr --expr +expr -expr ~ prefix ! multiplicative */% Arithmetic additive +- Shift shift > >>> comparison < > = instanceof Relational equality == != Bitwise bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | logical AND && Logical logical OR || Ternary ternary ?: = += -= *= /= %= &= ^= |= Assignment assignment = >>>= Java Unary Operator The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.: o incrementing/decrementing a value by one o negating an expression o inverting the value of a boolean Java Unary Operator Example: ++ and -- 1. public class OperatorExample{ 2. public static void main(String args[]){ 3. int x=10; 4. System.out.println(x++);//10 (11) 5. System.out.println(++x);//12 6. System.out.println(x--);//12 (11) 7. System.out.println(--x);//10 8. }} Java Arithmetic Operators Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic mathematical operations. Java Arithmetic Operator Example 1. public class OperatorExample{ 2. public static void main(String args[]){ 3. int a=10; 4. int b=5; 5. System.out.println(a+b);//15 6. System.out.println(a-b);//5 7. System.out.println(a*b);//50 8. System.out.println(a/b);//2 9. System.out.println(a%b);//0 10. }} 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. 1. public class OperatorExample{ 2. public static void main(String args[]){ 3. int a=10; 4. int b=5; 5. int c=20; 6. System.out.println(a