Java Programs //





Introduction to Java and its features 

 Java is a general-purpose, 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, run anywhere" (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture.

Java is a popular programming language, used for developing web, mobile, and desktop applications. It is used for developing applications for multiple platforms, including Windows, Mac OS, and the various versions of UNIX. Java is object-oriented and can be used to create complex applications. It is a secure programming language and provides robust security. Java is a high-level programming language, which means that it is easier to read and write than lower-level languages such as machine code. Java is platform-independent, meaning that it can be run on any system that has a Java Virtual Machine (JVM). This makes Java applications portable and helps to keep the cost of development down. Java also supports multithreading, which allows multiple tasks to be executed concurrently. This makes it easier to create applications that have complex logic and are capable of running multiple tasks at once. Java has a large set of libraries and tools that make development easier. The Java API (Application Programming Interface) provides access to many useful classes and methods to help developers quickly build applications. Additionally, Java has a large community of developers who have created a wide range of open-source libraries and tools for use in Java applications.


Features of Java:-

1. Object Oriented: Java is an object-oriented language, meaning that it uses objects to achieve code re-usability and encapsulation. Classes, objects, methods, and variables are used to create a modular design, which helps make code easier to understand, maintain, and reuse. 2. Platform Independent: Java is platform-independent because it is not dependent on any specific operating system or hardware. It can run on any type of computer, as long as a Java Virtual Machine (JVM) is installed. It allows developers to write code once and run it on multiple platforms. 3. Robust: Java is designed to be robust and secure, making it difficult for errors or malicious code to run on the system. It also detects memory errors during runtime and can handle exceptions to prevent system crashes. 4. Portable: Java is highly portable, meaning that it is easy to move to different computing environments without making any changes to the code. It is easy to compile Java code, which makes it easier to deploy on different operating systems. 5. Multi-Threaded: Java supports multi-threading, which means that it can run multiple tasks at the same time. This makes it easy to develop applications that are fast and efficient. 6. Extensive API: Java has an extensive API (Application Programming Interface) that allows developers to access hundreds of pre-defined classes, methods, and functions which can be used to develop applications. 7. Functional Programming: Java supports functional programming, which means that code can be broken down into small, re-usable modules that can be incorporated into multiple projects. This makes code easier to maintain and update.



 Benefits of Java programming language:-

Java is an extremely popular and versatile programming language that has changed the face of software development. Java has been around since 1995 and is now used to power various applications and devices. It is designed to be a powerful, secure and versatile language with capabilities to handle a variety of tasks. Here are some of the benefits of using Java: 1. Easier to Learn: Java is one of the simplest language to learn due to its organized and object-oriented nature. If a developer is familiar with other object-oriented languages, like C++ and Python, then it be an ease for him to learn and work with Java. 2. Platform Independence: Java provides the feature of being independent of any platform or system. It can run on multiple platforms, like Windows, MacOS, and Linux, without having to make any changes in its code. There is no need to compile the code again and again every time a code is run on a different system. 3. Security: Java has built-in security features and can identify and neutralize threats even before they hit the system. It also enables developers to create secure web applications. 4. Robustness: Java programs are highly reliable due to its storage management, compiler and garbage collection features. The runtime environment in Java automatically detects and eliminate any common errors. 5. Speed: Java code execution is faster than other languages, as the bytecodes are executed directly by the JVM instead of being compiled first. 6. Scalability: Java code can be easily scaled in terms of design, development and maintenance as it follows a modular approach which helps in the easy development and debugging of code. 7. Open Source: Java is an open-source language, which means anyone can access and modify its code for their own applications. Overall, Java is an important programming language which provides a number of benefits to developers, helping them in creating high-quality applications and software. Its strong syntax and versatility makes it the right language for any development project.



Advantages of Java over other programming languages:-

Java is a popular programming language used across numerous enterprise and consumer applications. Its one of the most sought-after languages due to its versatility, scalability, and robust security. Here are a few of the main advantages of using Java over other programming languages: Platform independence: Java allows developers towrite once, run anywhere, meaning that the same code can be used on different platforms without the need for any modifications. Automatic memory management: Java has an automatic memory management feature that helps reduce common programming errors caused by incorrect memory allocation. Robotics: Java has become an important language for robotics due to its low cost, easy learning curve, and robustness. Scalability: Java is highly scalable and can be used for applications as large and complex as web servers, enterprise applications, and mobile applications. Security: Java is well known for providing a secure coding environment. It has built-in security features such as data encryption, dynamic class loading, and reliable code execution. Open source: The language has an extensive library of open source libraries and frameworks. This makes it easier for developers to develop applications quickly. Overall, Java is a great language for enterprises, consumers and developers alike. With its robust security, scalability, and platform independence, its no surprise that Java continues to be a popular choice for many applications.


How to write Java code :-

1. Open a Java coding program like Eclipse or IntelliJ. This type of program provides an optimal working environment to write Java code. On the left side of the window, you will find the the spaces where you can copy and paste your desired code snippets. 2. Best practices always recommend that you organize your code in different sections for easy readability. Start with general declarations like global variables or imports. 3. Then move on to writing classes, which are like containers for your code. Each class should have a constructor, which is created and defined in the class body using the keywordpublic. 4. Then you must create the method in which the code will be executed. This is done by typing public void methodName. 5. Next, you must write your code. This can be done by simply typing the desired keywords and / or variables in the method body. 6. Finally, you will need to use the keywordreturn to exit the method and return to the main program. 7. Now you have finished writing your Java code. You can save the file and run the program to check if it is working as expected.



PROGRAMS

1: Introduction to Object Oriented Programming and

 Installation of JDK. Write a program to print a message

 ”Hello World...”.


Theory: JDK Installation Instructions for Windows

You run a self-installing executable file to unpack and install the JDK on Windows computers.

Install JDK on Windows computers by performing the actions described in the following topics:

·         Downloading the JDK Installer

·         Installing the JDK from the JDK .exe Installer

·         Installing the JDK from the MSI Enterprise Installer

·         Installing the JDK Silently

Downloading the JDK Installer

Access the Java SE Downloads page and click Accept License Agreement. Under the Download menu, click the Download link that corresponds to the .exe for your version of Windows.

Download the file jdk-18.interim.update.patch_windows-x64_bin.exe.

Note:

Verify the successful completion of file download by comparing the file size on the download page and your local drive. Alternatively, you can ensure that the downloaded file's checksum matches the one provided on the Java SE Downloads page.

Installing the JDK from the JDK .exe Installer

You must have administrator privilege to install the JDK on Microsoft Windows.

To run the JDK installer:

1.      Start the JDK 18 installer by double-clicking the installer's icon or file name in the download location.

2.      Follow the instructions provided by the installer.

3.      After the installation is complete, delete the downloaded file to recover the disk space.

Alternatively, you can run these executables directly from the JDK's bin directory.

Installing the JDK from the MSI Enterprise Installer

The JDK MSI Enterprise Installer is packaged as a .msi installer and runs with minimal dialogs. It supports silent installation of the JDK and is customizable using command line parameters.

You must have administrative permissions install JDK 18.

1.      Download jdk-18_windows-x64_bin.msi.

2.      Double click the .msi file to run the installer.

Installing the JDK from the Command Line

You can install the JDK by downloading the appropriate Oracle JDK MSI Enterprise Installer for your system and running it from the command line.

3.      Download jdk-18_windows-x64_bin.msi.

4.      Open an MS-DOS prompt with Administrative permissions.

5.      Run one of the following commands depending on the type of installation that you want to perform:

o   Basic UI mode:Copymsiexec.exe /i installer.msi

o   Silent mode:Copymsiexec.exe installer.msi /qn

Creating a Log File

You can use a log file to verify that an installation succeeded.

To create a log file describing the installation, append /L C:\path\setup.log to the install command and scroll to the end of the log file to verify.

The following is an example of creating a log file:

Copymsiexec.exe /i installer.msi /L C:\path\setup.log

In this example, the log is written to the C:\path\setup.log file.

Installing the JDK Silently

Instead of double-clicking or opening the JDK installer, you can perform a silent, non interactive, JDK installation by using command-line arguments.

Install JDK in silent mode using the command:Copyjdk.exe /s

Beginning to Use the JDK

Use the Java Development Kit in the Windows Start menu to access information related to Reference Documentation.

During JDK installation, Java menu items are added to the Windows Start menu to provide easy access to Reference Documentation, which is online documentation web page.

During JDK installation and uninstallation processes, the appropriate start menu items are updated so that they are associated with the latest JDK version on the system


Write "hello world" program in java:-

Code:-

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

Output:-


This program prints "Hello World!" when executed. This is usually the first program beginners learn how to write in any programming language; it is a simple way to begin understanding how different coding constructs work. The program begins by declaring a class, "HelloWorld" that contains a single static method, "main". This method requires an array of strings as a parameter, however since the program does not require any input the array is empty. Inside the main method, a single line is run: System.out.println("Hello World!"). This line prints the "Hello World!" string to the console.

 

 2: Develop a program to explain use of Operators in Java


Theory:-

Operators are special symbols in Java that perform specific operations on one, two, or three operands and produce a result. Java has a wide range of operators to perform various operations. 1. Arithmetic Operators: These operators are used to perform arithmetic operations on two operands. Java arithmetic operators include addition (+), subtraction (-), multiplication (*), division (/), modulus (%) and increment (++). 2. Relational Operators: These operators are used to compare two operands and return true or false depending on the result of the comparison. Java relational operators include equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=) and less than or equal to (<=). 3. Logical Operators: These operators are used to perform logical operations on two or more boolean values and return true or false depending on the result of the operation. Java logical operators include AND (&&), OR (||) and NOT (!). 4. Bitwise Operators: These operators are used to perform bitwise operations on two operands. Java bitwise operators include AND (&), OR (|), XOR (^), NOT (~), left shift (<<


Code:

class operator

{

 public static void main(String[] args)

 {

    int a = 122, b = 105;

    System.out.println("a + b = " + (a + b));

    System.out.println("a - b = " + (a - b));

    System.out.println("a * b = " + (a * b));

    System.out.println("a / b = " + (a / b));

    System.out.println("a % b = " + (a % b));

    if(a>b)

    System.out.println("a is greater");

    if(a<b)

    System.out.println("b is greater");

    int x=47, y=105;

    System.out.println("value of x|y is=" + (x | y));

    System.out.println("value of x&y is=" + (x & y));

    System.out.println("value of x^y is=" + (x ^ y));

   }

 }

Output:






3 : Develop a Program to study and implements Looping Statements belonging to Java.


Theory: 

1. Identify the types of looping statements available in Java: Java has four main types of looping statements, including for loop, while loop, do-while loop, and enhanced for loop.

2. Determine the purpose and scope of each statement: Each looping statement has a specific purpose and scope, so research should be done to determine how each statement is used. 3. Understand the syntax of each statement: Syntax is important when programming in Java and looping statements have specific syntax requirements. 4. Learn the different ways to use each statement: Once the syntax is understood, research should be done to understand the different ways each statement can be used. 5. Practice writing code: After understanding the syntax and different uses of each statement, the student should practice writing code to implement the looping statements. 6. Debug code: Debugging is an important part of programming, so students should learn to debug their code when necessary. 7. Understand the impact of looping statements on performance: Looping statements can have an effect on the performance of a program, so understanding how each statement affects performance is important. 8. Compare looping statements: Comparing looping statements is another.

Code:-

class for_whileloop

{

    public static void main(String args[])

    {

       

        for (int i = 1; i <= 5; i++)

            System.out.println("for loop");

 

        int i = 1;

        while (i < 6) {

            System.out.println("while loop");

            i++;

             }

        int j=1;

        do

          {

           System.out.println("do while loop");

           j++;

          }while(j < 6);

     }

}


Output:



 

4 : Develop a Program to study and implements Statements belonging to Java. 


Theory:

This theory proposes a program to study and implement statements belonging to Java. The program will use a compilation-based approach to analyzing and understanding the syntax and semantics of Java statements. The program will first parse the Java statements into a parse tree and then analyze each component of the tree for its syntax and semantics. The program will then generate an optimized intermediate representation (IR) for the Java statements. Finally, the program will generate code for the Java statements that is optimized for execution on the target platform. The program will also take into account any optimizations that the user has specified. By applying the principles of compilation, the program will be able to generate code that is optimized for both performance and memory usage.

Code:

class mypg4

{

       public static void main(String[] args) {

              int x=7425;

              int y=2797;

              int z=3949;

              if(x>y && x>z)

              {

             System.out.println("x = " +x+ "is biggest");    

              }

              else if (y>x && y>z)

              {

                  System.out.println("y = " +y+ "is biggest");

              }

              else

              {

                  System.out.println("z = " +z+ "is biggest");

              }

          }

}


Output:








5: Develop a program to demonstrate the concept of

 Class, Method and Object.


Theory:

Class: A class is a template or blueprint that is used to create objects. It serves as a foundation for objects and can be used to define the properties, characteristics, and behaviors of a particular type of object.

Method: A method is a block of code that can be used to perform a specific task. Methods are associated with classes and can be used to define the functionality of an object. Object: An object is an instance of a class and can be used to store data and perform operations. Objects are created from classes and can contain data such as variables and methods.

Code:

class pr_6

{

int a=25;

void sum_d()

{

int sum;

sum=a+a;

System.out.println("the sum of number a is " + sum);

}

public static void main(String args[])

{

pr_6 o1=new pr_6();

o1.sum_d();

}

}                     


 OUTPUT:-





6: Develop a program to study and implement

 the concept of method overloading.


Theory :

1. Create a class with multiple methods with the same name but different parameter types and number of parameters. 2. In the main method, call the overloaded methods with different parameters. 3. Use the if-else statement to identify the parameters type and number of parameters. 4. Based on the parameters type and number of parameters, call the appropriate method. 5. For each method, use the appropriate logic to perform the desired operations. 6. After the operations are done, print out the result. 7. Repeat the process until the program terminates.


Code:

class method_overload

{

int length,breadth,side;

void area(int l,int b)

{

int Area;

length=l;

breadth=b;

Area=l*b;

System.out.println("area of rectangle is "+Area);

}

void area(int s)

{

int area_;

side=s;

area_=s*s;

System.out.println("area of square is "+area_);

}

 

public static void main(String args[])

{

 method_overload O1=new method_overload();

 O1.area(15,23);

 O1.area(69);

}

}

 

Output:







7 : Develop a program to and implement concept of

 Constructor in Java.


Theory :

Constructors are special methods in Java that are used to initialize objects. They are invoked when an object is created and are used to set the initial state of an object. Constructors typically have the same name as the class in which they are defined and take in parameters that are used to set the initial state of the object.

Implementation: To implement the concept of constructors in Java, the following steps should be followed: 1. Declare a class in which the constructor will be defined. 2. Include a constructor method with the same name as the class and define the parameters that will be used to set the initial state of the object. 3. Invoke the constructor when an object is created, passing in the necessary parameters. 4. Set the initial state of the object with the values of the parameters passed in. 5. Use appropriate access modifiers to control how the constructor is accessed.

Code:

class A_area

{

int length, breadth, area;

A_area()

{

length=55;

breadth=24;

}

void area()

{

area=length*breadth;

System.out.println("area is " + area);

}

public static void main(String args[])

{

A_area a=new A_area();

a.area();

}

}

 

Output:







8: Develop a program to study and implement concept of Constructor Overloading.


Theory :

Program to Study and Implement Constructor Overloading:

1. Constructor Overloading is a feature of object-oriented programming that allows for the creation of multiple constructors for a single class with different parameters.

2. Overloaded constructors are used to initialize objects with different sets of initial values.

3. When a class has multiple constructors, each constructor must have a unique list of parameters.

4. Constructor Overloading can be used to create multiple versions of the same constructor with different parameters.

5. The constructor with the most specific parameters is called first when an object is created.

6. If a constructor with the exact same parameter list is not found, the compiler will try to find a constructor with a compatible parameter list.

7. If a compatible constructor is found, the compiler will use it to create the object.

8. Constructor Overloading can also be used to provide default values for parameters.

9. The program should be able to create objects with different sets of initial values using constructor overloading.

10. The program should be able to demonstrate the concept of constructor overloading by creating objects with different sets of parameters.


Code:

class Rectangle 
{
    int length;
    int breadth;
    Rectangle()//constructor without arguments
    {
        length  = 47;
        breadth = 96;
    }
    Rectangle(int l, int b)//constructor with argument
    {
        length = l;
        breadth = b;
    }
    void area()
    {
        int area_a;
        area_a = length * breadth;
        System.out.println("Area of rectangle is "+area_a);
        
    }
    public static void main(String args[])
    {
       Rectangle r = new Rectangle();
       r.area();
       Rectangle r1 = new Rectangle(20,40);
       r1.area();
    }
}


Output:




9: Develop a program to study and implement concept of Array in Java.

Theory : 1. Arrays in Java can be defined as a collection of similar data type elements. 2. Array elements are accessed using zero-based indexing. 3. Arrays can be declared in two ways: a. Declaring an array of a specific size b. Declaring an array without specifying its size 4. Arrays can be multidimensional, with elements of each array indexed by multiple indices. 5. Java provides a number of built-in methods for working with arrays. 6. Arrays can be passed as parameters to methods. 7. Arrays can be sorted using the Arrays.sort() method. 8. Arrays can be searched using the Arrays.binarySearch() method. 9. The length of an array can be determined using the arrayname.length attribute. 10. The Arrays class contains a number of static methods for manipulating arrays. 11. Array elements can be accessed using the arrayname[index] notation. 12. Array elements can be assigned values using the arrayname[index] = value notation.

Code: class Array { public static void main(String args[ ]) { int A[ ]={4,5,8,189,219,215,6,123,4,89,8911,1444}; int n,i,j,temp; n = A.length; for(i=0;i<n;i++) { for(j=1+i;j<n;j++) { if(A[ i ]>A[ j ]) { temp=A[ i ]; A[ i ]=A[ j ]; A[ j ]=temp; } } } for(i=0;i<n;i++) { System.out.println(""+A[ i ]); } } }

Output:-




 




Post a Comment

Previous Post Next Post