Write A Java Program To Initialize & Access 1-D Array? Public Class Arrayexample1 (

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

1. Write a java program to initialize & access 1-D array?

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]);  
        }  
   }
}  

2. Define & Explain File handling in java with program?

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.

// Importing File Class


import java.io.File;
  
class GFG {
    public static void main(String[] args)
    {
  
        // File name specified
        File obj = new File("myfile.txt");
          System.out.println("File Created!");
    }
}

3.Define Exception & Its Types?

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

4.Define Array & write its types

An array is a collection of similar types of data.

1]One-Dimensional Arrays:

The general form of a one-dimensional array declaration is :


type var-name[];
OR
type[] var-name;

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];

5.Define String & how to declare string in java

In Java, string is basically an object that represents sequence of char values


syntax:

<String_Type> <string_variable> = "<sequence_of_string>";

public class StringDecExample{


public static void main(String []args){
String str;
str="Hello World!";
System.out.println("String is: " + str);
}
}

6. Write the method of file handling?

S.No. Method Return Description


Type

1. canRead() Boolean The canRead() method is used to check


whether we can read the data of the file or not.

2. createNewFile() Boolean The createNewFile() method is used to create


a new empty file.
3. canWrite() Boolean The canWrite() method is used to check
whether we can write the data into the file or
not.

4. exists() Boolean The exists() method is used to check whether


the specified file is present or not.

5. delete() Boolean The delete() method is used to delete a file.

6. getName() String The getName() method is used to find the file


name.

7. getAbsolutePath( String The getAbsolutePath() method is used to get


) the absolute pathname of the file.

8. length() Long The length() method is used to get the size of


the file in bytes.

9. list() String[] The list() method is used to get an array of the


files available in the directory.

10. mkdir() Boolean The mkdir() method is used for creating a new


directory.

7. Write name of any two exception?

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

8. Which package used for file handling operation?


import java.io.File;
9. Write a Program for Operation on String (any 5 Operation)
class Main {
public static void main(String[] args) {

// create a string
String greet = "Hello! World";
String first = "Java ";

System.out.println("String: " + greet);

// get the length of greet


int length = greet.length();

System.out.println("Length: " + length);


String joinedString = greet.concat(first);

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

10. Define Try, Catch, finally block?

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

11. Define & Explain Tokenization of String with program?

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

Java File Class Methods 


The following table depicts several File Class methods:
Method Name Return Type

canRead() Boolean

canWrite() Boolean

createNewFile() Boolean

delete() Boolean
Method Name Return Type

exists() Boolean

length() Long

getName() String

list() String[] 

mkdir() Boolean

getAbsolutePath(
) String

Q13] Write a java s program using try, catch block?

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.

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is provided
in the A6 class.
1. interface printable{  
2. void print();  
3. }  
4. class A6 implements printable{  
5. public void print(){System.out.println("Hello");}  
6.   
7. public static void main(String args[]){  
8. A6 obj = new A6();  
9. obj.print();  
10.  }  
11. }  

Output:
Hello

Q15]What is a Java Exception and it’s Types?

Types of Exception in Java

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. 

Exceptions can be categorized into two ways:

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.

Q16] Explain about try, catch, statements with examples

Java try block

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 try block must be followed by either catch or finally block.

Java catch block

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. }  

Q17] Give the difference between checked and unchecked exceptions?



In this post, we will understand the difference between checked and unchecked exceptions in
Java.
Checked Exceptions
 They occur at compile time.
 The compiler checks for a checked exception.
 These exceptions can be handled at the compilation time.
 It is a sub-class of the exception class.
 The JVM requires that the exception be caught and handled.
 Example of Checked exception- ‘File Not Found Exception’
Unchecked Exceptions
 These exceptions occur at runtime.
 The compiler doesn’t check for these kinds of exceptions.
 These kinds of exceptions can’t be caught or handled during compilation time.
 This is because the exceptions are generated due to the mistakes in the program.
 These are not a part of the ‘Exception’ class since they are runtime exceptions.
 The JVM doesn’t require the exception to be caught and handled.
 Example of Unchecked Exceptions- ‘No Such Element Exception’

Q18] Define String? Explain different String declarations with an example

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.

Difference between String and StringBuffer


There are many differences between String and StringBuffer. A list of differences between String
and StringBuffer are given below:

No String StringBuffer
.

1) The String class is immutable. The StringBuffer class is mutable.

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.

4) String class is slower while StringBuffer class is faster while


performing concatenation performing concatenation operation.
operation.

5) String class uses String constant StringBuffer uses Heap memory


pool.
20. List and explain any five string methods.

All String Methods


The String class has a set of built-in methods that you can use on strings.

Method Description Return


Type

charAt() Returns the character at the specified index (position) char

codePointAt() Returns the Unicode of the character at the specified int


index

codePointBefore() Returns the Unicode of the character before the int


specified index

codePointCount() Returns the number of Unicode values found in a int


string.

compareTo() Compares two strings lexicographically int

compareToIgnoreCase() Compares two strings lexicographically, ignoring case int


differences

concat() Appends a string to the end of another string String

contains() Checks whether a string contains a sequence of boolean


characters

contentEquals() Checks whether a string contains the exact same boolean


sequence of characters of the specified CharSequence
or StringBuffer

copyValueOf() Returns a String that represents the characters of the String


character array

endsWith() Checks whether a string ends with the specified boolean


character(s)

equals() Compares two strings. Returns true if the strings are boolean
equal, and false if not

equalsIgnoreCase() Compares two strings, ignoring case considerations boolean

format() Returns a formatted string using the specified locale, String


format string, and arguments

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.

Classes does not support multiple


inheritance. Interface supports multiple inheritance.

It can be inherit another class. It cannot inherit a class.

It can be inherited by a class by using the


It can be inherited by another class using keyword ‘implements’ and it can be inherited
the keyword ‘extends’. by an interface using the keyword ‘extends’.

It can contain constructors. It cannot contain constructors.

It cannot contain abstract methods. It contains abstract methods only.

Variables and methods in a class can be


declared using any access specifier(public, All variables and methods in a interface are
private, default, protected) declared as public.

Variables in a class can be static, final or


neither. All variables are static and final.

You might also like