Introduction to JAVA PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document provides an introduction to Java programming. It covers the history, philosophy, tools, and basic data types used in Java. The document outlines topics such as the versatility of Java, its origins, and its use in various applications.
Full Transcript
Introduction to JAVA UNIT - I Java Java is a high-level, class-based, object-oriented programming language designed to have as few implementation dependencies as possible. It is a general-purpose programming language that is widely used in various dom...
Introduction to JAVA UNIT - I Java Java is a high-level, class-based, object-oriented programming language designed to have as few implementation dependencies as possible. It is a general-purpose programming language that is widely used in various domains like web development, mobile applications (Android), enterprise systems, and more. History of Java Created by Sun Microsystems: Java was initially developed by James Gosling and his team at Sun Microsystems in 1995. The original purpose was for interactive television, but it was too advanced for the cable television industry at the time. Acquired by Oracle: Sun Microsystems was acquired by Oracle Corporation in 2010, and Oracle now maintains Java. Java Philosophy "Write Once, Run Anywhere" (WORA): Java is designed to be platform-independent at both the source and binary levels, meaning that compiled Java code (bytecode) can run on any device that has the Java Virtual Machine (JVM). Why learn Java? Versatility: Java is used in a wide range of applications, from desktop to web to mobile applications. Popularity: Java is one of the most popular programming languages in the world, with a large community and extensive resources. Strong Object-Oriented Features: Java’s object-oriented structure is essential for building modular and maintainable code. Platform Independence: Java code can run on any machine that has the JVM, making it highly portable. Robustness: Java has strong memory management features, exception handling, and a powerful security model. Large Ecosystem: Java has a rich ecosystem with a vast standard library, as well as many third-party libraries and frameworks. Java Syntax and Structure Case Sensitivity: Java is case-sensitive, which means MyClass and myclass would be considered different identifiers. Class-Based: Everything in Java is encapsulated within classes. Entry Point: The entry point of any Java application is the main method: public static void main(String[] args). Java Development Tools JDK (Java Development Kit): A software development environment used for developing Java applications. It includes the JRE (Java Runtime Environment), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other tools. JVM (Java Virtual Machine): An abstract machine that provides a runtime environment to execute Java bytecode. IDEs (Integrated Development Environments): Tools like Eclipse, IntelliJ IDEA, and NetBeans provide a comprehensive environment for Java development. Writing and Running Java Programs Setting Up the Environment: Download and Install JDK: Ensure the JDK is installed and the JAVA_HOME environment variable is set. Choose an IDE: Use an IDE like IntelliJ IDEA, Eclipse, or NetBeans to write and manage your Java code. Compile and Run: Compile: javac HelloWorld.java (Compiles the Java source file to bytecode). Run: java HelloWorld (Executes the compiled bytecode). Data Types Java Is a Strongly Typed Language Every variable has a type, every expression has a type, and every type is strictly defined. All assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility. Data Types Data Types Primitive Data Types: They form the basis for all other types of data that you can create in Java. The primitive types represent single values—not complex objects. Although Java is otherwise completely object-oriented, the primitive types are not. They are analogous to the simple types found in most other non–object-oriented languages. All data types have a strictly defined range and mathematical behavior. Integers: This group includes byte, short, int, and long, which are for whole-valued signed numbers. Floating-point numbers: This group includes float and double, which represent numbers with fractional precision. Characters: This group includes char, which represents symbols in a character set, like letters and numbers. Boolean: This group includes boolean, which is a special type for representing true/false values. Data Types - Integers Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values. Java does not support unsigned, positive-only integers. Byte – The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127. Variables of type byte are especially useful when you’re working with a stream of data from a network or file. They are also useful when you’re working with raw binary data. Short – short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-used Java type. Int – The most commonly used integer type is int. It is a signed 32-bit type that has a range from – 2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to index arrays. Long – long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. The range of a long is quite large. This makes it useful when big, whole numbers are needed. Data Types – Floating Point Types Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. Java implements the standard (IEEE–754) set of floating-point types and operators. There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively. The type float specifies a single-precision value that uses 32 bits of storage. Variables of type float are useful when you need a fractional component, but don’t require a large degree of precision. Double precision, as denoted by the double keyword, uses 64 bits to store a value. Floating Point Numbers IEEE 754 Standard: 32-bit Floating Point (Single-Precision): Format: 1 sign bit, 8 exponent bits, 23 mantissa (fraction) bits. Range: Approximate range: −3.4028235×1038 to 3.4028235×1038 for normal values. Smallest positive value: 1.4×10−45 Precision: About 6-7 decimal digits. 64-bit Floating Point (Double-Precision): Format: 1 sign bit, 11 exponent bits, 52 mantissa (fraction) bits. Range: Approximate range: −1.7976931348623157×10308 to 1.7976931348623157×10308 for normal values. Smallest positive value: 4.9×10−324 Precision: About 15-16 decimal digits. Data Types - Chars In Java, the data type used to store characters is char. Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages (world wide). It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Hebrew, and many more. For this purpose, it requires 16 bits. In Java, char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127. and the ISO-Latin-1, ranges from 0 to 255. Since Java is designed to allow programs to be written for worldwide use, it makes sense that it would use Unicode to represent characters. Data Types - Boolean Java has a primitive type, called boolean, for logical values. It can have only one of two possible values, true or false. This is the type returned by all relational operators, as in the case of a < b. Boolean is also the type required by the conditional expressions. Example – Using Boolean // Demonstrate boolean values. class BoolTest { public static void main(String args[]) { boolean b; b = false; System.out.println("b is " + b); b = true; // a boolean value can control the if statement if(b) System.out.println("This is executed."); b = false; if(b) System.out.println("This is not executed."); // outcome of a relational operator is a boolean value System.out.println("10 > 9 is " + (10 > 9)); }} Literals A literal is a specific value directly written into the code. It's the actual value, like 42, "Hello", 3.14, etc. Examples: Integer Literal: 100 String Literal: "Hello" Floating-point Literal: 3.14 Boolean Literal: true or false Literals represent fixed values that you use directly in your code. Constants A constant is a variable whose value is fixed once assigned and cannot be changed during the execution of the program. Constants can be defined using literals. Declaration: In many programming languages, constants are explicitly declared using keywords like const (in JavaScript, C++, etc.) or final (in Java). Examples: (In Java) final int MAX_HEIGHT = 100; Literals vs Constant Mutability: 1. Literals: Are just values, not variables, and are immutable by nature. 2. Constants: Are variables that are initialized once and then cannot be changed. Purpose: 1. Literals: Provide direct values in the code. 2. Constants: Provide a way to name these values, ensuring they remain unchanged and making code easier to understand and maintain. Note: Literals can be used to initialize constants, but they themselves are not variables or constants. They are just the values. Variables The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime. The basic form of a variable declaration is: type identifier [ = value]; The type is one of Java’s atomic types (primitive data types), or the name of a class or interface. Variables – Dynamic Initialization Dynamic initialization in Java refers to the process of initializing variables at runtime, typically using values that are determined during the execution of the program rather than at compile time. This is in contrast to static initialization, where variables are initialized with fixed values at the time of declaration. class DynInit { public static void main(String args[]) { double a = 3.0, b = 4.0; //static initialization // c is dynamically initialized double c = Math.sqrt(a * a + b * b); System.out.println("Hypotenuse is " + c); }} Scope and Lifetime of Variables Java allows variables to be declared within any block. A block begins with an opening curly brace and ends by a closing curly brace. A block defines a scope. Thus, each time you start a new block, you are creating a new scope. A scope determines what variables are visible to other parts of your program. It also determines the lifetime of those variables. Within a block, variables can be declared at any point, but are valid only after they are declared. For example, this fragment is invalid because count cannot be used prior to its declaration: count = 100; // oops! cannot use count before it is declared! int count; Scopes can be nested. When you create a new block inside an existing block, the outer scope encloses the inner scope. This means that variables declared in the outer scope will be visible to code within the inner scope. However, the reverse is not true. Example - Scope and Lifetime of Variables // Demonstrate block scope. class New { public static void main(String args[]) { int x; // variable x known to all code within main x = 10; if(x == 10) { // start new scope int y = 20; // variable y known only to this block System.out.println("x and y: " + x + " " + y); // x and y both known here. x = y * 2; } y = 100; // Error! y not known here System.out.println("x is " + x); // variable x is still known here. }} Scope and Lifetime of Variables Although blocks can be nested, you cannot declare a variable to have the same name as one in an outer scope. For example, the following program is illegal: // This program will not compile class example { public static void main(String args[]) { int bar = 1; { // creates a new scope int bar = 2; // Compile-time error – bar already defined! } }} Scope and Lifetime of Variables Variables are created when their scope is entered, and destroyed when their scope is left. This means that a variable will not hold its value once it has gone out of scope. Therefore, variables declared within a method will not hold their values between calls to that method. Also, a variable declared within a block will lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope. In Java, the two major scopes are those defined by a class and those defined by a method. (Shall be discussed later). Type Casting Automatic Type Conversion: When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met: 1. The two types are compatible. 2. The destination type is larger than the source type. The numeric types, including integer and floating-point types are compatible with each other. But not all types are compatible. For example: double to byte, int to byte, numeric types to char or boolean. Also, char and Boolean are not compatible with each other. Note: Java also performs an automatic type conversion when storing an integer literal into variables of type byte, short, long, or char. Type Casting To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. It has this general form: (target-type) value target-type specifies the desired type to convert the specified value to. For example, the following fragment casts an int to a byte. If the integer’s value is larger than the range of a byte, it will be reduced modulo (the remainder of an integer division by the) byte’s range. int a; byte b; b = (byte) a; Type Casting - Truncation A different type of conversion will occur when a floating-point value is assigned to an integer type called as truncation. When a floating-point value is assigned to an integer type, the fractional component is lost. For example, if the value 1.23 is assigned to an integer, the resulting value will simply be 1. If the size of the whole number component is too large to fit into the target integer type, then that value will be reduced modulo the target type’s range. Type Promotion Type Promotion Rules: First, all byte, short, and char values are promoted to int. Java automatically promotes each byte, short, or char operand to int when evaluating an expression. For example: byte b = 50; b = b * 2; // Error! Cannot assign an int to a byte! Then, if one operand is a long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands is double, the result is double.