Core_Java_Unit_1

Java Fundamentals 
1    Introduction to Java. 
 Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is intended to let application developers write once, and run anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java was first released in 1995 and is widely used for developing applications for desktop, web, and mobile devices. Java is known for its simplicity, robustness, and security features, making it a popular choice for enterprise-level applications. 
JAVA was developed by James Gosling at Sun Microsystems Inc in the May 1995 and later acquired by Oracle Corporation. It is a simple programming language. Java makes writing, compiling, and debugging programming easy. It helps to create reusable code and modular programs. 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++. 

1.1 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, or 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 the bytecode. That is why we call java a platform-independent language. 
2. Object-Oriented Programming Language: Organizing the program in the terms of a 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, and 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. 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 the CPU. 
6. 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. 
7. High Performance: Java architecture is defined in such a way that it reduces overhead during the runtime and at some times 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. 
8. Write Once Run Anywhere: As discussed above java application generates a ‘.class’ file that corresponds to our applications(program) but contains code in binary format. It provides ease to 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. . 

1.2 Basics of Java: - 

Understanding the basics of Java is fundamental to becoming proficient in the language. Here is a concise overview of some of the key concepts: 

1. Data Types 
Java is a statically typed language, which means that each variable must be declared with a data type. Java has two categories of data types: primitive data types and reference data types. 

Primitive Data Types: 
byte: 8-bit signed integer, ranges from -128 to 127. 
short: 16-bit signed integer, ranges from -32,768 to 32,767. 
int: 32-bit signed integer, ranges from -2^31 to 2^31-1. 
long: 64-bit signed integer, ranges from -2^63 to 2^63-1. 
float: Single-precision 32-bit IEEE 754 floating point. 
double: Double-precision 64-bit IEEE 754 floating point. 
boolean: Represents true or false values. 
char: 16-bit Unicode character, ranges from '\u0000' to '\uffff'. 

Reference Data Types: 
Objects: Instances of classes. 
Arrays: Containers that hold multiple variables of the same type. 

2. Variable 
A variable in Java is a container that holds data that can be changed during the execution of a program. Variables must be declared before they are used. The syntax for declaring a variable is: 

dataType variableName = value; 

Example: 
int number = 10; 

3. Expression

An expression in Java is a combination of variables, operators, and method calls that are evaluated to produce a single value. For example: 

int result = 3 + 5; // Expression: 3 + 5 

In this case, 3 + 5 is the expression which evaluates to 8. 

4. Operators 

Operators are special symbols that perform operations on variables and values. Java operators can be categorized as:

Arithmetic Operators:
• + (Addition)
• - (Subtraction) 
• * (Multiplication) 
• / (Division) 
• % (Modulus)

 Relational Operators: 
• == (Equal to) 
• != (Not equal to) 
• > (Greater than) 
• < (Less than) 
• >= (Greater than or equal to) 
• <= (Less than or equal to) 

Logical Operators: 
• && (Logical AND) 
• || (Logical OR) 
• ! (Logical NOT) 

Assignment Operators: 
• = (Assign) 
• += (Add and assign) 
• -= (Subtract and assign) 
• *= (Multiply and assign) 
• /= (Divide and assign) 
• %= (Modulus and assign) 

Unary Operators: 
• + (Unary plus) 
• - (Unary minus) 
• ++ (Increment) 
• -- (Decrement) 
• ! (Logical complement) 

Bitwise Operators: 
• & (Bitwise AND) 
• | (Bitwise OR) 
• ^ (Bitwise XOR) 
• ~ (Bitwise complement) 
• << (Left shift) 
• >> (Right shift) 
• >>> (Unsigned right shift) 

5. Constant 

A constant in Java is a variable whose value cannot be changed once it has been assigned. Constants are declared using the "final" keyword. The naming convention for constants is to use all uppercase letters with words separated by underscores. Example: 

final int MAX_VALUE = 100; 

In this example, MAX_VALUE is a constant, and its value cannot be changed after it has been initialized to 100. 

1.3 Structure of a Java Program 
A typical Java program consists of the following components: 

1. Package Declaration (optional): Defines the package to which the class belongs. 

    package com.example; 

2. Import Statements (optional): Allows the inclusion of other classes and packages. 
    
    import java.util.Scanner; 

3. Class Declaration: Defines the class. 
    
    public class MyClass { 
         // Fields, methods, and constructors go here 
    }

4. Main Method: The entry point of the program where execution begins. 

    public static void main(String[] args) { 
 // Code to be executed 


Example: 

package com.example; 
import java.util.Scanner; 
public class MyClass { 
        public static void main(String[] args) { 
       System.out.println("Hello, World!"); 
     } 

1.4 Execution Process of a Java Program 

1. Writing Code: Write the Java code in a file with a .java extension. 

public class HelloWorld { 
 public static void main(String[] args) { 
 System.out.println("Hello, World!"); 
 } 

2. Compiling Code: Use the Java Compiler (javac) to compile the .java file into bytecode, which is saved in a .class file. 

javac HelloWorld.java 

3. Running the Program: Use the Java Runtime Environment (java) to execute the compiled bytecode. 

java HelloWorld 


1.5 JDK Tools 

The Java Development Kit (JDK) includes various tools for developing and running Java programs: 
• javac: The Java compiler that converts Java source code into bytecode. 
• java: The launcher for Java applications that starts the Java Runtime Environment (JRE). 
• javadoc: Generates HTML documentation from Java source code. 
• jar: Creates and manages Java Archive (JAR) files. 
• jdb: The Java debugger. 
• javap: The class file disassembler. 
• jconsole: Provides monitoring and management of Java applications. 

1.6 Command Line Arguments 

Command-line arguments are parameters passed to the main method of a Java program from the terminal or command prompt. They are used to provide input to the program at runtime. 

Example: 

public class CommandLineExample { 
         public static void main(String[] args) { 
         for (String arg : args) { System.out.println(arg);
             } 
         } 

To run this program with command-line arguments: 
java CommandLineExample arg1 arg2 arg3 

Output: 
arg1 
arg2 
arg3 

In this example, args is an array that contains the command-line arguments passed to the program. Each argument is accessed via the array index. 

1.7 Array and String:

1.7.1 Single Array & Multidimensional Array 

Single Array: 

A single array (or one-dimensional array) is a collection of variables of the same type that are accessed using a single index. 

Declaration: 
        int[] numbers; 

Instantiation: 

    numbers = new int[5]; 

Initialization: 
    numbers[0] = 10; 
    numbers[1] = 20; 
    numbers[2] = 30; 
    numbers[3] = 40; 
    numbers[4] = 50; 

Combined Declaration, Instantiation, and Initialization: 

int[] numbers = {10, 20, 30, 40, 50}; 

Accessing Elements: 

int firstNumber = numbers[0]; // 10 

Iterating through the Array: 

for (int i = 0; i < numbers.length; i++) {
             System.out.println(numbers[i]); 

Multidimensional Array: 

A multidimensional array is an array of arrays. The most common type is the two-dimensional array, which can be visualized as a table or a matrix.

 Declaration: 
        int[][] matrix; 

Instantiation: 
        matrix = new int[3][3]; // A 3x3 matrix 

Initialization: 

matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3; 
matrix[1][0] = 4; 
matrix[1][1] = 5; 
matrix[1][2] = 6; 
matrix[2][0] = 7; 
matrix[2][1] = 8; 
matrix[2][2] = 9; 

Combined Declaration, Instantiation, and Initialization: 

        int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; 

Accessing Elements: 
      
    int element = matrix[1][1]; // 5 

Iterating through the Multidimensional Array: 

    for (int i = 0; i < matrix.length; i++) { 
         for (int j = 0; j < matrix[i].length; j++) { 
                         System.out.print(matrix[i][j] + " "); 
     
     System.out.println(); 

1.7.2 String and String Buffer String: 

Strings in Java are objects that represent sequences of characters. Strings are immutable, meaning their values cannot be changed once they are created. 

Declaration and Initialization: 

String str = "Hello, World!"; 

Common Methods:

 int length = str.length(); // Length of the string 
char ch = str.charAt(0); // Character at index 0 
String substr = str.substring(7); // Substring from index 7 
boolean isEmpty = str.isEmpty(); // Check if string is empty 
String upperCase = str.toUpperCase(); // Convert to uppercase 

String Concatenation: 
String greeting = "Hello"; 
String name = "Alice";
String message = greeting + ", " + name + "!"; // "Hello, Alice!" 

String Buffer: 

StringBuffer is a mutable sequence of characters. Unlike String, StringBuffer can be modified after it is created. It is synchronized, meaning it is thread-safe.

Declaration and Initialization: 

StringBuffer buffer = new StringBuffer("Hello, World!"); 

Common Methods: 

buffer.append(" How are you?"); // Append to the end 
buffer.insert(7, "Alice "); // Insert at index 7 
buffer.replace(0, 5, "Hi"); // Replace from index 0 to 5 
buffer.delete(0, 3); // Delete from index 0 to 3 
String result = buffer.toString(); // Convert to string 


StringBuilder: 

Similar to StringBuffer, but not synchronized. It is faster but not thread-safe. 

Declaration and Initialization: 

StringBuilder builder = new StringBuilder("Hello, World!"); 

Common Methods: 

builder.append(" How are you?"); 
builder.insert(7, "Alice "); 
builder.replace(0, 5, "Hi"); 
builder.delete(0, 3); 
String result = builder.toString(); 

Example Usage: 

public class ArrayStringExample { 
         public static void main(String[] args) { 
             // Single Array 
         int[] numbers = {1, 2, 3, 4, 5}; 
         for (int num : numbers) { 
                 System.out.print(num + " "); 
         } 
         System.out.println();
    
     // Multidimensional Array 
     int[][] matrix = { 
             {1, 2, 3}, 
             {4, 5, 6}, 
             {7, 8, 9} 
 }; 

     for (int i = 0; i < matrix.length; i++) { 
             for (int j = 0; j < matrix[i].length; j++) { 
                     System.out.print(matrix[i][j] + " "); 
     } 
     System.out.println();
     }

     // String 
     String str = "Hello, World!"; 
   System.out.println(str); 

 // StringBuffer 
     StringBuffer buffer = new StringBuffer("Hello, World!"); 
     buffer.append(" How are you?"); 
 System.out.println(buffer.toString()); 

 // StringBuilder 
 StringBuilder builder = new StringBuilder("Hello, World!");
 builder.append(" How are you?"); 
 System.out.println(builder.toString()); 
 } 


This program demonstrates the basics of single arrays, multidimensional arrays, strings, StringBuffer, and StringBuilder in Java. 

1.8 Built In Packages and Classes: 

Java provides a rich set of built-in packages that offer various classes and interfaces for different functionalities. Two of the most commonly used packages are java.util and java.lang. 

1.8.1 java.util 

The java.util package contains utility classes that are commonly used in Java programs. Here are a few important classes: 

Scanner: The Scanner class is used to read input from various sources like keyboard, files, and strings. 

Example: 

import java.util.Scanner; 
public class ScannerExample { 
     public static void main(String[] args) { 
     Scanner scanner = new Scanner(System.in); 
     System.out.print("Enter your name: "); 
     String name = scanner.nextLine(); 
     System.out.println("Hello, " + name + "!"); 
     scanner.close(); 
     } 


Date: The Date class represents a specific instant in time, with millisecond precision. 

Example: 

import java.util.Date; 
public class DateExample { 
     public static void main(String[] args) { 
         Date now = new Date(); 
         System.out.println("Current date and time: " + now);
     } 
}

 Math: The Math class provides methods for performing basic numeric operations such as exponential, logarithm, square root, and trigonometric functions. 

Example: 

public class MathExample { 
         public static void main(String[] args) { 
         double result = Math.sqrt(25); 
         System.out.println("Square root of 25: " + result); 
     result = Math.pow(2, 3); 
 System.out.println("2 raised to the power 3: " + result); 
 result = Math.random(); 
 System.out.println("Random number: " + result); 
 } 
}

 ArrayList: The ArrayList class is a resizable array implementation of the List interface. 

Example:

import java.util.ArrayList; 
 public class ArrayListExample { 
     public static void main(String[] args) { 
     ArrayList list = new ArrayList<>(); 
 list.add("Apple"); 
 list.add("Banana"); 
 list.add("Orange"); 
 for (String fruit : list) { 
         System.out.println(fruit); 
 } 
 } 

1.8.2 java.lang 

The java.lang package is automatically imported into every Java program and contains fundamental classes that are essential to the Java language. 

String: The String class represents sequences of characters and provides methods for string manipulation. 

Example: 

public class StringExample {
     public static void main(String[] args) { 
     String greeting = "Hello, World!"; 
 System.out.println("Length: " + greeting.length()); 
 System.out.println("Uppercase: " + greeting.toUpperCase()); 
     }
 }

System: The System class provides access to system resources like standard input, output, and error streams, and methods for manipulating system properties. 

Example: 

public class SystemExample {
     public static void main(String[] args) { 
         System.out.println("Current time in milliseconds: " + System.currentTimeMillis());                  System.out.println("Environment variable PATH: " + System.getenv("PATH")); 

 } 

Math: Also available in java.lang, providing basic numeric operations. 

Example: 

public class MathLangExample { 
     public static void main(String[] args) { 
     double result = Math.sin(Math.PI / 2); 
     System.out.println("Sin of 90 degrees: " + result); 

 } 

Wrapper Classes: These classes provide a way to use primitive data types (int, boolean, etc.) as objects. 

Example: 
    public class WrapperExample { 
         public static void main(String[] args) { 
     Integer intObj = Integer.valueOf(10); 
    Double doubleObj = Double.valueOf(3.14);
 int intValue = intObj.intValue(); 
 double doubleValue = doubleObj.doubleValue(); 
 System.out.println("Integer value: " + intValue); 
 System.out.println("Double value: " + doubleValue); 

 } 
}


 Thread: The Thread class provides a way to create and manage threads in Java. 

Example:
 public class ThreadExample extends Thread { 
     public void run() { System.out.println("Thread is running.");
 } 
 public static void main(String[] args) {
 ThreadExample thread = new ThreadExample();
 thread.start(); 
 } 
}

 These are just a few examples of the many classes available in the java.util and java.lang packages. These classes provide a wide range of functionality that is essential for developing Java applications.

No comments:

Post a Comment