Professional Documents
Culture Documents
Write A Java Program To Initialize & Access 1-D Array? Public Class Arrayexample1 (
Write A Java Program To Initialize & Access 1-D Array? Public Class Arrayexample1 (
Write A Java Program To Initialize & Access 1-D Array? Public Class Arrayexample1 (
public class ArrayExample1 {
public static void main( String args[] ) {
//initializing array without passing values
int[] array = new int[5];
//print each element of the array
for (int i = 0; i < 5; i++)
{
System.out.println(array[i]);
}
}
}
File handling in Java implies reading from and writing data to a file. The File class from
the java.io package, allows us to work with different formats of files. In order to use the File
class, you need to create an object of the class and specify the filename or directory name.
In Java, exception is an event that occurs during the execution of a program and disrupts the
normal flow of the program's instructions. Bugs or errors that we don't want and restrict our
program's normal execution of code are referred to as exceptions. In this section, we will focus
on the types of exceptions in Java and the differences between the two.
1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
2. User-Defined Exceptions
1]One-Dimensional Arrays:
2]Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other arrays. These are also known as Jagged Arrays. A multidimensional array is
created by appending one set of square brackets ([]) per dimension.
Examples:
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10];
1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
1. Checked Exception
2. Unchecked Exception
3. Error
// create a string
String greet = "Hello! World";
String first = "Java ";
Char ch=greet.charAt(3);
System.out.println(ch);
String s=first.toLowerCase();
System.out.println(s);
String s2=first.toUpperCase();
System.out.println(s2);
}
}
Output:
12
Hello! World Java
l
java
JAVA
Java try and catch The try statement allows you to define a block of code to be tested for errors
while it is being executed. The catch statement allows you to define a block of code to be
executed, if an error occurs in the try block.
Java finally block is a block used to execute important code such as closing the connection, etc
Tokenization is the act of breaking up a sequence of strings into pieces such as words,
keywords, phrases, symbols and other elements called tokens. Tokens can be individual words,
phrases or even whole sentences. In the process of tokenization, some characters like
punctuation marks are discarded. The tokens become the input for another process like parsing
and text mining.
1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is Sergio"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
Output:
my
name
is
Sergio
Q]12. List the file handling Classes & file handling Method?
Methods of InputStream
S. No. Method
1. write()
2. write(byte[] array)
3. close()
flush()
4.
S No. Method
1 read()
read(byte[] array)
2 ()
3 mark()
4 available()
5 markSupported()
6 reset()
7 skips()
8 close()
Methods of OutputStream
canRead() Boolean
canWrite() Boolean
createNewFile() Boolean
delete() Boolean
Method Name Return Type
exists() Boolean
length() Long
getName() String
list() String[]
mkdir() Boolean
getAbsolutePath(
) String
1. public class TryCatchExample2 {
2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }
Q14] What is an interface? List the rules to create an interface in java with example
Interface in Java:-
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
Rules for Declaring Interface
There are some rules that need to be followed by Interface.
All interface Methods are implicitly public and abstract. Even if you use keyword it will
not create the problem as you can see in the second Method declaration. (Before Java 8)
Interfaces can declare only Constant. Instance variables are not allowed. This means all
variables inside the Interface must be public, static, final. Variables inside Interface
are implicitly public static final.
Interface Methods cannot be static. (Before Java 8)
Interface Methods cannot be final, strictfp or native.
The Interface can extend one or more other Interface. Note: The Interface can only
extend another interface.
Output:
Hello
In Java, exception is an event that occurs during the execution of a program and disrupts the
normal flow of the program's instructions. Bugs or errors that we don't want and restrict our
program's normal execution of code are referred to as exceptions.
1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
2. User-Defined Exceptions
Built-in Exception
Exceptions that are already available in Java libraries are referred to as built-in exception. These
exceptions are able to define the error situation so that we can understand the reason of getting
this error. It can be categorized into two broad categories, i.e., checked exceptions and
unchecked exception.
Checked Exception
Checked exceptions are called compile-time exceptions because these exceptions are checked
at compile-time by the compiler. The compiler ensures whether the programmer handles the
exception or not. The programmer should have to handle the exception; otherwise, the system
has shown a compilation error.
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
If an exception occurs at the particular statement in the try block, the rest of the block code will
not execute. So, it is recommended not to keep the code in try block that will not throw an
exception.
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.
1. public class TryCatchExample3 {
2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. // if exception occurs, the remaining statement will not exceute
8. System.out.println("rest of the code");
9. }
10. // handling the exception
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16. }
17.
18. }
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
Q19] Write the difference between String and String Buffer classes.
No String StringBuffer
.
2) String is slow and consumes more StringBuffer is fast and consumes less
memory when we concatenate too memory when we concatenate t strings.
many strings because every time it
creates new instance.
3) String class overrides the equals() StringBuffer class doesn't override the
method of Object class. So you can equals() method of Object class.
compare the contents of two
strings by equals() method.
equals() Compares two strings. Returns true if the strings are boolean
equal, and false if not
getBytes() Encodes this String into a sequence of bytes using the byte[]
named charset, storing the result into a new byte array
21. Differentiate between Classes and Interface?
Class Interface
The keyword used to create a class is The keyword used to create an interface is
“class” “interface”
A class can be instantiated i.e, objects of a An Interface cannot be instantiated i.e, objects
class can be created. cannot be created.