Instance variables in java with example program

  • Variables declared inside a class and outside method without static keyword known as instance variables.
  • Instance variables will be used by objects to store state of the object.
  • Every object will have their own copy of instance variables. where as static variables will be single and shared(accessed) among objects.
  • Instance variables will be associated with the instance(Object)
  • Static variables will be associated with the class.



#1: Java example program on declaring and accessing instance variables.

  1. package com.instanceofjava.instancevariables;

  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview questions
  5.  * 
  6.  * Description: Instance variables in java with example program
  7.  *
  8.  */
  9. public class InstanceVariables {

  10. String websiteName;
  11. String category;
  12. public static void main(String[] args) {
  13. InstanceVariables obj = new InstanceVariables();
  14. obj.websiteName="www.InstanceOfJava.com";
  15. obj.category="Java tutorial/interview questions";

  16. }

  17. }


  • Instance variables allows all four type of access specifiers in java


instance variables in java with example



  • Instance variables can be final and transient


instance variables in java with example program



  • Instance variables can not be declared as abstract, static strictfp, synchronized and native

Java program to write a string to file using PrintWriter

  • We can write a string to text file in java in various ways.
  • Using PrintWriter we can write or append a string to the text file. 
  • Using println() method of PrintWriter we can save or write string to text file.
  • After completion of using PrintWriter you need to close it by calling close() method.
  • If you are using java 7 , by using try with resources we can implement it and closing will be taken care automatically.
  • Now we will see an example program on how to write or save a string / string variable  to a text file using java 7.

#1: Java Example program to write or save string to file using PrintWriter and java 7 try with resources.

  1. package com.instanceofjava.writetofile;
  2. import java.io.FileNotFoundException;
  3. import java.io.PrintWriter;
  4. /**
  5.  * 
  6.  * @author www.instanceofjava.com 
  7. * @category: java example program
  8.  * 
  9.  * Description: Write a java example program to write string to files using PrintWriter 
  10.  * 
  11. */
  12. public class WriteStringToFile {
  13.  
  14.  public static void main(String[] args) { 
  15.        String str="Write String to file";  
  16.  try(  PrintWriter out = new PrintWriter("data.txt")  )
  17.            
  18. out.println( str );    
  19. catch (FileNotFoundException e) 
  20. {  
  21. e.printStackTrace()
  22.      
  23. }
  24. }   
  25. }

save string to file

Java read file line by line example program

  • Reading a text file line by line in java can be done by using java.io.BufferedReader .
  • Create a BufferedReader class by passing new FileReader(new File("filename")) object to it's constructor.
  • By using readLine() method of  BufferedReader class we can read line by line text from a text file as Strings.
  • Lets see a java example program on hoe to read data from file line by line using BufferedReader class readLine() method.
  • Java read lines from text file example program.


#1: Java Example program to read file line by line

 

  1. package com.instanceofjava.readfile;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. /** *  * 
  8. @author www.instanceofjava.com 
  9. * @category: Interview Programs 
  10. * @description: How to read text file line by line in java example program 
  11. * */
  12.  
  13. public class ReadFile {
  14.  
  15.     public static void main(String[] args) {        
  16.         
  17.         try {            
  18.            File fileName = new File("E:\\data.txt");
  19.             FileReader fileReader = new FileReader(fileName);     
  20.             BufferedReader bufferedreader = new BufferedReader(fileReader);           
  21.             StringBuffer sb = new StringBuffer();
  22.             String strLine;            
  23.            while ((strLine = bufferedreader.readLine()) != null) {
  24.                 sb.append(strLine);
  25.                 sb.append("\n");        
  26.             }         
  27.            fileReader.close();
  28.            System.out.println(sb.toString()); 
  29.          } catch (IOException e) {
  30.             e.printStackTrace();     
  31.    }
  32.  
  33.     }
  34.  
  35. }

Output:

  1. java read file line by line example
  2. java read file line by line java 8
  3. java read lines from text file 
  4. example bufferedreader java example

#2: Java example program to read text file line by line using java 7 try with resource example



read file line by line java


#3: Java example program to read text file line by line using java 8 example (Using stream)

  1. package com.instanceofjava.readfile;
  2. import java.io.IOException;
  3. import java.nio.file.Files;
  4. import java.nio.file.Paths;
  5. import java.util.stream.Stream;
  6. /**
  7.  *
  8. * @author www.instanceofjava.com
  9.  * @category: Interview Programs 
  10. * @description: How to read text file line by line in java example program using java 8 stream
  11. */
  12. public class ReadFile {
  13. public static void main(String[] args) throws IOException {
  14.  
  15. try (Stream<String> stream = Files.lines(Paths.get("E:\\data.txt"))) 
  16. {           
  17.  
  18.  stream.forEach(System.out::println);
  19.  
  20. }
  21. }
  22. }

Convert to maven project in eclipse java

  • In order to convert any java project in to maven using eclipse we need to install m2e plugin.
  • Latest versions of eclipse are coming with this m2e plugin by default.
  • If not found this plugin we can install it by help->install->click on add and enter http://download.eclipse.org/technology/m2e/releases. 
  • currently i am using eclipse oxygen version so it is having m2e plugin.
  • I have created a normal java project and i want to convert that into a maven project.
  • To convert any project in to maven right click on the project and ->configure->convert to maven project. 
  • After that a window will be opened and you need to enter group id and artifact id and then click on finish.  
  • convert to maven project eclipse luna / convert to maven project is not visible in eclipse /convert to maven project option not available in eclipse.



Right click on project and select configure-> convert to maven project.


convert to maven project java

Project will be converted to maven by creating pom.xml file.

how to convert to maven project java

 

pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.or
  2. /2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  3. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.   <modelVersion>4.0.0</modelVersion>
  5.   <groupId>com.instanceofjava.maven</groupId>
  6.   <artifactId>MavenProject</artifactId>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <build>
  9.     <sourceDirectory>src</sourceDirectory>
  10.     <plugins>
  11.       <plugin>
  12.         <artifactId>maven-compiler-plugin</artifactId>
  13.         <version>3.7.0</version>
  14.         <configuration>
  15.           <source>1.8</source>
  16.           <target>1.8</target>
  17.         </configuration>
  18.       </plugin>
  19.     </plugins>
  20.   </build>
  21. </project>

Add dependencies to your pom.xml file

  1.  <properties>
  2.         <springVersion>5.0.3.RELEASE</springVersion>
  3.       </properties>
  4.       <dependencies>
  5.         <dependency>
  6.           <groupId>org.springframework</groupId>
  7.           <artifactId>spring-context</artifactId>
  8.           <version>${springVersion}</version>
  9.         </dependency>
  10.        <dependency>
  11.          <groupId>org.springframework</groupId>
  12.          <artifactId>spring-core</artifactId>
  13.           <version>5.0.3.RELEASE</version>
  14.         </dependency>
  15.       </dependencies>

How to read values from properties file in java example

  • To store configurable parameters, .properties file will be used in java.
  • We can Store data in key value pair (key=value).
  • Re compilation not required if we change any keys or values in properties file.
  • Used for internationalization  and to store frequently changeable values. 
  • java.util.Properties class is sub class of Hashtable. 
  • We can read / load the propertied file using InputStream.
  • InputStream inputStream = getClass().getClassLoader().getResourceAsStream(properties_FileName);
  • Create a maven project, under resources create one .properties file and load this file in main class using getClass().getClassLoader().getResourceAsStream(properties_FileName).
  • Lets see an example java program on java read properties file from resource folder or how to read values from properties file in java example or how to get values from properties file in java.

 #1: Create a maven project:

java read properties file from classpath


Create properties file:

reading properties file in java

#1: Java example program  to get values from properties file in java

  1. package com.instanceofjava.propertiesfile;
  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.util.Date;
  6. import java.util.Properties;
  7. /**
  8.  *  
  9. * @author www.instanceofjava.com
  10.  * @category: java example programs
  11.  *  
  12. * Write a java example program to read/ load properties file
  13.  *
  14.  */
  15. public class ReadPropertiesFile {
  16.  
  17.     public Properties getProperties() throws IOException {
  18.         
  19.         InputStream inputStream=null;
  20.         Properties properties = new Properties();
  21.         try {
  22.             
  23.             String propFileName = "config.properties";
  24.  
  25.             inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
  26.  
  27.             if (inputStream != null) {
  28.                 properties.load(inputStream);
  29.             } else {
  30.                 throw new FileNotFoundException("property file '" + propFileName + "' not found
  31. in the classpath");
  32.             }
  33.  
  34.  
  35.         } catch (Exception e) {
  36.             System.out.println("Exception: " + e);
  37.        } finally {
  38.             inputStream.close();
  39.         }
  40.          return properties;
  41.     }
  42.     
  43.     
  44.     public static void main(String[] args) throws IOException {
  45.         
  46.         ReadPropertiesFile obj= new ReadPropertiesFile();
  47.         Properties properties=obj.getProperties();
  48.         // get the each property value using getProperty() method 
  49.         System.out.println("username: "+properties.getProperty("username"));
  50.         System.out.println("password: "+properties.getProperty("password"));
  51.         System.out.println("url: "+properties.getProperty("url"));
  52.         
  53.                 
  54.     }
  55.  
  56. }

Output:

  1. username: user1
  2. password: abc123
  3. url: www.instanceofjava.com

Java finally block after return statement

  • finally block will be executed always even exception occurs.
  • If we explicitly call System.exit() method then only finally block will not be executed if exit() call is before finally block.
  • There are few more rare scenarios where finally block will not be executed.
  1. When JVM crashes
  2. When there is an infinite loop
  3. When we kill the process ex:kill -9 (on unix)
  4. Power failure, hardware error or system crash.
  5. And as we discussed System.exit().
  •  Other than these conditions finally block will be executed always.
  • finally block is meant to keep cleaning of resources. Placing code other than cleaning is a bad practice
  • What happens if we place finally block after return statement? or
  • Does finally block will execute after return statement??
  •  As per the above rules Yes finally will always execute except any interruption like System.exit()  or all above mentioned conditions

 Program #1 : Java example program which explains how finally block will be executed even after a return statement in a method.

  1. package com.instanceofjava.finallyblockreturn;
  2. /**
  3.  * By: www.instanceofjava.com
  4.  * program: does finally gets executed after return statement??
  5.  *
  6.  */
  7. public class FinallyBlockAfterReturn {
  8.  
  9.     public static int Calc(){
  10.         try {
  11.             
  12.             return 0;
  13.         } catch (Exception e) {
  14.             return 1;
  15.         }
  16.  
  17. finally{
  18.             
  19.  System.out.println("finally block will be executed even when we
  20. place after return statement");
  21.         }
  22.  }
  23.     
  24. public static void main(String[] args) {
  25.         
  26.         System.out.println(Calc());         
  27. }
  28.  
  29. }



  
Output:


  1. finally block will be executed even when we place after return statement
  2. 0


 Can we place return statement in finally??
  • Yes we can place return statement in finally and finally block return statement will be executed.
  • But it is a very bad practice to place return statement in finally block.
Program #2 : Java example program which explains finally block with return statement in a method.



finally block after return statement
Select Menu