Monday, 22 August 2016

String Vs StringBuffer Vs StringBuilder in Java

String in Java has many characteristics like being immutable, thread safety, declared as final that sets it apart. But, being immutable also means that any modification to String object will result in a creation of new string even if you use operations like converting to lowercase, uppercase. Thus concatenation of many strings will result in creation of many objects making it less memory efficient in that case.

Enters StringBuffer which is mutable and has an append() method which can append to the original StringBuffer and doesn’t result in creation of many objects. StringBuffer is also thread safe but here thread safety comes from the fact that all of its methods are synchronized. This synchronization makes it a little slow.

Enters StringBuilder class which provides the same methods as StringBuffer but it is not thread safe. Which makes it faster, as it performs no synchronization.

In this post we’ll go through these difference among the String, StringBuffer and StringBuilder classes which is a very important String interview question too.

Difference among String, StringBuffer and StringBuilder

String StringBuffer StringBuilder
Creation Apart from creating strings using new operator, String object can also be created like primitive data types are created as example String str = "test"; When String is created this way it is stored in a common string pool. StringBuffer object can only be created using new operator. StringBuffer object is stored in Heap. StringBuilder object can only be created using new operator. StringBuilder object is stored in Heap.
Modifiability Once you create a String object the content of that string cannot be modified i.e. String objects are immutable. Here being immutable means whenever you perform any operation on string which alters its content a new string object is created which contains the modified string. Original string is left as it is. StringBuffer is a mutable(modifiable) sequence of characters. Thus in case of StringBuffer length and content of the sequence can be changed through certain method calls. StringBuilder is a mutable(modifiable) sequence of characters. Thus in case of StringBuilder length and content of the sequence can be changed through certain method calls.
Appending If you have to append a lot of strings it will take more memory. Since string is immutable so concatenation of strings will result in creation of a lot of intermediary strings. StringBuffer class is mutable so appending to it using append() method will not result in creation of intermediary objects. That way less memory is used. StringBuilder class is mutable so appending to it using append() method will not result in creation of intermediary objects. That way less memory is used.
Thread-safety As string objects are immutable so they are thread safe. StringBuffer is thread safe so String buffers are safe for use by multiple threads. Each method in StringBuffer is synchronized making it thread safe. StringBuilder is not thread-safe.
Performance String class is fast. All the methods in StringBuffer class are synchronized which makes it a little slow. If you don't have to bother about thread safety then use StringBuilder class as it supports all of the same operations as StringBuffer but it is faster, as it performs no synchronization.

That's all for this topic String Vs StringBuffer Vs StringBuilder in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. String charAt() and subString() methods in Java
  2. Searching within a String using indexOf(), lastIndexOf() and contains() methods
  3. Splitting a String using split() method in Java
  4. String join() method in Java 8
  5. Java String interview questions

You may also like -

>>>Go to Java Basics page

Friday, 19 August 2016

Switch-Case statement in Java

Switch case statement is Java's decision statement which can have a number of possible execution paths. It provides an easy and more readable way to execute a set of code based on the value of the expression.

General form of switch-case statement

switch (expression) {
 case value1:
  // statement
  break;
 case value2:
  // statement
  break;
 .
 .
 .
 case valueN :
  // statement
  break;
 default:
  // default statement
}

Switch works with byte,short, char, and int primitive data types and their wrapper classes Character,  Byte, Short, and Integer. Starting Java 7 it also works with String in Java.

Execution path of switch-case statement

When a value is passed in the switch expression it is compared with the value of each case statement, if match is found the code following that case statement is executed. Code execution with in the case statement is terminated when the break statement is encountered. As soon as the break statement is encountered no other case statement is executed and control comes out of the switch case statement.

If none of the values in the case statement matches the value of the expression then the default statement is executed. Note that default statement is not mandatory though. If none of the values in the case statement matches the value of the expression and default statement is also not there then control will come out of the switch-case statement executing nothing.

It is not mandatory to have break statement in every case statement, in case break statement is omitted in any case statement, next case statement will also be executed though it doesn't match the value of the expression. That can be used to group a set of case statements but omission due to negligence will result in execution of several case statements in place of a single matching one. See example for more clarity.

Also note that the type of each value must be compatible with the type of expression.

Switch-case statement example

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 7;
  switch(month){
   case 1: System.out.println("Month is January"); 
   break;
   case 2: System.out.println("Month is February"); 
   break;
   case 3: System.out.println("Month is March"); 
   break;
   case 4: System.out.println("Month is April"); 
   break;
   case 5: System.out.println("Month is May"); 
   break;
   case 6: System.out.println("Month is June"); 
   break;
   case 7: System.out.println("Month is July"); 
   break;
   case 8: System.out.println("Month is August"); 
   break;
   case 9: System.out.println("Month is September"); 
   break;
   case 10: System.out.println("Month is October"); 
   break;
   case 11: System.out.println("Month is November"); 
   break;
   case 12: System.out.println("Month is Decmber"); 
   break;
  }

 }

}

Output

Month is July

Here month expression has the value 7 so it will go to the case statement which has value 7 and execute the statements with in that case statement and then break out.

Note that default statement is not used this code.

Let us change this example to pass month as 13 and have a default statement to encounter such cases.

Java code

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 13;
  switch(month){
   case 1: System.out.println("Month is January"); 
   break;
   case 2: System.out.println("Month is February"); 
   break;
   case 3: System.out.println("Month is March"); 
   break;
   case 4: System.out.println("Month is April"); 
   break;
   case 5: System.out.println("Month is May"); 
   break;
   case 6: System.out.println("Month is June"); 
   break;
   case 7: System.out.println("Month is July"); 
   break;
   case 8: System.out.println("Month is August"); 
   break;
   case 9: System.out.println("Month is September"); 
   break;
   case 10: System.out.println("Month is October"); 
   break;
   case 11: System.out.println("Month is November"); 
   break;
   case 12: System.out.println("Month is Decmber"); 
   break;
   default: System.out.println("Invalid month value passed");
  }
 }
}

Output

Invalid month value passed

Example omitting break statement

As stated above break statement is not mandatory but it will result in execution of the next case statement.

Java code

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 7;
  
  switch(month){
   case 1: System.out.println("Month is January");
   
   case 2: System.out.println("Month is February"); 
   
   case 3: System.out.println("Month is March"); 
   
   case 4: System.out.println("Month is April"); 
   
   case 5: System.out.println("Month is May"); 
   
   case 6: System.out.println("Month is June"); 
   
   case 7: System.out.println("Month is July"); 
   
   case 8: System.out.println("Month is August"); 
   
   case 9: System.out.println("Month is September"); 
   
   case 10: System.out.println("Month is October"); 
   
   case 11: System.out.println("Month is November"); 
   
   case 12: System.out.println("Month is Decmber"); 
   
   default: System.out.println("Invalid month value passed");
  }

 }

}

Output

Month is July
Month is August
Month is September
Month is October
Month is November
Month is Decmber
Invalid month value passed

In the above switch case statement break is not used with any case statement. Since month passed is 7 so control will go to the case statement having value 7 and start executing the code with in that case statement but it won't know when to break so all the following case statements (even default) are executed.

Case statements can be grouped by omitting the break statement. As example if you want to display the quarter passed month falls into then you can group three case statements where break statement is used with only the last one in the group.

Java Code

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 5;
  
  switch(month){
   case 1: 
   
   case 2: 
   
   case 3: System.out.println("Quarter 1"); 
     break;
   
   case 4: 
   
   case 5:  
   
   case 6: System.out.println("Quarter 2"); 
     break;
   
   case 7:
   
   case 8:
   
   case 9: System.out.println("Quarter 3"); 
     break;
   
   case 10:  
   
   case 11: 
   
   case 12: System.out.println("Quarter 4"); 
      break;
   
   default: System.out.println("Invalid month value passed");
  }

 }

}

Output

Quarter 2

Using Strings in switch Statements

In Java SE 7 and later, you can use a  String object in the switch statement's expression.

 
public class StringSwitchDemo {

 public static void main(String[] args) {
  String dept = "Human Resources";
  String deptCd = null;
  switch(dept.toLowerCase()){
   case "account": 
    deptCd = "acct";
    break;
   case "human resources": 
    deptCd = "hr";
    break;
   case "administration":
    deptCd = "admin";
    break;
   default: System.out.println("Invalid deprtment");
  }
  
  System.out.println("Department - " + deptCd);
 }

}

Output

Department – hr

Nested switch statements

You can have nested switch-case statement with in the outer switch statement.

switch(month){
 case 1:
 switch(week){
  case 1: .....
         break;
  case 2 : ....

  ...
  ...
 }
 break;
}

Switch-case statement efficiency

If you have to make a choice between sequence of if-else stateemnt and switch-case statement opt for switch case as it will run faster.

Reason being when the Java compiler compiles a swith-case statement it will go through all the case statement values (which are constants) and make a jump table. The value on which the switch is being performed is used as an index into the jump table to directly go to that case statement. In the case of switch-case statemnt it can be done as compiler knows that case values are all of sane type and switch expression can only be used for equality test with case values.

Points to note

  1. Value of the case statement can only be a constant expression.
  2. Switch case statement can only be used for equality test. No other boolean expression like greater than, not equal to etc. can be used with switch statement.
  3. Duplicate case values are not allowed, each case statement should have a unique value.
  4. default statement is not mandatory.
  5. break statement is also not mandatory. Leaving break statement with in a case statement will result in the execution of the next case statement.
  6. From Java 7 string class can also be used with switch case.

That's all for this topic Switch-case statement in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. String in Java
  2. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Monday, 15 August 2016

String interview questions

  1. What is String in Java?

    In Java String class represents character strings which means; Strings in Java are objects and all strings are instances of the String class. Internally in String class Strings are stored as character array.

    Read more about String in Java here.

  2. In how many ways String object can be created?

    Since strings are objects so strings can of course be created using new operator. String class has more than 10 constructors to create Strings which ranges from taking nothing as parameter to taking char array, StringBuffer, StringBuilder, another String as argument.
    Another and more preferred way to create Strings is to assign String literal directly to a String reference as you will do for any primitive type. For every string literal Java will automatically constructs a String object.

    As example - String str = “abc”; 
    

    Read more about String in Java here.

  3. If String can be created using String str = “test” then String is a primitive data type.Yes/No?

    No. For every string literal Java automatically constructs a String object.


  4. What is String pool? Where is it created in memory?

    When String literals are created they are stored in a String pool and that is a common pool; which means if there are two strings literals having the same content then those string will share the space in the pool.
    When String object is created by assigning a string literal, pool will be checked to verify if there is any existing object with the same content if there is then that existing reference is used, no new object is created in that case. If no object is found with the same content then this new literal will be added in the pool.
    String pool is stored in the heap.

    Read more about String in Java here.

  5. What is immutable object? Is String object immutable?

    An immutable object is an object that would not be able to change its state after creation. Thus immutable object can only be in one state and that state can not be changed after creation of the object.
    Yes String object is immutable. Once you create a String object the content of that string cannot be modified.


  6. Why is String class immutable?

    Since Java maintains a string pool where String references are shared thus changing content of any of the String will also affect the other strings sharing the same references that’s one reason why string is immutable.


  7. Why is String class final in Java?

    Since String is immutable, whenever you perform any operation on string which alters its content a new string object is created containing the modified string. Which means all the methods of the String class that modify the content in any way return a new String object with the modified content.
    Now, What if you can override the method of the String class so that it modifies and return the original string reference itself? In that case all the other strings having the same data in the string pool will also get affected as the reference is shared for the String literals having the same content.
    To avoid these kind of scenarios String class is declared as final and it can’t be overridden.


  8. Which operator is overloaded for String?

    ‘+’ operator is overloaded in Java for String. It is used for concatenating two strings.


  9. How many objects will be created if two Strings are created this way?

    String s1 = “test”; 
    String s2 =  “test”;
    

    Since s1 and s2 are string literals and having the same content object reference will be shared by them in the string pool. Therefore only one object is created.


  10. How many objects will be created if two Strings are created this way?

    String s1 = “test”;
    String s2 =  new String(“test”);
    

    In this case string literal goes to string pool and s2 is another object created using new. So, in this case two objects are created even if content is same.


  11. How many objects will be created if two Strings are created this way?

    String s1 = new String(“test”);
    String s2 =  new String(“test”);
    

    Two separate objects are created.
    If you check it using the following code

    if(s1 == s2){
       System.out.println("s1 and s2 are same");
    }else{
       System.out.println("s1 and s2 are not same");
    }
    
    s1 and s2 are not same will be displayed.


  12. How many object will be created if Strings are created this way?

    String s1 = “test”;
    String s2 =  new String(“test”);
    String s3 = new String(“test”).intern();
    

    s1 will go to string pool, for s2 new object is created. S3, though created using new will still search in the string pool for any reference having the same content as intern() method is used. So two objects will be created.


  13. What is intern() method in String?

    Using intern() method you can still get string object from the pool (if it exists) even if new operator is used to create a string.
    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    Read more about String in Java here.

  14. Is String thread safe in Java?

    Yes string is thread safe in Java as String is immutable.

    Read more about String and thread safety in Java here.

  15. What is StringBuffer in Java?

    StringBuffer class is the companion class of String. StringBuffer is a mutable(modifiable) sequence of characters which is in contrast to String class which is an immutable sequence of characters. Thus in case of StringBuffer length and content of the sequence can be changed through certain method calls.
    Since StringBuffer is mutable a new String object is not created every time string is modified, which in turn results in less memory consumptions and not having lots of intermediate String object for garbage collection.

    Read more about StringBuffer in Java here.

  16. What is StringBuilder in Java?

    StringBuilder class (Added in Java 5),just like StringBuffer, is a mutable(modifiable) sequence of characters which is in contrast to String class which is an immutable sequence of characters. Thus in case of StringBuilder length and content of the sequence can be changed through certain method calls.

    Read more about StringBuilder in Java here.

  17. Differences among String, StringBuffer and StringBuilder in Java?

    String is immutable where as both StringBuffer and StringBuilder are mutable.
    String and StringBuffer are thread safe where as StringBuilder is not thread safe.

    Read more about String Vs StringBuffer Vs StringBuilder in Java here.

  18. Is StringBuffer class also immutable in Java?

    No, StringBuffer is not immutable.

    Read more about StringBuffer in Java here.

  19. Is StringBuffer class also final in Java?

    Yes, StringBuffer class is final in Java.


  20. Is StringBuffer class thread safe?

    Yes StringBuffer class is thread safe. Methods in StringBuffer class are synchronized.


  21. Is StringBuilder class thread safe?

    No StringBuilder class is not thread safe. That makes it faster than StringBuffer.


  22. Is StringBuilder class also final in Java?

    Yes StringBuilder class is final in Java.

    Read more about StringBuilder in Java here.

  23. How to compare two strings in Java?

    equals() method can be used for comparing two strings in Java. If you want to ignore case then you can use equalsIgnoreCase(String anotherString) method.
    There are also compareTo() and compareToIgnoreCase() methods for comparing two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.
    You can also use matches() method where you can pass a regular expression for matching strings.

    Read more about String comparison in Java here.

  24. What will happen if “==” operator is used to compare two strings in Java?

    “==” operator will compare the references of the strings not the content.

    String str1 = "abc";
    String str4 = new String("abc");
    
    Comparing these two strings using “==” operator
     if(str1 == str4)
    
    will return false as the references are different.


  25. How to get characters and substrings by index with in a String?

    You can get the character at a particular index within a string by invoking the charAt() accessor method.

    String str = "Example String";
    char resChar = str.charAt(3);
    
    Will give char ‘m’. If you want to get more than one consecutive character from a string, you can use the substring method. The substring method has two versions -
    • String substring(int beginIndex, int endIndex) - Returns a new string that is a substring of this string.
    • String substring(int beginIndex) - Returns a new string that is a substring of this string.

    Read more about String charAt() and subString() methods in Java here.
  26. How can you find characters or substrings within a string?

    To find characters or substrings with in a string indexOf() and lastIndexOf() methods can be used.
    You can also use contains() method
    public boolean contains(CharSequence s) - Returns true if and only if this string contains the specified sequence of char values. Otherwise it returns false.

    Read more about charAt() and subString() methods in Java here.
  27. How can you split a string in Java?

    String provides a split method in order to split the string into one or more substring based on the given  regular expression.
    As example If you have a string where one (or more) spaces are used and you want to split it around those spaces.

    String str1 = "split example    program";
    String[] strArray = str1.split("\\s+");
    

    Read more about Splitting a String using split() method in Java here.
  28. How can you join strings in Java?

    With Java 8 join() method has been added in the String class which makes it very easy to join the multiple strings.
    join method has two overloaded versions -

    • public static String join(CharSequence delimiter, CharSequence... elements) - Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
    • public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) – Here elements is an Iterable that will have its elements joined together and delimiter is a sequence of characters that is used to separate each of the elements in the resulting String.

    Read more about String join() method in Java 8 here.
  29. Can we use String in switch case statement?

    Yes from Java 7 string can be used in switch case statement.


Related Topics

  1. Java OOP interview questions
  2. Core Java basics interview questions
  3. Java Collections interview questions
  4. Java Multi-threading interview questions
  5. Java Concurrency interview questions
  6. Java Exception Handling interview questions

Tuesday, 9 August 2016

Java basics interview questions

  1. What are JVM, JRE and JDK?

    JVM

    JVM meaning Java Virtual Machine is an abstract layer between a Java program and the platform that Java Program is running on.
    JVM is platform dependent and different implementations of JVMs are available for specific platforms.

    JRE

    JRE meaning Java Runtime Environment provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language.

    JDK

    JDK meaning Java Development Kit is a superset of the JRE, and contains everything that is in the JRE, plus development tools such as the compilers and debuggers necessary for developing applets and applications.

    Read more about JVM, JRE and JDK here

  2. What is bytecode in Java or Why java is called platform independent?

    Java programs are both compiled and interpreted which means -
    When we do javac javaprogram, the java source code is compiled into a .class file which is actually a bytecode. The generated bytecode is portable and it's format is same across platforms.
    After compilation, the interpreter reads the generated byte code & transforms it according to the native platform.
    The compiled bytecode doesn't run on CPU directly, JVM sits in between and interpret the bytecode into readable machine language for the CPU. So Java program is platform independent but JVM is platform dependent and different implementations of JVMs are available for specific platforms.


  3. Java is pass by value or pass by reference?

    Java is pass by value for both primitive types as well as for objects.

    Read more about Java pass by value or pass by reference here

  4. What is package in Java?

    A package is a namespace that organizes a set of related classes and interfaces. Packages also help in  preventing naming conflicts.
    Packages also provide visibility control mechanism. You can define classes and class members inside a package that are not visible to the classes in other packages.

    Read more about Package in Java here

  5. What are access modifiers in Java?

    Access level modifiers are used to control the visibility of the class or the members of the class i.e. fields and methods.
    Types of Access Modifiers

    • private - private modifier specifies that the member can only be accessed in its own class.
    • default (or package-private) - If no specifier is used (which is known as default access) member is visible only within its own package.
    • protected - protected modifier specifies that the member can only be accessed within its own package and by a subclass of its class in another package.
    • public - public modifier specifies that member is visible to all classes everywhere.

    Read more about Access Modifiers here

  6. What all access modifiers can be used with a class?

    At the class level only two of the modifiers can be used, public or default.
    If a class is declared with the modifier public, that class is visible to all classes everywhere.
    If a class has no modifier (the default), it is visible only within its own package.

    Read more about Access Modifiers here

  7. What all access modifiers can be used with class fields?

    All the four types of access modifiers - public, protected, default, private can be used with variables declared in the class.

    • If a field is declared as public then it is visible to all classes in the same package or other packages.
    • If a fields is declared with no access specifier (default) then it can be accessed by any class in the same package.
    • If a field is defined as protected then it is accessible to any class in the same package or to any subclass (of the class where field is declared) in different package.
    • If a field is defined private then that field can only be accessed in its own class.


  8. What all access modifiers can be used with class methods?

    All the four types of access modifiers - public, protected, default, private can be used with methods of the class and access modifier for the methods work the same way as for the fields.


  9. What all access modifiers can be used with constructors?

    All the four types of access modifiers - public, protected, default, private can be used with constructors of the class.

    • In case constructor of the class is private then the object of that class can be created by that class only.
    • In case constructor is marked as protected then a subclass in different package can access the protected constructor.
    • If a constructor is declared with no access specifier (default) then it can be accessed by any class in the same package.
    • If a constructor is declared as public then it is visible to all classes in the same package or other packages.


  10. What is automatic numeric promotion in Java?

    In Java numeric promotion happens in case of primitive types when those primitives are used in an expression.
    As exp.

    byte a = 100;
    byte b = 50;
    int i = a * b;
    
    In the above code a * b will exceed the range of its byte operand (range of byte is -128 to 127). In these types of situations Java will automatically promote the byte, short or char to int when evaluating an expression.

    Read more about automatic numeric promotion here

  11. What is constructor?

    In Java there is a special method provided to initialize objects when they are created. This special method which is used for automatic initialization is called Constructor.
    Constructor has the same name as the class in which it is created and defined just like a method, that is, constructor's syntax is similar to a method

    Read more about constructor here.

  12. What is default constructor in Java?

    When a constructor is not explicitly defined for a class, then Java creates a default no-arg constructor for a class that is called default constructor.

    Read more about constructor here.

  13. What is Parameterized Constructor in Java?

    If we want our object's fields to be initialized with specific values, we can do it by adding parameters to the constructor.

    Read more about constructor here.

  14. What is constructor chaining in Java?

    In case when we have a hierarchy of classes (inheritance) the constructors of the classes are invoked in an order. That order is known as constructor chaining.
    For Exp - If class A is super-class and there is Class B which is subclass of A. In that case if a new instance of class B is created, order in which constructors of Class A and Class B are executed is from super-class to subclass.

    Read more about constructor chaining here.

  15. What is constructor overloading in Java?

    Like method overloading there is also an option to have multiple constructors within the same class where the constructors differ in number and/or types of parameters, that process is known as Constructor overloading.

    Read more about constructor overloading here.

  16. Are constructors from the super class inherited in the sub-class?

    No constructors are not inherited in Java.


  17. What is this in java?

    this in java is a reference to the current object on which the method or constructor was invoked. this can be used inside any method or constructor to refer to the current object.

    Read more about this here

  18. What is super in java?

    The super keyword in java is essentially a reference variable that can be used to refer to its immediate parent class.
    Usage of super -

    • Invoke the constructor of the super class.
    • Accessing the variables and methods of parent class.

    Read more about super here

  19. What is interface in Java?

    Interfaces help in achieving full abstraction in Java, as using interface, you can specify what a class should do, but how class does it is not specified.
    Interfaces look syntactically similar to classes, but they differ in many ways -

    • Interfaces don't have instance variables.
    • In interfaces methods are declared with out any body. They end with a semicolon.
    • Interface can't be instantiated.
    • Interfaces don't have constructors.
    • An interface is implemented by a class not extended.
    • An interface can extend multiple interfaces.

    Read more about interfaces here.

  20. Can an Interface be final?

    No, interface can't be final. The whole idea of having an interface is to inherit it and implement it. Having it as final means it can't be subclassed.

    Read more about interfaces here.

  21. Is it possible to declare an interface method static?

    Not before Java 8, from Java 8 it is possible to have interface static methods.

    Read more about interface here and interface static method here.

  22. What are interface default/defender methods?

    With the release of Java 8, it is now possible to add default method in interfaces. With the addition of default method to an interface, addition of new method, to even an interface will not break the pre-existing code.
    An interface default method is defined the same way a method will be defined in a class. One difference is that in interface default method is preceded by the keyword default
    As Exp.

    public interface MyInterface {
     int method1();
     // default method, providing default implementation
     default String displayGreeting(){
      return "Hello from MyInterface";
     }
    }
    

    Read more about interface default method here.

  23. Can an Interface implement another Interface?

    No, an interface can't implement another interface. Though, interface can extend another interface.

    Read more about extending interface here.

  24. Can an Interface extend another Interface?

    Yes,interface can extend another interface.

    Read more about extending interface here.

  25. Is it possible to have final method in an interface?

    No, whole idea of interface is to have abstract methods for which implementation is provided by the implementing classes. Making a method as final in interface will mean it can't be overridden which will mean implementing class can't provide an implementation for that mthod.

    Read more about interfaces here.

  26. Is it possible to define a class inside an interface?

    Yes.An interface can have an inner class. That class will be accessed by using interfaceName.ClassName.


  27. What is a nested interface?

    An interface or a class can have another interface. Such an interface is known as nested interface or a member interface.When a nested interface is used outside, it must be used as a fully qualified name i.e. must be qualified by the name of the class or interface of which it is a member.

    Read more about nested interface here.

  28. What is a marker interface?

    A marker interface is an interface that has no method declarations or fields in it. It is used as a tag to let the compiler know it needs to add some special behavior to the class implementing marker interface. That is why marker interface is also known as tag interface.

    Read more about marker interfaces here.

  29. What is an abstract class?

    An abstract class is a class that is declared using the abstract keyword. An abstract class may contain methods without any implementation, called abstract methods.

    Read more about abstract class here.

  30. Is it possible to have abstract method in a class that is not abstract?

    No. If there is even a single abstract method in a class that class has to be declared as abstract.

    Read more about abstract class here.

  31. Is it possible to instantiate an abstract class?

    No. An abstract class can not be instantiated on its own, but abstract class can be used to create object references.

    Read more about abstract class here.

  32. Is it possible to have an abstract class without any abstract method?

    Yes. Even if there are no abstract methods in a class that class can still be declared as abstract. That abstract class still can not be instantiated.

    Read more about abstract class here.

  33. Can you use abstract and final both with a method?

    No. The whole idea of having a abstract method in a class is that it would be implemented by the inheriting class. Whereas making a method final means it can't be overridden thus can't be provided implementation in inheriting class. So using both of them is not possible.

    Read more about abstract class here and about final here

  34. What are the differences between abstract class and interface?

    Abstract Class Interface
    Methods Abstract class can have both abstract and non-abstract methods. Interface can have abstract methods only.
    Note: From Java 8 interfaces can have default methods and static methods.
    Access Modifiers Abstract class methods can have public, protected, private and default modifier apart from abstarct methods. In interface methods are by default public abstract only.
    Variables Abstract class fields can be non-static or non-final. In interface all the fields are by default public, static, final.
    Implementation Abstract class may have some methods with implementation and some methods as abstract. In interface all the methods are by default abstract, where only method signature is provided. Note: From Java 8 interfaces can have default methods and static methods.
    Constructor Abstract class have a constructor, it may be user supplied or default in case no constructor is written by a user. Interface can't have a constructor.
    Multiple Inheritance Abstract class can extend at most one class and implement one or more interfaces. Interface can only extend one or more interfaces.
    Abstraction Abstract class can provide both partial or full abstraction. Interface provides full abstraction as no implementation is provided for any of the method.
    Extends/Implements Abstract class are extended by the sub-classes. Sub-classes need to provide implementation for all the abstract methods of the extended abstract class or be declared as abstract itself. Interface is implemented by a class and the implementing class needs to provide implementation for all the methods declared in an interface. If a class does not implement all the methods of interface then that class must be declared as abstract.
    Easy to evolve Abstract class was considered easy to evolve as abstract classes could add new methods and provide default implementation to those methods. Interface was not considered easy to evolve as, in the case of adding new method to an interface, all the implementing classes had to be changed to provide implementation for the new method. With Java 8 even interfaces can have default methods so that issue has been addresses.


  35. What is Static variable in Java?

    A variable declared as static is associated with the class rather than with any object. When objects of its class are created, copy of static variable is not created per object. All objects of the class share the same static variable.

    Read more about static keyword here.

  36. What is static method in Java?

    A static method is associated with the class rather than objects of the class. Static method can be called directly with the class name ClassName.static_method() rather than with the object of the class.

    Read more about static method here.

  37. What is static block in Java?

    A static block in a class is executed only once, when the class is first loaded, even before the main method.

    Example of static block

    public class StaticDemo {
    // static blank final variable
     static final int i;
     static int b;
    static {
      System.out.println("in static block");
      i = 5;
      b = i * 5;
      System.out.println("Values " + i + " " +  b);
     }
    }
    
    Read more about static block here.

  38. Can we have static variable inside a method?

    No. Since static variables belong to a class where as variables declared inside a method are local variables and belong to that method. So variables inside a method can be declared as final, but not static, public, protected or private.

    Read more about static keyword here.

  39. Why can't we access non-static variable from static method?
    OR
    Why non-static variable can not be accessed from main method in Java?

    Static methods or fields can be accessed without even creating an instance of the class, we just need to qualify the static member with the class name and access it. But non-static members need instance of the class to be created to come into existence. That is the reason why non-static field or method can not be called from the static context.

    Read more about Static reference to the non-static method or field error here.

  40. Can we overload static method?

    Static methods can be overloaded just as 'instance methods'. So it is possible to have two or more static methods having the same name, but the parameters are different in types or number.

    Read more about static overloading here.

  41. Can we override static method?

    Static methods can not be overridden in Java. Though it is possible to have a static method with same signature in sub-class but in that case sub-class method hides the super class method rather than overriding it.

    Read more about static method overriding here.

  42. Why main method is static in Java?

    When a class is loaded JVM needs an entry point (main method). JVM needs to access that main method with out creating an instance of the class, that is why main method is static.
    If it is not declared as static then instance of the main class has to be created which may cause ambiguity.

    public class A {
     private int i;
     A(int i){
      this.i = i;
     }
     public static void main(String args[]){
     }
    }
    

    Here in the class there is a constructor with one argument i. Now in order to create an object of the class what should be passed as i? To avoid these types of ambiguities it doesn't make sense for the JVM to have to create an object of the class before the entry point (main method) is called. That's why main method is static.

    Read more about Why main method is static here.

  43. What is static import in Java?

    In order to access any static member (static field or method) of the class, it is necessary to qualify references with the class they came from.
    As exp. - ClassName.static_method()

    With static import feature of Java 5, members defined in a class as public static can be used without qualifying it with the class name, in any Java class which does a static import. This shortens the syntax required to use a static member.

    Read more about static import in Java here.

  44. What is final in Java?

    final keyword in java has its usage in preventing the user from modifying a field, method or class.

    • final field - A variable declared as final prevents the content of that variable being modified.
    • final method - A method declared as final prevents the user from overriding that method.
    • final class - A class declared as final can not be extended thus prevents inheritance.

    Read more about final keyword here.

  45. What is a final blank variable?

    A final variable can be initialized only once but it can be done in two ways.

    • Value is assigned when the variable is declared.
    • Value is assigned with in a constructor.
    A final variable that has not been assigned a value while declaring a variable is called blank final variable, in that case it forces the constructor to initialize it.

    Read more about final keyword here.

  46. What if a list is declared as final, is it possible to add or remove values from that list?

    When an object reference variable is declared as final, object fields can still be changed but the reference can't be changed.
    So yes it is possible to add or remove values from the list even if the list is declared as final.

    But we can't change the reference of that list.
    As Exp.

    final List tempList = new Arraylist();
    tempList.add("1"); // permitted
    tempList = new ArrayList()// This will result in an error as we are trying to change the reference
    

  47. What is a final method?

    A method can be declared as final in order to avoid method overriding. Method declared as final in super class cannot be overridden in subclass.

    Read more about final method here.

  48. What is a final class?

    A class declared as final can't be extended thus avoiding inheritance altogether.
    If creator of the class is sure that the class has all the required functionality and should be used as it is with out extending it then it should be declared as final.

    Read more about final class here.

  49. What is covariant return type?

    Before Java 5, when you override a superclass method in a subclass the method signature had to be exactly same, i.e., the name, argument types and return type of the overriding method in the sub-class had to be exactly same as that of the super-class method.

    This is relaxed a bit in Java 5 in case of return type. The sub-class method's return type may be different from super-class method's return type but the return type of the subclass should be a subtype of return type of super class method. Which means, if method in the super-class has return type R1 and the overriding method in the subclass has return type R2 then R2 must be the subtype of R1. That is known as covariant return type.

    Read more about covariant return type here.

  50. What is strictfp in Java?

    strictfp is a keyword in Java that restricts floating-point calculations to ensure portability. Prior to JVM 1.2, floating-point calculations were strict; which meant, all intermediate floating-point results were represented as IEEE single or double precisions only. As a consequence, errors of calculation (round-off errors), overflows and underflows would occur with greater frequency than in architectures which did intermediate calculations in greater precision.

    Since JVM 1.2, intermediate computations are not limited to the standard 32 bit and 64 bit precisions. On platforms that can handle other representations e.g. 80-bit double extended on x86 or x86-64 platforms, those representations can be used, helping to prevent round-off errors and overflows, thereby increasing precision.

    Read more about strictfp in Java here.

Related Topics

  1. Java OOP interview questions
  2. Java String interview questions
  3. Java Exception Handling interview questions
  4. Java Multi-threading interview questions
  5. Java Collections interview questions
  6. Java Concurrency interview questions

Monday, 8 August 2016

Difference between Encapsulation and Abstraction in Java

Encapsulation and abstraction are two of the fundamental OOP concepts other two being polymorphism and inheritance.

Some times people do get confused between encapsulation and abstraction as both are hiding something. So in this post let's try to differentiate between these two concepts.

First let's try to define these two concepts to get some idea -
  • Encapsulation - Encapsulation means keeping together the implementation (code) and the data it manipulates (variables). Having proper encapsulation ensures that the code and data both are safe from misuse by outside entity. So, in a way Encapsulation is more about data hiding.
    It is a Java class which is the foundation of encapsulation in Java.

    Refer Encapsulation in Java to know more about encapsulation in Java.

  • Abstraction - Abstraction means hiding the complexity and only showing the essential features of the object. So in a way, abstraction means abstracting/hiding the real working and we, as a user, knowing only how to use.
    A very good example from Java would be - Java Database Connectivity (JDBC) API which provides universal data access from the Java programming language. Using the JDBC API, we can access virtually any data source without knowing how the driver for that particular data source is implemented. All we have is an API with a given set of methods. 
    PreparedStatement pstmt = conn.prepareStatement(SQL);
    

    While writing this line we don't bother how connection or prepareStatement is implemented in Oracle, SQLServer, DB2 or MySQL for us as a user those details are abstracted and we just know how to use JDBC API to interact with DBs. 

    Abstraction in Java is achieved through interface and abstract class.

      Refer Abstraction in Java to know more about abstraction in Java.

Hope you have got some idea now about these two terms, so let's see the differences between these terms.

Difference between Encapsulation and Abstraction

  1. Encapsulation is about keeping together the implementation and the data is manipulates. In a properly encapsulated Java class, method defines how member variables can be used. That access control to the methods and the variables is achieved through access modifiers (public, private, default & protected).
    Abstraction is about hiding the implementation and only giving the information about how to use it. Abstraction in Java is achieved through interfaces and abstract classes. 
  2. One of the benefit of Encapsulation is it helps in maintaining code that is changed frequently by keeping that in one place thus providing maintainability and flexibility. In fact that is one of the design principle Encapsulate what varies.
    Benefit of Abstraction is to provide a contract through interface or may be a bare skeletal implementation through Abstract class. Where as generalized implementations are provided based on that contract but user just sees the API.
      Any number of classes can implement an interface and each class is free to provide their own implementation. That's how using interfaces, Java fully utilizes "one interface, multiple methods" aspect of polymorphism. 

Let see an example for Encapsulation-

public class Employee {
    private String lastName;
    private String firstName;
    private String empId;
    private int age;
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getEmpId() {
        return empId;
    }
    public void setEmpId(String empId) {
        this.empId = empId;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    // method for getting full name
    public String getFullName(){
     return this.firstName + " " + this.lastName;
    }  
}
public class EmployeeTest {

 public static void main(String[] args) {
  Employee emp = new Employee();
  /*This line will give compiler error
  age field can't be used directly as it is private */
  // emp.age = 40;
     emp.setEmpId("E001");
     emp.setAge(40);
     emp.setFirstName("Ram");
     emp.setLastName("Chandra");
     System.out.println("Age- " + emp.getAge());
     System.out.println("Employee ID- " + emp.getEmpId());
     System.out.println("Full Name- " + emp.getFullName());

 }
}

Here we have a class called Employee and in the class there are public methods that provide access to the class’ fields (If you have noticed access modifier for all the fields is private). These methods for setting/getting the values of the fields are called setters and getters.

Any other class (in this example EmployeeTest) that wants to access the variables should access them through these getters and setters.
There is also one other method getFullName() in the same class which is using the fields of the class, that method can use the variables directly.

Let’s see an example for Abstraction -

Here we have an interface Ipayment with one method doPayment(). There are two implementing classes CashPayment and CreditCardPayment that provide implementation for cash payment and credit card payment respectively. But as a user all you need to know is that you have to call doPayment() method.

public interface IPayment {
 void doPayment(double amount);
}
public class CashPayment implements IPayment {

 @Override
 public void doPayment(double amount) {
  System.out.println("Cash payment " + amount);
  
 }
}
public class CreditCardPayment implements IPayment {

 @Override
 public void doPayment(double amount) {
  System.out.println("CreditCard payment " + amount);

 }

}
public class Payment {
 private static final String CASH = "CASH";
 private static final String CC = "CC";
 public static void main(String[] args) {
  Payment payment = new Payment();
  payment.executePayment(CASH, 34.45);
  payment.executePayment(CC, 34.45);
  

 }
 
 private void executePayment(String mode, double amount){
  IPayment payRef;
  // If payment is in CASH
  if(mode.equalsIgnoreCase(CASH)){
   payRef = new CashPayment();
   payRef.doPayment(amount);
   
  }
  // If payment is through credit card
  else if(mode.equalsIgnoreCase(CC)){
   payRef = new CreditCardPayment();
   payRef.doPayment(129.78);
  }
 }

}

In Payment class based on the mode of payment appropriate class is called. Of course there are better ways to do it using factory and encapsulating the logic in another class but here focus is more on knowing what is Abstraction.

That's all for this topic Difference between Encapsulation and Abstraction in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Association, Aggregation and Composition in Java
  2. Method overloading in Java
  3. Difference between abstract class and interface
  4. Access modifiers in Java
  5. Java OOP interview questions

You may also like -

>>>Go to Java Basics page

Thursday, 4 August 2016

Association, Aggregation and Composition in Java

When you model a system you can see that most of the classes collaborate with each other in many ways. In object-oriented modelling there are broadly three kind of relationships.

There are dependencies, there are generalizations and then there are associations. This post is about association and two types of associations – Aggregation and Composition. Many people get confused about these terms so I’ll try to define Association, Aggregation and composition, how they relate to each other and what are the differences among Association, Aggregation and Composition.

Association

An association is a structural relationship, in object oriented modelling, that specifies how objects are related to one another. This structural relationship can be shown in -

  • Class diagram associations
  • Use case diagram associations

An association may exist between objects of different types or between the objects of the same class. An association which connects two classes is called a binary association. If it connects more than two classes (not a very common scenario) it is called n-ary association.

An association in UML is drawn as a solid line connecting objects of different classes or two objects of same class.

If you want to show navigability then you can use arrow, at one end or at both end for bi-directional navigability.

Association Navigability
Association Navigability

Here B is navigable from A.

There are

four attributes of association

that you should know.

  1. Name – You use a name to describe the relationship with in the association. You can also give a direction to the name by using a triangle that points to the direction name should be read.
    association name
    Association Name
  2. Role – With in an association classes have specific role to play. You can explicitly state the role a class is playing in an association.
    As example – In the figure used above Factory is playing the role of employer where as worker is playing the role of employee.
  3. Multiplicity – In a structural relationship there may be zero, one or more objects connected with in an association. Multiplicity can be written as a range or as an explicit value. As example association end multiplicity can have one of the following values:
    • one (1): Indicates that exactly one entity type instance exists at the association end.
    • zero or one (0..1): Indicates that zero or one entity type instances exist at the association end.
    • One or more(1..*): Indicates that one or more entity type instances exist at the association end.
    association multiplicity
    Association Multiplicity
  4. Aggregation – Aggregation is a kind of association where you want to define whole/part kind of relationship. Since this post is about Aggregation and composition apart from association so let’s see aggregation in detail.

Aggregation

In a plain association classes are considered at the same level with one class having no more importance than the other. Sometimes you do need to define a “whole/part” relationship where one class (whole) consists of smaller classes (part). This kind of relationship is called aggregation. It is also known as a “has-a” relationship as object of the whole has objects of the part.

An aggregation in UML is drawn as an open diamond at the whole end.

Example

In the era of smart phones a very relevant example of the aggregation would be aggregating companies like Uber which is a Cab aggregator. Here Uber (company) is “whole” part and cab driver (Person) is “part”.

aggregation
Aggregation

Here note that cab driver can also be aggregated by other class, a cab driver registered with Uber can also be registered with Ola (another cab aggregating company). That is why aggregation is also known as shared association.

Also to emphasise; in aggregation if there are two classes, class A (whole) and class B (part) then class A doesn’t own class B. Therefore, when specific instance of class A ceases to exist (garbage collected) the instance of class B doesn’t go out of scope. Class B object can still exist.

Java code

If we have to show the aggregation in Java classes.

public class Company{
    private List<Person> cabDrivers;
    .............
    .............
}

public class Person{
    private String id;
    private String name;
    .........
    .........
}

Composition

As we have seen aggregation relationship makes a distinction between “whole” and “part” but doesn’t force an ownership and it also doesn’t link the “whole” and “part” object in such a way that if whole is destroyed, parts are also destroyed.

There is a variation of aggregation called composition which has strong ownership, thus the scope of the whole and part are related. In composition if there are two classes, class A (whole) and class B (part) then destruction of class A object will mean class B object will also cease to exist. Which also means class B object may be a part of class A object only.

Composition in UML is drawn as a filled diamond at the whole end.

Example

An example of composition would be a person whose body is composed of many body parts like hand, leg, eyes etc.

composition
Composition

Another example

Composition

Here School has one or more Departments and each department belongs to exactly one School. If school is closed all of its department will also close.

Java code

In Composition the containing object is responsible for the creation and life cycle of the contained object (either directly or indirectly). We can do it with constructor initialization in Java code. Let’s say we have two classes Vehicle and Engine and Engine object is contained with in Vehicle class.

Class Engine {
 private String engineNum;
 .................
 .................
}

Class Vehicle{
 private Engine engine;
 // constuctor
 Vehicle(){
   engine = new Engine();
 }
}

Here it can be seen that Engine class object is created and destroyed along with the Vehicle class object.

That's all for this topic Association, aggregation and composition in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Class in Java
  2. Object in Java
  3. Encapsulation in Java
  4. Polymorphism in Java
  5. Abstraction in Java

You may also like -

>>>Go to Java Basics page

Tuesday, 2 August 2016

String and thread-safety in Java

As we know that String objects are immutable. It is also true that immutable objects are thread-safe so by transitive law string objects are thread-safe. In this post let’s go a little deeper into this concept of String and thread safety in Java.

For that first let’s define Immutable object and thread safety -

Immutable object - An immutable object is an object that would not be able to change its state after creation. Thus immutable object can only be in one state and that state can not be changed after creation of the object.

Thread safety – I’ll quote “Java concurrency in practice” book here – A class is thread-safe if it behaves correctly when accessed from multiple threads, where correctness means that a class conforms to its specification.

String, being immutable, has the specification that the Strings are constant; their values cannot be changed after they are created. 

But there is a little confusion in many users when it comes to string and thread safety – many people think that string is immutable so thread safety here should mean even if multiple threads are working on the same string those threads should not be able to change the content of the string at all.

But threads can change the content main point here is in that case reference will also change. Whenever content of the String is changed, a new String is created and the reference is changed. Same thing will happen in case of multiple threads too.

Let’s try to see this with an example. In this example three threads are created and all of them share the same string object. In each of these thread, thread name is appended to the string and then that string is printed. Join() method is also used here to wait for all of the threads to finish and then the string object is printed again.

Example Code

public class StrThread implements Runnable {
    private String s;
    //Constructor
    public StrThread(String s){
        this.s = s;
    }
    @Override
    public void run() {
        System.out.println("in run method " + Thread.currentThread().getName());        
            
            try {
                // introducing some delay
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }    
            s = s + Thread.currentThread().getName();
            System.out.println("String " + s);
    }
    
    public static void main(String[] args) {
        String str = "abc";
        // Three threadss
        Thread t1 = new Thread(new StrThread(str));
        Thread t2 = new Thread(new StrThread(str));
        Thread t3 = new Thread(new StrThread(str));
        t1.start();
        t2.start();
        t3.start();
        // Waiting for all of them to finish
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {    
            e.printStackTrace();
        }
        System.out.println("String is " + str.toString());
    }
}

Output

in run method Thread-0
in run method Thread-1
in run method Thread-2
String abcThread-1
String abcThread-2
String abcThread-0
String is abc

Here note that every thread changes the content of the string but in the process where str refers to is also changed, so effectively each of the thread get their own string object. Once all the threads finish, str is printed in the main method again and it can be seen that the original string is printed meaning original reference with the original content remains intact.

To see what may happen with a mutable object let us use StringBuffer in the place of String.

Example code

public class StrThread implements Runnable {
    private StringBuffer s;
    //Constructor
    public StrThread(StringBuffer s){
        this.s = s;
    }
    @Override
    public void run() {
        System.out.println("in run method " + Thread.currentThread().getName());        
            
            try {
                // introducing some delay
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }    
            s.append(Thread.currentThread().getName());
            System.out.println("String " + s);
    }
    
    public static void main(String[] args) {
        StringBuffer str = new StringBuffer("abc");
        // Three threadss
        Thread t1 = new Thread(new StrThread(str));
        Thread t2 = new Thread(new StrThread(str));
        Thread t3 = new Thread(new StrThread(str));
        t1.start();
        t2.start();
        t3.start();
        // Waiting for all of them to finish
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {    
            e.printStackTrace();
        }
        System.out.println("String is " + str.toString());
    }
}

Output

in run method Thread-0
in run method Thread-1
in run method Thread-2
String abcThread-0
String abcThread-0Thread-2
String abcThread-0Thread-2Thread-1
String is abcThread-0Thread-2Thread-1

Note – output may vary in different runs

Here it can be seen that shared StringBuffer object is modified.

That's all for this topic String and thread-safety in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. String in Java
  2. String comparison in Java
  3. Splitting a String using split() method in Java
  4. Searching within a String using indexOf(), lastIndexOf() and contains() methods
  5. String join() method in Java 8
  6. Java String interview questions

You may also like -

>>>Go to Java Basics page