How to read a file in java with example program

  • We can read java file using buffered reader class in java
  • We need to import java.io.BufferedReader in order to read java text file.
  • Create object of java.io.BufferedReader class by passing new FileReader("C:\\Sample.txt") object to the constructor.
  • In order to read line by line call readLine() method of BufferedReader class which returns current line. Initially first line of java text file



 Program #1: Write a java program to read a file line by line using BufferedReader class

  1. package com.instanceofjava.javareadfile;

  2. import java.io.BufferedReader;
  3. import java.io.FileReader;
  4. import java.io.IOException;

  5. public class ReadFileBufferedReader {

  6. /**
  7. * @Website: www.instanceofjava.com
  8. * @category: How to read java read file line by line using buffered reader
  9. */

  10. public static void main(String[] args) {

  11. BufferedReader breader = null;

  12.  try {

  13. String CurrentLine;

  14. breader = new BufferedReader(new FileReader("E://Sample.txt"));

  15. while ((CurrentLine = breader.readLine()) != null) {
  16. System.out.println(CurrentLine);
  17. }

  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. } finally {
  21.     try {
  22. if (breader != null)
  23. breader.close();
  24.      } catch (IOException ex) {
  25. ex.printStackTrace();
  26.      }
  27. }

  28. }

  29. }

 Output:
 
  1. Java open and read file
  2. Read file line by line in java
  3. Example java program to read a file line by line
  4. java read file line by line example
  
Program #2: Write a java program to read a file line by line using BufferedReader class using Eclipse

how to read a file in java

Can an abstract class have a constructor in Java

  • Yes we can define a constructor in abstract class in java.

  • Then next question will come like when we can not create object of abstract class then why to define constructor for abstract class.
  • It is not possible to create object of abstract class directly but we can create object of abstract class from sub class which is actually extending abstract class.
  • When we define a abstract class a class must extend that abstract class then only there will be use of that class
  • Then when we create object of class which extends abstract class constructor of sub class will be called from that abstract class constructor will be called and memory will be created for all non static members.
  • If we are not defining any constructor default constructor will be executed.
  • So we can define any number of constructor in abstract class.
  • And it is recommended to define constructor as protected. Because there is only one scenario which we can create object is from subclass so define abstract class constructor as protected always.

Order of  execution of  constructor in Abstract class and  its sub class.

  •  When we  create object of  class which is extending abstract class then it will call abstract class constructor through sub class constructor.
  • Lest see a java example program on abstract class constructor in java

Program #1: Does abstract class have constructor???

  1. package com.instanceofjava.abstractclassconstructor;
  2. public  abstract class AbstractDemo {
  3.  
  4. AbstractDemo(){
  5.         System.out.println("No argument constructor of abstract class");
  6.  }
  7.  
  8. }


  1. package com.instanceofjava.abstractclassconstructor;
  2. public class Test extends AbstractDemo{
  3.  
  4.     Test(){
  5.         System.out.println("Test class constructor");
  6.     }
  7.     
  8. public static void main(String[] args) {
  9.         Test obj = new Test();
  10.        
  11.  
  12. }
  13.  
  14. }


Output: 

  1. No argument constructor of abstract class
  2. Test class constructor

Can we define parameterized constructor in abstract class?

  • Yes we can define parameterized constructor in abstract class.
  • But we need to make sure that the class which is extending abstract class have a constructor and it should call super class parameterized constructor
  • We can call super class parameterized constructor in sub class by using super() call
  • For example: Super(2) ;
  • What will happen if we are not placing super call in sub class constructor?
  • Compiler time error will come.

Program #2: Can we define parameterized constructor in abstract class in java?

  1. package com.instanceofjava.abstractclassconstructor;
  2. public abstract class AbstractDemo {
  3.  
  4. AbstractDemo( int x){
  5.          System.out.println("No argument constructor of abstract class x="+x);
  6.  }
  7.  
  8. }


  1. package com.instanceofjava.abstractclassconstructor;
  2. public class Test extends AbstractDemo{
  3.  
  4.     Test(){
  5.         super(10);
  6.         System.out.println("Test class constructor");
  7.     }
  8.     
  9. public static void main(String[] args) {
  10.         Test obj = new Test();
  11.        
  12.  
  13. }
  14.  
  15. }


Output:
 
  1. No argument constructor of abstract class  x=10
  2. Test class constructor

Program #3: What will happen if we are not placing super call in sub class constructor?


does abstract class have constructor in java

How to generate unique random numbers in java

  • In java we can generate random number in two ways 
  • By using Random class
  • By using Math.random



Program #1:  Java Example program to generate random numbers using random class within  the range of 1 to 10

  • First we need to create object of java.util.Random class.
  • After creating object of java.util.Random class then we need call nextInt() method by passing range
  • int range = maximum - minimum + 1;
  • int randomNum =  rn.nextInt(range) + minimum;

  1. package com.randomnumbergenerator;

  2. import java.util.Random;
  3. import java.util.Scanner;

  4. public class RandomNumber {

  5. /**
  6. * @Website: www.instanceofjava.com
  7. * @category: how to generate random numbers in java within range
  8. */
  9. public static void main(String[] args) {
  10. Scanner in = new Scanner(System.in);
  11. System.out.println("Enter minimum number");
  12. int minimum=in.nextInt();
  13. System.out.println("Enter maximum number");
  14. int maximum=in.nextInt();
  15. Random rn = new Random();
  16. int range = maximum - minimum + 1;
  17. int randomNum =  rn.nextInt(range) + minimum;
  18. System.out.println("Random Number= "+randomNum);

  19. }

  20. }

Output:

  1. Enter minimum number
  2. 1
  3. Enter maximum number
  4. 10
  5. Random Number= 4


Program #2:  Java Example program to generate random numbers using Math.random  within  the range of 1 to 10

  • By using Math.random() method also we can generate random number in java
  • int randomNum = minimum + (int)(Math.random() * maximum);

  1. package com.randomnumbergenerator;

  2. import java.util.Random;
  3. import java.util.Scanner;

  4. public class RandomNumber {

  5. /**
  6. * @Website: www.instanceofjava.com
  7. * @category: how to generate random numbers in java within range
  8. */
  9. public static void main(String[] args) {
  10. Scanner in = new Scanner(System.in);
  11. System.out.println("Enter minimum number");
  12. int minimum=in.nextInt();
  13. System.out.println("Enter maximum number");
  14. int maximum=in.nextInt();
  15.   
  16.   int randomNum = minimum + (int)(Math.random() * maximum);
  17. System.out.println("Random Number= "+randomNum);

  18. }

  19. }

Output:

  1. Enter minimum number
  2. 1
  3. Enter maximum number
  4. 10
  5. Random Number=5


Program #3:  Java Example program to generate 10 random numbers using Random class  within  the range of 1 to 100 using for loop.

  1. package com.randomnumbergenerator;

  2. import java.util.Random;
  3. import java.util.Scanner;

  4. public class RandomNumber {

  5. /**
  6. * @Website: www.instanceofjava.com
  7. * @category: how to generate random numbers in java within range
  8. */
  9. public static void main(String[] args) {
  10. Random randomNumGenerator = new Random();
  11.  
  12.            for (int idx = 1; idx <= 10; ++idx){
  13.               int randomInt = randomNumGenerator.nextInt(100);
  14.               System.out.println("Random Number= "+randomInt);
  15.  
  16. }       

  17. }

  18. }

Output:

  1. Random Number= 17
  2. Random Number= 3
  3. Random Number= 74
  4. Random Number= 59
  5. Random Number= 81
  6. Random Number= 90
  7. Random Number= 2
  8. Random Number= 32
  9. Random Number= 11
  10. Random Number= 75


random number generator java




How to generate random numbers in java without repetitions

  • lets see how to generate unique random numbers in java
  • By using Collections.shuffle();


Program #4:  Java Example program to generate 4 random numbers using Random class  within  the range of 1 to 100 without duplicate / java generate unique random number between 1 and 100


  1. package com.randomnumbergenerator;


  2. public class RandomNumber {

  3. /**
  4. * @Website: www.instanceofjava.com
  5. * @category: how to generate random numbers in java within range
  6. */
  7. public static void main(String[] args) {
  8.   ArrayList<Integer> list = new ArrayList<Integer>();
  9.             for (int i=1; i<10; i++) {
  10.                 list.add(new Integer(i));
  11.             }
  12.             Collections.shuffle(list);
  13.             for (int i=0; i<4; i++) {
  14.                 System.out.println("Random Number= "+(list.get(i)));
  15.             }
  16. }       

  17. }

  18. }

Output:

  1. Random Number= 7
  2. Random Number= 3
  3. Random Number= 2
  4. Random Number= 9

Program #5:  Java Example program to generate 10 random numbers. random number generator that doesn't repeat java

  1. package com.randomnumbergenerator;


  2. public class RandomNumber {

  3. /**
  4. * @Website: www.instanceofjava.com
  5. * @category: how to generate 10 random numbers in java within range
  6. */
  7.  
  8. public static final int SET_SIZE_REQUIRED = 10;
  9.  public static final int NUMBER_RANGE = 100;
  10.  
  11.  public static void main(String[] args) {
  12.  
  13.             Random random = new Random();
  14.  
  15.             Set set = new HashSet<Integer>(SET_SIZE_REQUIRED);
  16.  
  17.             while(set.size()< SET_SIZE_REQUIRED) {
  18.                 while (set.add(random.nextInt(NUMBER_RANGE)) != true)
  19.                     ;
  20.             }
  21.             assert set.size() == SET_SIZE_REQUIRED;
  22.             System.out.println(set);
  23.         }
  24. }


Output:

  1. [48, 99, 24, 58, 44, 77, 14, 95, 31, 79]

How to assign multiple classes to one html element

  • In HTML if we want to apply any styles to any elements we will use cascading style sheets.
  • By using CSS we can apply styles to an element in HTML
  • If some style is needed for more than one type of element then we cant make a style and name it and where ever that style is required we can place that style for that element.

  • So like this it is always possible to apply multiple styles or multiple classes to HTML elements.
  • We can specify more than one CSS class to an element.
  • By using class attribute we can specify multiple  CSS classes to a single element and all classes must be separated by a space.
  • For example if we are applying multiple classes to a div tag.
  • <div class="class1 class2"></div>
  • Here class is the attribute and class1 and class2 are the two different CSS classes.
  • Lets take an example of one paragraph element and two css classes 
  • Fist we define a <p> element with no styles.
  • Second one more <p> element with one style
  • Third one more <p> element with two styles.  
  • HTML multiple classes

 

#1: Html example file to show how to assign multiple CSS classes to an HTML element :

 

  1. <!DOCTYPE html>
  2. <html>
  3.  
  4. <title>Cascading Style Sheet</title>
  5.  
  6. <style type="text/css">
  7.  
  8. .class1 {  
  9. text-align: center;
  10. color: red; 
  11. }
  12.  
  13. .class2 { font-size: 300%; }
  14.  
  15. </style>
  16. </head>
  17. <body>
  18. <p >   How to assign multiple classes to html element<p>
  19. <p class="class1">How to assign multiple classes to html element<p>
  20. <p class="class1 class2">How to assign multiple classes to html element<p>
  21.  
  22. </body>
  23. </html>


html multiple classes

Builder design pattern in java with example program

  • Design patterns are solutions to software design problems.
  • Design patterns classified into three types.
  • Creational, Structural and behavioral design patterns.

  • Creational patterns helps us to create objects in a manner suitable to the given situation.
  • Builder design pattern is one of the creational  design pattern in java.
  • Builder  design pattern helps us to create complex class object.
  • Builder design pattern helps us to separate the construction process of a complex object from its representation so that same object construction process can be created in different representations.
  • Means it will separate complex construction into two parts  initialization of class instance and return  class instance.
  • When a class having more number of fields and constructor of that class take care of assigning initial values. 
  • And when we want to create object of the class we need to pass all  parameters and should be in same order which constructor is accepting.
  • Builder design pattern helps us to create same class object by passing required number of fields by using separate builder class object.
  • Builder design pattern is useful when object creation is very complex.

Advantages of builder design pattern:

  • Builder design pattern simplifies complex object creation.
  • Builder design pattern provides separation between instance creation and representation
  • Re usability

 Program #1: Builder design pattern in java with example program

Employee:
  1. package com.designpatternsinjava.builderdesignpattern;

  2. public class Employee {

  3. String name;
  4. String company;
  5. int id;
  6. String passport_number;
  7. String temp_address;
  8. String perm_address;
  9. int salary;

  10. Employee(String name,String company,int id,String passport_number,String
  11. temp_address,String perm_address,int salary){
  12. this.name=name;
  13. this.company=company;
  14. this.id=id;
  15. this.passport_number=passport_number;
  16. this.temp_address=temp_address;
  17. this.perm_address=perm_address;
  18. this.salary=salary;
  19. }

  20. public String toString(){
  21.  return "Name="+name+" \n Company="+company+"\n id="+id+"\n
  22.    passport_number="+passport_number+"" +"\n temp_address="+temp_address+"\n
  23.    perm_address"+perm_address+"\n
  24.    salary="+salary;

  25. }
  26. }

EmployeeBuilder

  1. package com.designpatternsinjava.builderdesignpattern;

  2. public class EmployeeBuilder {


  3. String name;
  4. String company;
  5. int id;
  6. String passport_number;
  7. String temp_address;
  8. String perm_address;
  9. int salary;
  10. public EmployeeBuilder setName(String name) {
  11. this.name = name;
  12. return this;
  13. }

  14. public EmployeeBuilder setCompany(String company) {
  15. this.company = company;
  16. return this;
  17. }

  18. public EmployeeBuilder setId(int id) {
  19. this.id = id;
  20. return this;
  21. }

  22. public EmployeeBuilder setPassport_number(String passport_number) {
  23. this.passport_number = passport_number;
  24. return this;
  25. }

  26. public EmployeeBuilder setTemp_address(String temp_address) {
  27. this.temp_address = temp_address;
  28. return this;
  29. }

  30. public EmployeeBuilder setPerm_address(String perm_address) {
  31. this.perm_address = perm_address;
  32. return this;
  33. }

  34. public EmployeeBuilder setSalary(int salary) {
  35. this.salary = salary;
  36. return this;
  37. }
  38. public Employee build(){
  39. return new Employee(name, company, id, passport_number, temp_address,
  40. perm_address, salary);
  41. }

  42. }

BuilderDemo


builder design pattern java code

  • To create object of employee class  we need to provide all the fields values to the constructor.
  • So it is somewhat difficult to pass all values all times.
  • Employee builder class taken all variables of Employee and in setter methods accepts a value and returns EmployeBuilder object.
  • And EmployeBuilder class has build method which will  assign all values to employee and returns Employee object.
  • Employee empobj= new EmployeeBuilder().setName("Saidesh").setId(1234).build();
  • Now we create object of Employee class by creating EmployeBuilder class object and caling calling setter methods whatever we have.
  • Is is very easy to set the values because we have corresponding setter method name is same as variable name.
  • After setting the values we need  to call build method so that it will return employee object with values.

Static method vs final static method in java with example programs

  • Static methods are class level so there are not part of object.
  • So we can not override static methods but we can call super class static method using subclass name or instance also.
  • If we are trying to override static methods in sub class from super class then it will be method hiding not method overriding.

  • Means whenever we call the static method on super class will call super class static method and if we are calling method using sub class it will call sub class method.
  • So it is clear that static methods are hidden not overridden and they are part of class means class level not object level.
  • Now the question is can a method be static and final together?
  • For non static methods if we declare it as final then we are preventing that method from overriding so it can not be overridden in sub class.
  • When we declare static method as final its prevents from method hiding.
  • When we declare final static method and override in sub class then compiler shows an error
  • Compile time error: Cannot override the final method from Super
  • Lets see an example program to understand this better.

Static methods in java

Program #1: Java example program to explain about static method in java

  1. package inheritanceInterviewPrograms;
  2. /*
  3.  * @website: www.instanceofjava.com
  4.  * @category: Deference between staic and final static methods in java
  5.  */


  6. public class Super {
  7.   
  8.  
  9.  static void method(){
  10.  
  11. System.out.println("Super class method");
  12.  }

  13. }

  1. package inheritanceInterviewPrograms;

  2. //  www.instanceofjava.com 

  3. public class Sub extends Super {
  4. static void method(){
  5.  
  6. System.out.println("Sub class method");

  7. }

  8. public static void main (String args[]) {
  9. Super.method();
  10. Sub.method();
  11.  
  12.  
  13. }
  14. }

Output:

  1. Super class method
  2. Sub class method

  • When we override static methods its not overriding it is method hiding and whenever we call method on class name it will call corresponding class method.
  • If we call methods using objects it will call same methods.

Program #2: Java example program to explain about calling super class static method using sub class in java

  1. package inheritanceInterviewPrograms;
  2. /*
  3.  * @website: www.instanceofjava.com
  4.  * @category: Deference between staic and final static methods in java
  5.  */


  6. public class Super {
  7.   
  8.  
  9.  static void method(){
  10.  
  11. System.out.println("Super class method");
  12.  }

  13. }


  1. package inheritanceInterviewPrograms;

  2. //  www.instanceofjava.com 

  3. public class Sub extends Super {
  4. public static void main (String args[]) {
  5. Super.method();
  6. Sub.method();
  7.  
  8.  
  9. }
  10. }

Output:

  1. Super class method
  2. Super class method

  • We can call super class static methods using sub class object or sub class name also.
  • Now lets see what will happen in final static methods

Final static methods in java:

  • Can a method be static and final together in java?
  • When we declare a method as final we can not override that method in sub class.
  • In the same way when we declare a static method as final we can not hide it in sub class means we can not create same method in sub class. 
  • If we try to create same static method in sub class compiler will throw an error.
  • Lets see a java example program on final static methods in inheritance.

Program #3: Java example program to explain about final static method in java

  1. package inheritanceInterviewPrograms;
  2. /*
  3.  * @website: www.instanceofjava.com
  4.  * @category: Deference between staic and final static methods in java
  5.  */


  6. public class Super {
  7.   
  8.  
  9.  final static void method(){
  10.  
  11. System.out.println("Super class method");
  12.  }

  13. }

  1. package inheritanceInterviewPrograms;

  2. //  www.instanceofjava.com 

  3. public class Sub extends Super {
  4. static void method(){  // compiler time error:

  5. System.out.println("Sub class method");
  6.  
  7. }
  8. public static void main (String args[]) {
  9. Super.method();
  10. Sub.method();
  11.  
  12.  
  13. }
  14. }

Output:


difference between static method and final method in java
Select Menu