JAVA PROGRAMMING EXAMPLES WITH OUTPUT PDF

adminComment(0)

To understand a programming language you must practice the programs, this way you can learn the language faster. This page includes java programs on. programming languages are presented through writing Java programs. Java is The source code used in all examples, as well as possible list of errata. Download as PDF, TXT or read online from Scribd the no. of elements in the array, For example in the second case above when p is not Output: This java program finds if a number is odd or even. If the number is divisible by 2 then it.


Java Programming Examples With Output Pdf

Author:ARLETHA ZAHNISER
Language:English, German, Hindi
Country:Lithuania
Genre:Science & Research
Pages:247
Published (Last):01.03.2015
ISBN:327-2-47813-883-3
ePub File Size:30.49 MB
PDF File Size:18.25 MB
Distribution:Free* [*Sign up for free]
Downloads:22722
Uploaded by: STARLA

bestthing.info - Download as PDF File .pdf), Text File .txt) or read online. what programming is, but you've heard Java is easy to learn, really powerful, and very cool. An Output icon highlights what the same HTML code looks like when viewed by For example, a printing code of shows that the first printing of. r Example: Determining a Variable's Scope q Summary q Review Questions q Review Exercises. Chapter 6 Simple Input and Output.

Here we are using min and max methods of Math class, min returns minimum of two integers and max returns maximum of two integers. Following will produce an error:. We need to write class name because many classes may have a method with same name which we are calling.

Using multiple classes in Java program ava program can contain more than one i. Following example Java program contain two classes: Computer and Laptop. Both classes have their own constructors and a method. In main method we create object of two classes and call their methods.

Using two classes in Java program. Java constructor tutorial with code examples Constructor java tutorial: Java constructors are the methods which are used to initialize objects. Constructor method has the same name as that of class, they are called or invoked when an object of class is created and cant be called explicitly. Attributes of an object may be available when creating objects if no attribute is available then default constructor is called, also some of the attributes may be known initially.

It is optional to write constructor method in a class but due to their utility they are used. Java constructor example. This code is the simplest example of constructor, we create class Programming and create an object, constructor is called when object is created. As you can see in output Constructor method called. Java constructor overloading Like other methods in java constructor can be overloaded i. Number of constructors depends on the information about attributes of an object we have while creating objects.

See constructor overloading example: When cpp object is created default constructor is called and when java object is created constructor with argument is called, setName method is used to set name attribute of language, getName method prints language name. Java constructor chaining Constructor chaining occurs when a class inherits another class i. Both the super and sub class may have constructor methods, when an object of sub class is created its constructor is invoked it initializes sub class attributes, now super class constructor needs to be invoked, to achieve this java provides a.

For more understanding see constructor chaining example:. Constructor method doesnt specify a return type, they return instance of class itself. Java program to swap two numbers This java program swaps two numbers using a temporary variable.

To swap numbers without using extra variable see another code below. Swapping using temporary or third variable. Java program to find largest of three numbers This java program finds largest of three numbers and then prints it. If you want to find out largest of a list of numbers say 10 integers then using above approach is not easy, instead you can use array data structure.

Enhanced for loop java Enhanced for loop java: Enhanced for loop is useful when scanning the array instead of using for loop.

Syntax of enhanced for loop is: Java enhanced for loop integer array. Java exception handling tutorial with example programs Java exception handling tutorial: In this tutorial we will learn how to handle exception with the help of suitable examples.

Exceptions are errors which occur when the program is executing. Consider the Java program below which divides two integers. Now we compile and execute the above code two times, see the output of program in two cases:. In the second case we are dividing a by zero which is not allowed in mathematics, so a run time error will occur i.

If we write programs in this way then they will be terminated abnormally and user who is executing our program or application will not be happy. This occurs because input of user is not valid so we have to take a preventive action and the best thing will be to notify the user that it is not allowed or any other meaningful message which is relevant according to context.

Note that exceptions dont occur only because of invalid input only there are other reasons which are beyond of programmer control such as stack overflow exception, out of memory exception when an application requires memory larger than what is available.

Java provides a powerful way to handle such exceptions which is known as exception handling. In it we write vulnerable code i. Following modified code handles the exception. Java exception handling example. Whenever an exception is caught corresponding catch block is executed, For example above code catches ArithmeticException only.

If some other kind of exception is thrown it will not be caught so its the programmer work to take care of all exceptions as in our try block we are performing arithmetic so we are capturing only arithmetic exceptions.

A simple way to capture any exception is to use an object of Exception class as other classes inherit Exception class, see another example below: Here our catch block capture an exception which occurs because we are trying to access an array element which does not exists languages[5] in this case. Once an exception is thrown control comes out of try block and remaining instructions of try block will not be executed.

At compilation time syntax and semantics checking is done and code is not executed on machine so exceptions can only be detected at run time. Finally block in Java Finally block is always executed whether an exception is thrown or not.

Exception occurred because we try to allocate a large amount of memory which is not available. This amount of memory may be available on your system if this is the case try increasing the amount of memory to allocate through the program. Java program to find factorial This java program finds factorial of a number. Entered number is checked first if its negative then an error message is printed. Java programming code.

You can also find factorial using recursion, in the code fact is an integer variable so only factorial of small numbers will be correctly displayed or which fits in 4 bytes. For large numbers you can use long data type. Because 20! To calculate factorial of say hundred we use BigInteger class of java. We run the above java program to calculate factorial and following output is obtained.

Java program print prime numbers This java program prints prime numbers, number of prime numbers required is asked from the user. Remember that smallest prime number is 2.

Java programs

We have used sqrt method of Math package which find square root of a number. To check if an integer say n is prime you can check if it is divisible by any integer from 2 to n-1 or check from 2 to sqrt n , first one is less efficient and will take more time. Java program to print Floyds triangle This java program prints Floyds triangle. This is a simple pattern to print but helpful in learning how to create other patterns.

Key to develop pattern is using nested loops appropriately. Java program to reverse a string This java program reverses a string entered by the user. We use charAt method to extract characters from the string and append them in reverse order to reverse the entered string.

Java program to check palindrome Java palindrome program: Java program to check if a string is a palindrome or not. Remember a string is a palindrome if it remains unchanged when reversed, for example dad is a palindrome as reverse of dad is dad whereas program is not a palindrome.

Some other palindrome strings are mom, madam, abcba. Interface in Java Interface in Java: Java interfaces are like Java classes but they contain only static final constants and declaration of methods. Methods are not defined and classes which implements an interface must define the body of method s of interface s. Final constants cant be modified once they are initialized; final, interface, extend and implements are Java keywords. Declaration of interface:. Interface program in Java In our program we create an interface named Info which contains a constant and a method declaration.

We create a class which implements this interface by defining the method declared inside it. Java program to compare two strings This program compare strings i. If you wish to compare strings but ignoring the case then use compareToIgnoreCase method. To check two strings for equality you can use equals method which returns true if strings are equal otherwise false.

Java program for linear search Java program for linear search: Linear search is very simple, To check if an element is present in the given list we compare search element with every element in the list. If the number is found then success occurs otherwise the list doesnt contain the element we are searching. Above code locate first instance of element to found, you can modify it for multiple occurrence of same element and count how many times it occur in the list.

Similarly you can find if an alphabet is present in a string. Java program for binary search Java program for binary search: This code implements binary search algorithm. Please note input numbers. Java program to find all substrings of a string Java program to find substrings of a string: For example substrings of fun are: Java code to print substrings of a string is given below.

Empty string is considered to be substring of every string also known as NULL string. Java program to generate random numbers Java program to generate random numbers: This code generates random numbers in range 0 to both inclusive.

To generate random floats use nextFloat which returns float between 0. Java program to perform garbage collection This program performs garbage collection. Free memory in java virtual machine is printed and then garbage collection is done using gc method of RunTime class, freeMemory method returns amount of free memory in jvm, getRunTime method is used to get reference of current RunTime object.

Obviously the amount of available after garbage collection will be different on your computer. Numbers are not important, what is important is that amount of memory available is more than before. You can use this code in your program or projects which uses large amount of memory or where frequently new objects are created but are required for a short span of time. Java program to get ip address This program prints IP or internet protocol address of your computer system.

InetAddress class of java. Java has a very vast Networking API and can be used to develop network applications. Java program to reverse number This program prints reverse of a number i. You can also reverse or invert a number using recursion. You can use this code to check if a number is palindrome or not, if the reverse of an integer is equal to integer then its a palindrome number else not.

Java program to transpose matrix This java program find transpose of a matrix of any order. This code can be used to check if a matrix symmetric or not, just compare the matrix with its transpose if they are same then its symmetric otherwise non symmetric, also its useful for calculating orthogonality of a matrix.

Java program to multiply two matrices This java program multiply two matrices. Before multiplication matrices are checked whether they can be multiplied or not. This is a basic method of multiplication, there are more efficient algorithms available. Also this approach is not recommended for sparse matrices which contains a large number of elements as zero. Java program to open Notepad How to open Notepad through java program: Notepad is a text editor which comes with Windows operating system, It is used for creating and editing text files.

You may be developing java programs in it but you can also open it using your java code. How to open notepad using Java program. Download Notepad program. Explanation of code: You can also specify a file while opening notepad such as exec notepad programming.

You can launch other applications using exec method, for example exec calc will launch calculator application. If an application is present in a directory which is not set in environment variable PATH then you can specify complete path of application.

How to find a digit string from the given alphanumeric string. Matcher; import java. This would produce the following result: Found value: This order was placed for QT!

This order was placed for QT Found value: This example shows how we can search a word within a String object using indexOf method which returns a position index of a word within the string if found. Otherwise it returns The above code sample will Result: How to optimize string concatenation? The above code sample will produce the following result.

The result may vary. This example shows how to merge two arrays into a single array by the use of list. Addall array1. ArrayList; import java. Arrays; import java.

How to check if two arrays are equal or not? Following example shows how to use equals method of Arrays to check if two arrays are equal or not. How to use method overriding in Inheritance for subclasses?

This example demonstrates the way of method overriding by subclasses with different number and type of parameters. Is array 1 equal to array 2?? Inside area for figure. Area is: Following example shows how to implement stack by creating user defined push method for entering elements and pop method for retriving elements from the stack. How to implement Queue? Following example shows how to implement a queue in an employee structure. The employees name are: JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which java bytecode can be executed.

It is a specification. It physically exists. Many types: Class Method Area 2. Stack 4. Program Counter Register 5. Native Method Stack. It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term compiler refers to a translator from the instruction set of a Java virtual machine JVM to the instruction set of a specific CPU.

A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardwarebased. Java provides software-based platform. The Java platform differs from most other platforms in the sense that its a software-based platform that runs on top of other hardware-based platforms.

It has two components: Runtime Environment 2. The bytecode. Java is compiled to be a byte code which is the intermediate language between source code and machine code.

This byte code is not platform specific and hence can be fed to any platform. The classloader is a subsystem of JVM that is used to load classes and interfaces. There are many types of classloaders e. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc. Yes, save your java file by. The local variables are not initialized to any default value, neither primitives nor object references.

But they have been categorized in many sections such as constructor interview questions, static interview questions, Inheritance Interview questions, Abstraction interview question, Polymorphism interview questions etc. Object based programming languages follow all the features of OOPs except Inheritance.

The object references are all initialized to null in Java. Constructor is just like a method that is used to initialize the state of an object. It is invoked at the time of object creation.

The default constructor provides the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class. A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an instance of a class. Is used to initialize the static data member. It is executed before main method at the time of classloading. A method i.

Object is required to call instance methods. Inheritance is a mechanism in which one object acquires all the properties and behaviour of another object of another class. It represents IS-A relationship. It is used for Code Resusability and Method Overriding. To reduce the complexity and simplify the language, multiple inheritance is not supported in java in case of class. Aggregation represents weak relationship whereas composition represents strong relationship.

For example: Pointer is a variable that refers to the memory address. They are not used in java because they are unsafe unsecured and complex to understand. Because super or this must be the first statement. The object cloning is used to create the exact copy of an object. If a class have multiple methods by same name but different parameters, it is known as Method Overloading.

It increases the readability of the program. If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to provide the specific implementation of the method. It is because the static method is the part of class and it is bound with class whereas instance method is bound with object and static gets memory in class area and instance gets memory in heap.

Method Overriding 1 Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its super class.

Method overriding occurs in two classes that have IS-A relationship. In this case, parameter must be same. Yes, all functions in Java are virtual by default.

Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type. If you make any variable as final, you cannot change the value of final variable It will be constant. A final variable, not initalized at the time of declaration, is known as blank final variable.

Java Interview Questions 51 Can we intialize blank final variable? Yes, only in constructor if it is non- static. If it is static blank final variable, it can be initialized only in the static block. Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a super class.

The determination of the method to be called is based on the object being referred to by the reference variable. In case of static binding type of object is determined at compile time whereas in dynamic binding type of object is determined at runtime. Abstraction is a process of hiding the implementation details and showing only functionality to the user.

100 Java Programs With Output Useful Collection of Java Programs - Aniket Pataskar

Abstraction lets you focus on what the object does instead of how it does it. Abstraction hides the implementation details whereas encapsulation wraps code and data into a single unit.

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated. Interface is a blueprint of a class that have static constants and abstract methods.

It can be used to achieve fully abstraction and multiple inheritance. No, because methods of an interface is abstract by default, and static and abstract keywords cant be used together. An interface that have no data member and method is known as a marker interface. For example Serializable, Cloneable etc.

Abstract class Interface 1 An abstract class can have method body nonabstract methods. Interface have only abstract methods. An interface cannot have instance variables. Interface cannot have constructor. Interface cannot have static methods. You can implement multiple interfaces.

An object reference can be cast to an interface reference when the object implements the referenced interface. A package is a group of similar type of classes interfaces and sub-packages.

It provides access protection and removes naming collision. One can import the same package or same class multiple times. Neither compiler nor JVM complains about it.

But the JVM will internally load the class only once no matter how many times you import the same class. By static import, we can access the static members of a class directly, there is no to qualify it with the class name.

Exception Handling is a mechanism to handle runtime errors. It is mainly used to handle checked exceptions. The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e. Checked exceptions are checked at compile-time. The classes that extend RuntimeException are known as unchecked exceptions e. ArithmeticException,NullPointerExcept ion etc.

Unchecked exceptions are not checked at compiletime. It represents IS-A relationship. It is used for Code Resusability and Method Overriding. Object class.

For Celsius to Fahrenheit conversion

To reduce the complexity and simplify the language, multiple inheritance is not supported in java in case of class. Holding the reference of the other class within some other class is known as composition. Aggregation represents weak relationship whereas composition represents strong relationship. For example: bike has an indicator aggregation but bike has an engine compostion.

Pointer is a variable that refers to the memory address. They are not used in java because they are unsafe unsecured and complex to understand. It is a keyword that refers to the immediate parent class object.

Because super or this must be the first statement. The object cloning is used to create the exact copy of an object. If a class have multiple methods by same name but different parameters, it is known as Method Overloading. It increases the readability of the program. Yes, You can have many main methods in a class by overloading the main method. It is used for runtime polymorphism and to provide the specific implementation of the method.

No, you cant override the static method because they are the part of class not object. It is because the static method is the part of class and it is bound with class whereas instance method is bound with object and static gets memory in class area and instance gets memory in heap. Method Overriding 1 Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its super class.

Method overriding occurs in two classes that have IS-A relationship. In this case, parameter must be same. Yes, all functions in Java are virtual by default. Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type.

It is known as covariant return type. If you make any variable as final, you cannot change the value of final variable It will be constant. Final methods cant be overriden. Final class cant be inherited.

Search form

A final variable, not initalized at the time of declaration, is known as blank final variable. Java Interview Questions 51 Can we intialize blank final variable?

Yes, only in constructor if it is non- static. If it is static blank final variable, it can be initialized only in the static block. Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a super class.

The determination of the method to be called is based on the object being referred to by the reference variable. In case of static binding type of object is determined at compile time whereas in dynamic binding type of object is determined at runtime.

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Java programs

Abstraction lets you focus on what the object does instead of how it does it. Abstraction hides the implementation details whereas encapsulation wraps code and data into a single unit. A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.Armstrong number 7 4. But the JVM will internally load the class only once no matter how many times you import the same class.

To check if an integer say n is prime you can check if it is divisible by any integer from 2 to n-1 or check from 2 to sqrt n , first one is less efficient and will take more time. Following modified code handles the exception. This code can be used to check if a matrix symmetric or not, just compare the matrix with its transpose if they are same then its symmetric otherwise non symmetric, also its useful for calculating orthogonality of a matrix.

No, because abstract method needs to be overridden whereas you cant override final method. Empty string is considered to be substring of every string also known as NULL string. Yes, by try block.

DELFINA from Tampa
Look over my other articles. I'm keen on horseshoes. I do enjoy exploring ePub and PDF books curiously.
>