Unit-1 Java's Magic PDF
Document Details
Uploaded by EnchantingMeerkat1543
Hemchandracharya North Gujarat University
Tags
Summary
This document describes the evolution, features, and components of Java, a programming language. It details its history, key characteristics, and the Java Development Kit (JDK) along with specifics on the Java Runtime Environment (JRE). The document also provides an introduction to Java's core packages, program structure, variables, and literals.
Full Transcript
Unit-1 What is Java? Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle Corporation). It was released in 1995 and has since become one of the most widely used programming languages in the world. ...
Unit-1 What is Java? Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle Corporation). It was released in 1995 and has since become one of the most widely used programming languages in the world. History of Java 1991: The Birth of Java (Project Green) Java was originally conceived by James Gosling, Mike Sheridan, and Patrick Naughton under the project name "Green." The language was initially called Oak, named after an oak tree outside Gosling's office. 1995: Java is Officially Released Oak was renamed to Java due to trademark issues. Java was officially launched with the tagline "Write Once, Run Anywhere" (WORA) to emphasize its platform independence. 1996: Java Development Kit (JDK) 1.0 The first official version of Java, JDK 1.0, was released. This version introduced core features like applets and basic APIs. History of Java 1997: Oracle Joins the Java Community Oracle became a major contributor to the development and adoption of Java. 2006: OpenJDK Released Sun Microsystems made Java open source by releasing the OpenJDK under the GNU General Public License. OpenJDK is released under the GNU General Public License (GPL) 2010: Oracle Acquires Sun Microsystems Oracle Corporation acquired Sun Microsystems and took over Java's development. Features of Java Platform Independent: / Portable Java follows the principle of "write once, run anywhere." Programs written in Java are converted into bytecode, which can run on any system with a Java Virtual Machine (JVM), regardless of the operating system or hardware. Simple: Java is easy to learn and use, especially for programmers with experience in C++ or object-oriented programming. Its clean syntax and straightforward structure make it accessible and efficient. Object-Oriented: Java uses an object-oriented approach, focusing on objects and their interactions. It balances flexibility by treating basic data types like integers as non-objects for better performance. Robust: Java ensures reliability by managing memory automatically using garbage collection and reducing errors with strong type checking and exception handling. This makes programs less prone to crashes or bugs. Secure: Security is biggest concern for a language which is used for Internet. Java system verify memory access and also ensure no virus are communicated over internet with Applet. Byte-code verifier checks the code fragments for illegal code that can violate access right to object. Features of Java Multithreaded: Java supports multithreaded programming, allowing multiple tasks to run simultaneously. Its built- in tools make it easy to create interactive and efficient applications. Interpreted & High Performance: Java compiles code into bytecode, which runs on the JVM. Performance is boosted with Just-In- Time (JIT) compilers that convert bytecode into machine code as needed. Distributed: Java is built for internet-based environments, supporting TCP/IP protocols and features like Remote Method Invocation (RMI) for executing methods across networks. Dynamic: Java provides run-time information about objects, enabling safe and efficient updates to code. This allows programs to adapt and evolve while running. Understanding JDK 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 + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation: Standard Edition Java Platform (J2SE) Enterprise Edition Java Platform (J2EE) Micro Edition Java Platform (J2ME) Development Tools in JDK Compiler javac: Compiles Java source code (.java files) into bytecode (.class files). Java Launcher java: Launches the Java application by executing the.class files containing the main() method. Debugging Tools jdb: A command-line debugger for inspecting and debugging Java applications. javap: Disassembles compiled.class files and provides information about the bytecode. jconsole: A graphical console for monitoring and managing Java applications using JMX (Java Management Extensions). Documentation Tools javadoc: Generates HTML documentation from Java source code comments written in the Javadoc format. Archiving Tools jar: Creates, views, and manipulates.jar (Java Archive) files, which are used to bundle Java classes and associated metadata/resources. Java Runtime Environment (JRE) The Java Runtime Environment (JRE) is a software package that provides the necessary components to run Java applications. It is a subset of the Java Development Kit (JDK) and includes the runtime components required for executing Java programs but not for developing them. Java Virtual Machine (JVM): – Abstract Machine that will execute bytecode and provides the platform independence that Java is known for. Java Package Classes: – A set of pre-written classes and APIs (e.g., java.lang, java.util, java.io) required for standard functionalities. Runtime Libraries – The runtime libraries are pre-compiled classes that the JVM uses to execute Java programs. JRE – Java Packages A Java package is a namespace for organizing classes and interfaces. The JRE includes several pre-defined packages that offer various functionalities. Key Packages in JRE java.lang – Collection of classes and methods for implementing basic features of Java, like: Object String Math Thread System – Automatically imported into every Java program. java.util – Contains utility classes like: ArrayList, HashMap, HashSet Date, Calendar Collections Framework for data structures. java.io – Handles input and output operations: File, InputStream, OutputStream BufferedReader, PrintWriter. java.net – Provides classes for networking: Socket, ServerSocket URL, HttpURLConnection. java.nio – Supports non-blocking I/O and file system operations: Path, Files ByteBuffer, CharBuffer. JRE – Java Packages java.sql – Includes classes for database connectivity using JDBC: Connection, Statement, ResultSet. java.security – Classes for security features: Key, Certificate MessageDigest, Signature. java.text – For text processing and formatting: DateFormat, NumberFormat SimpleDateFormat. java.time – Introduced in Java 8 for modern date and time API: LocalDate, LocalTime, LocalDateTime Duration, Period. java.awt and javax.swing – For building graphical user interfaces (GUIs): AWT: Button, Frame Swing: JButton, JFrame. java.util.concurrent – Classes for concurrent programming: Executor, Future, Lock. Java Virtual Machine (JVM) A Java Virtual Machine (JVM) is a virtual machine that allows Java bytecode to be executed. It acts as an interpreter between the Java programming language and the underlying hardware. The JVM provides a runtime environment for Java applications to run on different platforms and operating systems. The JVM consists of three distinct components: – Class Loader – Runtime Memory/Data Area – Execution Engine Java Virtual Machine (JVM) Class Loader When you compile a.java source file, it is converted into byte code as a.class file. When you try to use this class in your program, the class loader loads it into the main memory. The first class to be loaded into memory is usually the class that contains the main() method. There are three phases in the class loading process: loading, linking, and initialization. Java Virtual Machine (JVM) Runtime Memory/Data Area Runtime Memory / Data Area is place where the JVM allocates memory to execute Java programs and manage the program's runtime state. The runtime data area includes several specific memory areas, each serving a distinct purpose. Here's an overview: Like Method Arewa, Heap Area, Stack Area, PC Register and Native Method Stack Java Virtual Machine (JVM) Execution Engine Once the bytecode has been loaded into the main memory, and details are available in the runtime data area, the next step is to run the program. The Execution Engine handles this by executing the code present in each class. However, before executing the program, the bytecode needs to be converted into machine language instructions. The JVM can use an interpreter or a JIT compiler for the execution engine. Integrated Development Environment (IDE) A Java IDE is a software application that provides tools and features to streamline and simplify the process of developing Java applications. These tools typically integrate writing, compiling, debugging, and deploying code into a single environment. – Code Editor: A powerful text editor with syntax highlighting, code suggestions, and auto- completion. – Compiler and Debugger: Built-in tools to compile and debug Java code seamlessly. – Project Management: Organizes files and resources into structured projects. – Version Control Integration: Support for tools like Git to manage code versions. – Plugins and Extensions: Extend functionality for frameworks, libraries, or additional languages. – Build Tools: Integration with Maven, Gradle, or Ant for project builds and dependencies. – Graphical Interface: For designing user interfaces (Swing, JavaFX) or visual workflows. – Performance Monitoring: Profiling and performance analysis tools for applications. Integrated Development Environment (IDE) Eclipse: A versatile and widely-used IDE with a powerful plugin ecosystem for Java and other languages. NetBeans: A beginner-friendly IDE with excellent tools for Java SE, Java EE, and JavaFX development. Visual Studio Code: A lightweight editor with Java support through extensions, ideal for small projects. BlueJ: A simple IDE focused on teaching object-oriented programming to beginners. IntelliJ IDEA: Known for its intelligent code assistance and robust support for frameworks like Spring and Hibernate. Android Studio: The go-to IDE for Android app development, optimized for Java and Kotlin. DrJava: A lightweight and straightforward IDE for students and educators to write Java programs. JDeveloper: Oracle’s IDE, designed for enterprise-level Java applications and integration with Oracle databases. Java Program Structure Java Program Structure Package Declaration: Optional, but used to organize classes into namespaces. Example: package com.myapp.utilities; Java Program Structure Import Statements: Optional, but used to include Java classes or packages. Example: import java.util.ArrayList; here, ArrayList is a class which belongs to java.util package. Java Program Structure Class Declaration: As Java is purely Object Oriented Programming Language, every Java program must contain at least one class. Syntax: public class ClassName {... } Java Program Structure Class Declaration: Main Method: Entry point of the program. Syntax: public static void main(String[] args) {... } Understanding Main Method… public Access Modifier: Specifies the visibility of the method. Meaning: The main method must be accessible by the JVM from outside the class to start the program. Declaring it as public ensures it is globally accessible. static Modifier: Indicates that this method is static and thus we can not access it with instance(object) of class. Why? – The JVM can call the main method without creating an object of the class. (This is required because the program starts before any objects are created.) void Return Type: Specifies that the method does not return any value. main Method Name: The name main is a special name in Java and serves as the program's entry point. Purpose: – The JVM looks for this method to start executing a Java program. – If no main method is present in a class, the JVM will throw an error. String[] args Parameter: Represents an array of String values. Purpose: – This parameter allows users to pass arguments to the program via the command line. Understanding System.out.println() System Class: System is a built-in Java class in the java.lang package (which imports by-default). Purpose: – It provides access to system-related functionality. – It contains static fields and methods to interact with the environment, like input/output, system properties, and more. Three Fields if this Class: – System.out: Standard output stream. – System.in: Standard input stream. – System.err: Standard error output stream. out Field: out is a static field of the System class. Type: It is an instance of the PrintStream class. Purpose: Used to display output on the screen. println Method: println is a method of the PrintStream class. Purpose: – Prints the message (argument) passed to it, followed by a newline character (\n). – This means that the next printed output will appear on a new line. Data Types in Java Java is a strongly typed language All constants or variables defined for a given program must be described with one of the Java data types. Java has two categories in which data types are segregated – Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double. The Boolean with uppercase B is a wrapper class for the primitive data type boolean in Java. – Non-Primitive Data Type or Object Data type: such as String, Array, etc. Data Types in Java Java is a strongly typed language All constants or variables defined for a given program must be described with one of the Java data types. Java has two categories in which data types are segregated – Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double. The Boolean with uppercase B is a wrapper class for the primitive data type boolean in Java. – Non-Primitive Data Type or Object Data type: such as String, Array, etc. Primitive Data Types Type Syntax Default Size Example Literals Range of values boolean boolean booleanVar; false 8 bits true, false true, false byte byte byteVar; 0 8 bits (none) -128 to 127 characters ‘a’, ‘\u0041’, ‘\101’, representation of char char charVar; \u0000 16 bits ‘\\’, ‘\’, ‘\n’, ‘β’ ASCII values 0 to 255 short short shortVar; 0 16 bits (none) -32,768 to 32,767 -2,147,483,648 int int intVar; 0 32 bits -2,-1,0,1,2 to 2,147,483,647 - 9,223,372,036,854,77 5,808 long long longVar; 0 64 bits -2L,-1L,0L,1L,2L to 9,223,372,036,854,77 5,807 1.23e100f , -1.23e- float float floatVar; 0.0 32 bits 100f ,.3f ,3.14F upto 7 decimal digits 1.23456e300d , - double double doubleVar; 0.0 64 bits 123456e-300d , 1e1d upto 16 decimal digits Non-Primitive Data Types In java, non-primitive data types are the reference data types or user-created data types. All non-primitive data types are implemented using object concepts. Every variable of the non-primitive data type is an object. The non-primitive data types may use additional methods to perform certain operations. The default value of non-primitive data type variable is null. In java, examples of non-primitive data types are String, Array, List, Queue, Stack, Class, Interface... Non-Primitive Data Types String A string is a sequence of characters, like a word or a sentence, stored in a single variable. A string groups characters into one entity (object). A character array stores individual characters as separate elements. In Java, strings don’t end with a special null character (\0) as in C or C++. Syntax for Declaring a String String stringVariable = "sequence of characters"; Here: – String is the type. – stringVariable is the variable name. – "sequence of characters" is the value assigned to the string. Non-Primitive Data Types Class A class is like a blueprint for creating objects. It defines the properties (variables) and behaviors (methods) that all objects of that type will have. Key Features of Class Modifiers: Defines the access level of the class, such as public or default (no modifier). Example: A public class can be accessed from anywhere. Class Name: The name of the class should start with a capital letter (by convention). Example: Car, Person. Superclass: A class can inherit properties and methods from another class using the extends keyword. Example: class Dog extends Animal. Interfaces: A class can implement one or more interfaces to define specific behaviors. Use the implements keyword followed by a list of interfaces. Example: class Dog implements Pet, Animal. Non-Primitive Data Types Class Class Body: The body of the class contains fields (variables), methods, constructors, and sometimes inner classes. It is enclosed within { } Syntax for Declaring a String class extends implements , ,... { // } Non-Primitive Data Types Object An object is a fundamental unit in Object-Oriented Programming (OOP). It represents a real-world entity and is created from a class. They also referred as instance of class. Objects interact with each other by calling methods. Key Features of Class State: The state of an object is determined by its attributes (also known as fields or properties). These attributes store the data or characteristics of the object. Example: In a Car object, the state could be its color, model, and speed. Behavior: The behavior of an object is defined by its methods. Methods are actions that an object can perform, often changing its state or interacting with other objects. Example: In a Car object, the behavior could be methods like drive() or accelerate(). Identity: Every object has a unique identity, which allows it to be distinguished from other objects. Literals Literals in Java are fixed values directly written in the code. They represent constant values of a specific data type. Literals can be assigned to variables or used directly in expressions. Literals Integer Literals – Represent whole numbers in decimal (base 10), octal (base 8, prefix 0), or hexadecimal (base 16, prefix 0x). – Defaults to int, which is a 32-bit signed integer. For larger values, use the L suffix to indicate long. – Octal values must only use digits 0-7, and hexadecimal uses 0-9 and A-F (case-insensitive). Literals Floating-Point Literals – Represent numbers with fractional parts or in scientific notation. – Defaults to double (64-bit). Use F/f suffix to specify a float (32-bit). – Scientific notation uses E or e to indicate powers of 10, e.g., 6.022E23. Literals Boolean Literals – Represent logical values: true or false. – Cannot be converted to numeric types. – Used in conditional and logical operations. Literals Character Literals – Represent a single character enclosed in single quotes ('). – Support Unicode, ASCII, and escape sequences (\n, \', etc.). – Octal values are written as '\000', and hexadecimal as '\u0000'.. Literals String Literals – Represent a sequence of characters enclosed in double quotes ("). – Supports escape sequences and spans only a single line. Use of Literals Initialization of Variables Constants in Code Direct Use in Expressions Control Flow Decisions Text Representation Variable A variable is the basic unit of storage in Java. It acts as a container to hold data that can be modified during the execution of a program. It has three main parts: – Name (identifier): What the variable is called. – Type: The kind of data it holds (e.g., numbers, text). – Value: An optional value assigned to it when declared. Variables have: – Scope: Where the variable is accessible in the program. – Lifetime: How long the variable exists during program execution Declaring Variable & Example Syntax: type identifier [ = value][, identifier [= value]...] ; Here – Type: The data type of the variables (e.g., int, String, float). – Identifier: The name of the variable(s). – = value (Optional): The value assigned to the variable during declaration. This is optional, and if not provided, the variable will have its default value. – [,] (Comma separator): Used to separate multiple variables declared together. Scope and Lifetime of Variable Scope defines the visibility and accessibility of variables within specific parts of a program. It is determined by blocks of code, enclosed by curly braces {}. – Local Scope: Variables declared inside a method or block are visible only within that block. – Class Scope: Variables declared at the class level are visible throughout the class (not inside methods unless they are parameters or fields). Lifetime refers to how long a variable exists during the program's execution. Variables are created when their scope is entered and destroyed when the scope is exited. – If a variable is declared inside a method, it only exists during the execution of that method. – If declared in a block (e.g., inside an if statement or loop), the variable is created when the block is entered and destroyed when the block is exited. Rules for Naming the Variable A variable name can consist of Capital letters A-Z, lowercase letters a- z digits 0-9, and two special characters such as _ underscore and $ dollar sign. The first character must not be a digit. Blank spaces cannot be used in variable names. Java keywords cannot be used as variable names. Variable names are case-sensitive. There is no limit on the length of a variable name Variable names always should exist on the left-hand side of assignment operators.