Archive

Category Archives for "java"
1

ArrayList example in java

What is ArrayList in java?

ArrayList is a class of java collection framework (a collection framework gives the architecture for manipulation and storage of group of object).Arraylist is basically a dynamic array. We  are not required to define it size, it can increase its size dynamically. It has the capability of direct access, i.e is with index we can access its elements, same as we deal with arrays. Arraylist are not efficient for add/removing elements as much of shifting is required. you may look for other type of data structure if you data is frequently changing, LinkedList may be helpfull in that case.

Arraylist example in java

ArrayList example in java

Lets have a look , on how to create and add items to the Arraylist data structure.

How to iterate the elements of collection in java?

we can iterate either using the Iterator inter face or by simply using for loop.

 


package arraylistapplication;

import java.util.ArrayList;
import java.util.Iterator;

public class CollectionAL {

public static void main(String [] args){

ArrayList<String> al = new ArrayList<>();
al.add("orange");
al.add("apple");
al.add("bannana");

Iterator it = al.iterator();
while(it.hasNext()){

System.out.println(it.next());

}
} }

 

Not only can ArrayList contain only primitive data types, or objects , it can also contain user defined objects . Now lets create our own class and then add that to the array list and display each object on the screen. This is the most useful usage of the array list that you will be using in more advance programming.

Creating student class


package arraylistapplication;

public class Students {

int stdId;
String name;

Students(int id, String stdName) {
this.stdId = id;
this.name = stdName;

}
}

Creating Array list for the students class.


package arraylistapplication;

import java.util.ArrayList;
import java.util.Iterator;

public class ArraylistStd {

public static void main(String[] args) {

Students std1 = new Students(001, "Khan");
Students std2 = new Students(002, "dada");

ArrayList<Students> al = new ArrayList<>();
al.add(std1);
al.add(std2);

Iterator it = al.iterator();

while(it.hasNext()){

Students stds = (Students)it.next();
System.out.println("Student Id :"+stds.stdId+" Student Name : "+stds.name);

}

}

}

 

JAVA INTERVIEW QUESTIONS

JAVA INTERVIEW QUESTIONS

1) What is OOP?

OOP stands for object oriented programming. It is programming paradigm in which programming is performed through objects.


2) What is platform?

Any software or hardware in which program run or executed is called platform.


3) What is JRE?

Java Runtime Environment (JRE) is the platform for JAVA.


4) What are features of JAVA?

Java is Object Oriented Programming, Simple, Secure, Platform independent, Multithreaded, Portable, Robust etc.


****************Very important java interview questions****************


5) How JAVA is secure?

Java has no explicit pointers like most of the Object Oriented programming languages. This feature make it secure.


6) How JAVA is Multithreaded?

Java supports Multi threads programming.


7) How JAVA is platform independent?

Java program can be run on many platforms such as windows , Linux, sun Solaris, MAC OS etc. This is because of bytecode. Every Java program converted in to bytecode and This bytecode can execute on multiple platforms.


8) What is bytecode?

Java program is converted by compiler into bytecode. This bytecode is platform independent which can run on multiple plarforms.


9) What is JVM?

JVM stands for Java Virtual Machine. It is JVM who runs / executes bytecode.


10) What are basic functions of JVM?

  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

11) What is JDK?

JDK stands for Java Development Kit.  It is JRE and development tools used for Java.


****************Very important java interview questions****************


12) What are the basic concepts of OOP?

The basic concept of OOP are

  1. Classes
  2. Objects
  3. Encapsulation
  4. Inheritance
  5. Polymorphism
  6. Abstraction

JAVA INTERVIEW QUESTIONS

13) How Java program is executed form Command Line?

Two steps are required to do this.

  • Compile program: javac Program_name.java
  • Execute program: java Program_name

****************Very important java interview questions****************


14) What is mean by visibility of class or method or variable?

Visibility means who can access that class , method or variable. Visibility is achieved by access modifier in Java. There are three types of access modifiers.

  • private
  • public
  • protected

15) What are Valid main method signatures.

  • public static void main(String[] args)
  • public static void main(String []args)
  • public static void main(String args[])
  • public static void main(String… args)
  • static public void main(String[] args)
  • public static final void main(String[] args)
  • final public static void main(String[] args)
  • final strictfp public static void main(String[] args)

16) What is compile time?

When Java program  is compiled into Bytecode by compiler. Prgram.class file created.


17) What is run time?

When Bytecode executes.


18) Can you save Java program by different file name?

Yes you can. But this you should compiler program by file name. But execute by Java class name.

  • javac file_name.java
  • java class_name

19) What is JIT?

JIT stands for just in time compiler. JIT compiles that parts bytecode which have similar functionalities. It reduces compilation time.


20) What is variable?

Variable is name of reserved area in memory.


21) What are types of variables in Java?

  • Instance variable :- also called class variable. Variable inside class.
  • Local variable :- variable inside method.
  • Static variable :- variable declared as a static. this make it history sensitive.

22) What are Datatypes in JAVA?

There are two types

  • Primitive datatypes: – int, char, double etc.
  • Non-primitive datatypes: – Array, objects, String etc.

23) What is object?

Any entity having state and behavior is object. For example human, pen, book etc. It may be physical or may be logical. Pen is having state and its behavior is writing.


24) What is class?

Class is collection of data and methods or collection of objects.


25) What is inheritance?

When object acquire properties and behavior of other objects, it is called inheritance. It provides code re-usability facility.


26) What is Polymorphism?

When single task performed by different ways. In java method overloading and overriding gives us polymorphism facility.


****************Very important java interview questions****************


27) What is Abstraction?

Abstraction is technique in which we hide the internal details of something and only showing the functionality.

In java abstract class and methods are used to achieve Abstraction.


****************Very important java interview questions****************


28) What is Encapsulation?

Encapsulation is the wrapping of data and code together. It is also called data hiding.


29) What is a Java naming convention?

It is the suggestions provided by Java for naming classes, interface, method or variables.

  • Class and Interface name should start with upper case letter i-e Button.
  • Method name should be camel case notation i-e yourMthod().
  • Variable name should consist of small letter i-e cgpa, current etc.
  • Constant name should be all upper case letters i-e PI, AGE etc.

30) What is new keyword in Java?

New keyword is used to allocate memory at runtime.


****************Very important java interview questions****************


31) What are the characteristics of Objects?

Objects have three characteristics.

  • State
  • Behavior
  • Identity

32) How object is created?

Class_name object_name = new Class_name();


****************Very important java interview questions****************


33) What is nameless or anonymous object in java?

new Class_name();    // this object has no name(identity).


34) In how many ways objects in java can be created?

In JAVA objects can be created by four methods.

  • By “new” keyword
  • By clone method
  • By factory method
  • By newInstance method

35) In how many ways a method in java can be overloaded?

There are two ways to overload method in JAVA.

  • By changing number of arguments
  • By changing datatype

36) Why method overloading is used in JAVA?

It increase readability of code.


37) What is constructor?

Constructor is methods having no explicit return type, name same as class name and automatically called whenever object is created.


38) What is default constructor?

A no argument constructor is called default constructor.


****************Very important java interview questions****************


39) Why default constructor is used?

Default constructor is used to initialized default values for objects. For example 0 and null etc.


40) Why static keyword is used in JAVA.

Static keyword in java is used for memory management.


****************Very important java interview questions****************


41) Where static keyword can be used in java?

Static keyword can be used with following

  • Variables :- static variable is shared between all objects of the class. Static fields get memory only once
  • Nested class
  • Methods :- can be called using class name. Creating objects for static method is not important. Static method is used to change values of static data
  • Block :- it executed before main method and used to initialized static data

42) Why main method in JAVA is static?

Because main method execute automatically without creating any instance or object for it to call. If it were not static JVM must used some instance to call main method.


 

43) What is usage of “this” keyword in JAVA?

There are several usage of “this” keyword in JAVA.

“this” keyword is a reference variable used to refers current objects.

“this” is used to call current class method and constructor.

For example:  this.methodName();

“this” can be used as argument as well as return type in methods.

For example:   this methodName(this);

“this” can be used to access current class instance variable.

For example:   this.variable_name = 90;


44) What is use of “extend” keyword in JAVA?

“extend” keyword is used for inheritance in JAVA.

class child_class extend parent_class {    //coding here }

inheritance in JAVA is “is a relation”. Means used when something is a type of some other thing.

For example teacher is an employee

It will code in JAVA like this.

class Teacher extends Employee  { }


45) Why multiple inheritance is not supported in classes?

To remove ambiguity problem or diamond problem, multiple inheritance is not supported in case of classes, But multiple inheritance is allowed in interfaces (will discuss later).

Class C is inherits from class A and B and both of its parent class having method by the name show(). So when we called show method through object of class C. What show() will be called by object. Whether A method or B method. So there is ambiguity. It has been removed in JAVA.

JAVA INTERVIEW QUESTIONS46) How we can call method with nameless/anonymous object?

new class_name().methodName();


47) What is aggregation in JAVA?

In JAVA when a class contains the object of some other class as member of class. Such property is called aggregation. Aggregation is “has a relation”.


48) When something is part of another thing, we have to use aggregation.

class Processor

{

}

class Computer

{

int no;

Processor  pro;

}


49) When we have to used inheritance and when aggregation?

If relation is only maintained throughout the life time of object use inheritance, otherwise aggregation is best choice to use.


50) Can we override static methods and why?

No, it is not possible to override static methods in JAVA, because static method is bound with class not with objects.


51) Can main method be overridden?

No, because main method is static. And static cannot be overridden.


******************JAVA INTERVIEW QUESTIONS*******************


52) What is scope of Java access modifiers?

Access Modifier Within class By child class Within package Outside package
Private Yes No No No
Protected Yes Yes Yes No
Public Yes Yes Yes Yes

Java final keyword usage

Java final keyword

Java final keyword is used in three different places in java. Java final keyword can be used with

  • Variable
  • Method
  • Class

Java final keyword with method

Java final keyword can be used with variable when you want to prevent changes in variable value. For example when you assign any value to variable, It can be changed if not final.


class Afridi{

int age=21;

void show()

{

age=22;

System.out.println("age = "+age);

}

public static void main(String args[]){

Afridi obj=new  Afridi();

obj.show();

}

}

final in java

 

In above program the value of age was 21. But the function change it to 22. Complier will not stop you. So without java final keyword the variable can be changed.

Now with java final keyword

java final

By using Java final keyword now complier will not allow you to change the variable value. It is the final value. Java final keyword is same is CONST keyword in C++ and other programming languages.

Java final keyword with method

By using java final keyword with method will not allow you to override that method. Following examples shows the concept of java final keyword.

Method override example


class Rafi

{

void show()

{

System.out.println("Rafi on trustingeeks.com");

}

}

public class Afridi extends Rafi

{

void show()

{

System.out.println("Afridi on trustingeeks.com");

}

public static void main(String[] args)

{

Afridi obj = new Afridi();

obj.show();

}

}

final in java

 

Method show() has been defined in parent class Rafi and also in child class Afridi. But show() in child class override parent class method.

Now consider following java program using java final keyword with method. It will not allow you to override final method.

final keyword

 

Java final keyword with class

By using java final keyword with class means that you cannot extends that class. Any class that has been declared final cannot be extends.

Following program show that how to use java final keyword with class.

final class

 

In above program class Rafi is final. And then I tried to extends another class Afridi. Complier did not allow me to do that. This is because of java final keyword with class.

Java final keyword with parameter

Parameter is the function arguments. When you declare parameters as final you cannot change the value of that arguments. It will use its own value. Follow program shows how to use java final keyword with parameters.


public class Afridi

{

void show(int a)

{

System.out.println(a+" Rafi on trustingeeks.com");

}

public static void main(String[] args)

{

Afridi obj = new Afridi();

obj.show(2);

}

}

final method

 

Now by using java final keyword with parameter will not allow any method to change its value. Parameter has int a and inside method I try to change value to a=1; Comiler gave error.

final variable


Trustingeeks facebook page
World of programmar

1

Arrays in Java

Arrays in Java

Array is  a container that can contain collection  of same elements. it is a datastructure that can store only a fixeed size of elements . arrays in java

Array contains values that are called elements, and the elements can be accessed by the numerical values called indexes. Array is stored in contigous memery location. Array is one of the most used datastructure in java.

Advantages of  Array in java

  • Used for Code Optimization: that is   one can retrieve and  sort the data easily.
  • Random access:Data is accessible through the index value randomly .

Disadvantages of  Array in Java

  • Size Limit: one of the disadvantage of array in java is that we can’t increase the size of the array dynamically , instead we have to define it at first .

There are two types of array.

  • Single Dimensional Array
  • Multidimensional Array

 

 

 

 

3

Java interview questions and answers

Java interview question and answers section will bring you some nice question and about Java , this will indeed help you to memorize the concept and help you to understand all the questions that you may face in interviews

Java interview questions and answers

 

What is object:

It is a repository of data. It mean place where data can be stored .

java interviews short questions and answers

What is class?

It is a type of object.

ShopingList, ShopingCarts, animals etc

What is Method:

Procedure or function that operates on object or class is called methods.

What is inheritance ?

A class can  inherit properties form a more  general  class.

For example: A class ShopingList inherits (property of storing the list of items)  from more general class List

What is polymorphism ?

One method call works on several classes even if the classes need different implementation of the same method.

What does object oriented mean?

In oop each object knows it own class and methods that is why we say object oriented language.

What is difference between variable and reference variable?

Variable Int a=10;

String str;

This declares a variable str, the class of which is String.

The java compiler creates Memory which is allocated for str variable.

The str is still avariable but we can create an object and assigned that to str variable as shown below

java interviews short questions and answers java interviews questions about string 

str =  new String();

this line of code does two things

the new string(); is called the constructor; that is it actually constructs a brand new string.

The “=” assignment operator causes str to reference the string object.

 

 Hope you have understood some thing out of the article under the name of java interview questions .

 

 

 

 

 

 

join method in Java Threads

A thread that uses join method, causes other running methods to stop , until the thread which has called join() methode has not finished the execution.
There are two types of join methods

  • public void join()throws InterruptedException
  • public void join(long milliseconds)throws InterruptedException

you can use any one of this constructor a/c to your need, or what sort of application you are building up.

Example of join method in Java Threads


class Test extends Thread{
public void run(){
for(int k=1;k<=5;i++){
try{
Thread.sleep(600);
}catch(Exception d){System.out.println(d);}
System.out.println(k);
}
}
public static void main(String args[]){
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}

t2.start();
t3.start();
}
}

Output for join method in JAVA threads:

[ideabox]
       1
       2
       3
       4
       5
       1
       1
       2
       2
       3
       3
       4
       4
       5
       5
[/ideabox]
1

Unicode System

Unicode System is universal international standard character encoding system that has the capability of representing almost all the world’s written languages.This means for each character of any language a unique numbers is allocated since computer fundamentally deals with numbers rather than characters.
Unicode is adopted by the world’s most leading companies such as Oracle, Sap, Apple, HP, Microsoft and many more.

Unicode system in java:

Before Unicode, there were many encoding system available for different languages.

  • ASCII stands for American Standard Code for Information Interchange. This was one of the most used system, and could encode most of the languages most importantly the English , but it has one problem that it was limited to 128 characters.
  • ISO 8859-1 this coding system was used for Western European Language.
  • KOI-8 used for Russian.

Problems Caused by these Systems:

  • The single code value would corresponds to different letters in a different language standards.
  • The languages with large character would have different encoding value length. Some characters with a small length would have a single byte; other would required two or more bytes.

Thus to solve the above problems Unicode system was introduced that holds the characters in two bytes, and covers all the languages in the world, now no matter what language is used, and no matter what platform is used we have on the system for all the languages.

Values over 100,000 characters can be found at the Unicode Consortium 

There for Java also uses Unicode, both Java and Unicode uses 2 byte for characters.

Basic Understanding and Nature of Java programming

 Nature of Java programming

As you learn programming with Java, always keep this idea in mind that everything is an object in java its there for called  Nature of Java programming

Diagramming  a Simple application:
As you design your application you will be placing your code inside class definitions and wrapping that code inside functions known as methods .
Let’s have a look at the simpleApp that is indeed a hello world example .

</b>
Package com.trustingeeks.java;
Public class SimpleApp {
Public static void main(String[] args){
System.out.println(“hello everybody!, this trustingeeks.com”);
}

You can diagram, your Java application using a syntax called UML (unified modelling language).

 Nature of Java programming

Basic Understanding and Nature of Java programming

This diagram shows that:

  • the name of the class is SimpleAPP
  • It has single method named main();
  • It returns nothing, or void.

Now from this example you may not get the idea that everything is object so let’s expand the idea a little bit to two classes.

 

Using classes and objects


Package com.trustingeeks.java;

Public class SimpleApp {

Public static void main(String[] args){

Welcomer  welcomer = new Welcome();

welcome.sayWelcome();

}

public class welcomer{

private String  welcome=”welcome to trustingeeks.com”;

public  sayWelcome (){

System.out.println(welcome);

}

}

}

Explanation:

The simpleApp is called the starting class, because it contains the main() method.

As the application starts up , the main() method is called and the code in that method creates the instance of another class called welcomer. Shift your attention down to welcomer class , it declares a variable called welcome outside of any method.

These variables are called instance variables or fields. In this case we have an instance variable that is of type string, value is “welcome to trustingeeks.ocm” and is private to the class. Which means can only be read by the code within that class.

When the function sayWelcome is called from the SimpleApp class, then function is responsible to output the string to the console/cmd prompt.

Welcomer (with w as capital is the class) and the welcome (with small w) is object. To call the method saywelcome we use the syntax.

Object_of_class.method_name()

Objects can have methods and properties.

Diagramming the application:

Here you can see the uml diagram of both the above classes.

Basic Understanding and Nature of Java programming

Basic Understanding and Nature of Java programming

 

Basic Understanding and Nature of Java programming

Basic Understanding and Nature of Java programming

Java Exception Handling

Java Exception Handling

Java exception handling is the proper mechanism through which runtime exception errors are handled. Hence forbidding the exception errors to change the normal execution flow of the java code or program. Suppose we want to take numerical value as an input from the user, but by mistake, the user enters a charter(A-Z) value  instead of numerical value, so what should the program do in this Condition, should the user not be notified to enter the correct value of integer type?
Of course yes!
asking the user  to enter  the number again, and notifying  to enter numerical value , is the real goal of  Java exception handling.

What is exception?

Well according to Wikipedia , exception is said to be an action which  is not part of usual/normal operation.
In the context of programming when an unusual action(exceptional event/error ) is performed at runtime by an application, exception is thrown, indicating that something wrong has happened, which has changed the normal flow of the execution, and may give unwanted results.

What is exception Handler?

Exceptional handler is the code, which handles the exception and maintain the normal flow of the program. This handling is achieved with help of try and catch blocks, the code where exception is expected, is contained in the try block and the catch block is used to call the specific exception handling code that handles that exception that exception.

Why do we need Java Exception Handling?

Whenever an exception occurs, the code below exception(the line of code where exception has occurred) is never executed and the program crashes,so to maintain the normal flow of the program we need to use the Java exception handling mechanism.

Suppose you have 1000 lines of code, and when you run your program, you get an exceptional error at line number 200, so the rest of the program will never be executed unless the exception is not handled properly.

Example without Java Exception Handling


public class exceptionHandlingDemo {
public static void main(String[] args) {
System.out.println("Trustingeeks.com Java exception Handling Starts!");
String[] countries ={"Pakistan"};
System.out.println(countries[2]);//this is where exception occurs
System.out.println("This is last line ");

}
}

Out put Java Exception Handling

Trustingeeks.com Java exception Handling Starts!

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2

at exceptionHandlingDemo.main(exceptionHandlingDemo.java:8)

as you can see in the output we do not get display the last line of the code, since exception has occurred so , the rest of the code will not execute .. now lets see another example of java exception handling.

Example with Java Exception Handling


public class exceptionHandlingDemo {

public static void main(String[] args) {

System.<i>out</i>.println("Trustingeeks.com Java exception Handling Starts!");

String[] countries ={"Pakistan"};

try {

System.<i>out</i>.println(countries[2]);

} catch (Exception e) {

System.<i>out</i>.println("exception handled !!");

}

System.<i>out</i>.println("Trustingeeks.com Java exception Handling Ends!");

}

}

Output with Java Exception handling

Trustingeeks.com Java exception Handling Starts!
exception handled !!
Trustingeeks.com Java exception Handling Ends!

Compile Time and Runtime Errors In Java

Compile Time and Runtime Errors In Java

There are two types of errors in Java

Compile time errors in java

Compile time errors  in java are those errors that occur in the syntax or in the structure of the java application.
These errors are underlined by eclipse or any other compiler you are using.
Suppose i want to declare a variable counter of int type

 int counter=100 

Here i missed to place semicolon at the end of the statement. This breaks the Java’s fundamental syntax rule, which says that all statements must have semicolon at end. So all the errors that , violates the syntax rules such as return types, ; (),}  or accessing the variables which is not in the scope, declaring two variables with same name etc are considered as syntax errors.
Lets look at another example of compile time errors in Java,
suppose we write the code as

 String  str; System.out.println(str); 

Again here we will get an error in  the above code, although we have written the code syntactically correct, but because here we have ignored the fundamental rule of Java, that is you cannot output string value without first initializing it. This is what we call error in the structure of the code or application.
Errors in Java that may seem syntactically correct but sill violates the rules of Java.

Runtime errors in Java

These are the errors by breaking some rules of Java, that cannot be caught by the compiler  , and when we run our program , our program is crashed and stopped .An Exception is thrown and the stack of calls is printed, showing different methods that were called, from our main methods  until this exception was occurred .
Lets look at one of the error that most often occurs, “ArrayIndexOutOfBoundException”

String[] str={“TrustInGeeks.com”};
System.out.println(str[1]);

Now looking at  this there is no syntax error , we will not see any error in the editor(compile time), but since we know that to display the first element of any string array we need to write index value of zero. Sring array str has no value at index position 1, so there is an error due to which our application will stop, and print the call stack , that is
ArrayIndexOutOfBoundException error occurred at following line. So these errors are identified at runtime ,called runtime errors.
Now the question arises that what shell we do when such errors may occur ?                                                          well we have to Handel these exception so that we can run our application properly.
Java provide the Try and catch mechanism to handle all such types of errors that may occur at runtime.

1 2 3