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.
|Language:||English, Arabic, Japanese|
|Genre:||Fiction & Literature|
|ePub File Size:||24.87 MB|
|PDF File Size:||15.45 MB|
|Distribution:||Free* [*Sign up for free]|
computerescue.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.
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.
For Celsius to Fahrenheit conversion
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 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. 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.
Java Programs With Output Useful Collection of Java Programs - Aniket Pataskar
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. It increases the readability of the program. Yes, You can have many main methods in a class by overloading the main method.
Java Programs With Output Useful Collection of Java Programs - Aniket Pataskar
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. 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. 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. The birth of oops concept took place with encapsulation. Any program contains two parts. Date part and Logic part Out of data and logic the highest priority we have given to data.
But in a structured programming language, the data insecurity is high. Thus in a process, if securing data in structured prog. Note: In structured programming lang programs, the global variable play a vital role. But because of these global variables, there is data insecurity in the structured programming lang programs. In this way data is unsecured.
But this is not the actual reason. Assume that it is a project.In main method we create object of two classes and call their methods. In case of static binding type of object is determined at compile time whereas in dynamic binding type of object is determined at runtime. They are not used in java because they are unsafe unsecured and complex to understand.
Abstraction is a process of hiding the implementation details and showing only functionality to the user. Class names in Java begin with a capital letter, and if there are more words in class then their first letter will also be capital. Have you noticed why we write static keyword when defining main its because program execution begins from main and no object has been created yet.
- TOGETHER WITH PHYSICS LAB MANUAL CLASS 12 PDF
- DE PROGRAMA PARA ABRIR DOCUMENTO EM PDF
- TEST DRIVEN DEVELOPMENT BY EXAMPLE PDF
- BEGINNING MOBILE APP DEVELOPMENT WITH REACT NATIVE PDF
- PLAY WITH GRAPHS ARIHANT PUBLICATION PDF
- HEAD FIRST JAVA PDF FILE
- WARRIORS BOOK SERIES