Powered by Blogger.
Showing posts with label Java Programs. Show all posts
Showing posts with label Java Programs. Show all posts

Java Automatic Memory Management | Java Coding

Automatic Memory Management:

Many programming languages like C and C++ permit the memory to be allocated dynamically at runtime. After the allocated memory is no longer required, the program or runtime environment should de-allocated the memory. If the program does not de-allocate the memory that can crash eventually when there is no memory left for the system to allocate. These types of programs are said memory leaks. Java overcome this problem by using garbage collection. It provides a system level thread that tracks each memory allocation. During idle cycles in the JVM, the garbage collection thread checks for and frees any memory the can be freed in the object lifecycle.

Java: How to Read a Java String from the contents of a file

I have been using this idiom for some time now. And it seems to be the most wide-spread, at least in the sites I've visited.

Does anyone have a better/different way to Read a Java String from the contents of a file?

private String readFile( String file ) throws IOException {
    BufferedReader reader = new BufferedReader( new FileReader (file));
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    String ls = System.getProperty("line.separator");

    while( ( line = reader.readLine() ) != null ) {
        stringBuilder.append( line );
        stringBuilder.append( ls );
    }

    return stringBuilder.toString();
}

Read String from a File Example:-

 import java.io.*;

 public class ReadFile{
   public static void main(String[]args){
      File file = new File(”/home/Parvez/MyJavaBook”, ”MyText.txt”);
      try{
         BufferedReader in = new BufferedReader(new FileReader(file));
         String str = in.readLine();
         while(str != null){
         System.out.println(”Read: ” +str);
         str = in.readLine();
         }
         in.close();
      }catch(FileNotFoundException e1){
         System.out.println(”File not found”);
      }catch(IOException e2){
         System.out.println(”Input/output problem”);
      }
   }
 }

Generation of Source Code:--

/*
Read File in String Using Java Buffered Input Stream Example. This example shows how to read a file content into a Sting object using available and read methods of Java Buffered Input Stream.
*/
    
    import java.io.*;
    
    public class ReadFileInToString {
    
            public static void main(String[] args) {
                  
                    //create file object
                    File file = new File("C://FileIO//ReadFile.txt");
                    BufferedInputStream bin = null;
                  
                    try
                    {
                            //create FileInputStream object
                            FileInputStream fin = new FileInputStream(file);
                          
                            //create object of BufferedInputStream
                            bin = new BufferedInputStream(fin);
                          
                            //create a byte array
                            byte[] contents = new byte[1024];
                          
                            int bytesRead=0;
                            String strFileContents;
                          
                            while( (bytesRead = bin.read(contents)) != -1){
                                  
                                    strFileContents = new String(contents, 0, bytesRead);
                                    System.out.print(strFileContents);
                            }
                          
                    }
                    catch(FileNotFoundException e)
                    {
                            System.out.println("File not found" + e);
                    }
                    catch(IOException ioe)
                    {
                            System.out.println("Exception while reading the file " + ioe);
                    }
                    finally
                    {
                            //close the BufferedInputStream using close method
                            try{
                                    if(bin != null)
                                            bin.close();
                            }catch(IOException ioe)
                            {
                                    System.out.println("Error while closing the stream :"
    + ioe);
                            }
                          
                    }
            }
          
    }
    
    
/*
Output would be This file is for demonstration of how to read a file into String using Java Buffered Input Stream.
*/

Java~~Write a java program using Blocks~~


A block as a group of statements that are collected together called a compound statement. It is bound by opening and closing braces { }. A class definition is contained in a block. A block statement can be nested withing another block. In Java source code, block statements are executed first, then constructor statements are executed, and then method statements are executed.

Best Example: 

 public class BlockTest{
 public String info;

 public BlockTest(){
 info = ”Constructor:Executed in 2nd step”;
 System.out.println(info);
 }

 {
 info = ”Block:Executed in 1st step”;
 System.out.println(info);
 }

 public void show(){
 info = ”Method:Executed in 3rd step”;
 System.out.println(info);
 }

 public static void main(String[]args){
 BlockTest bt = new BlockTest();
 bt.show();
  }
 }

Java:: Simple Java Program for beginners

This short example shows how to write first java application and compile and run it, which prints a String Welcome in Java World in output:

1    public class Welcome{
2       public static void main ( String[ ]args ){
3          System. out.println(”Welcome in Java World”);
4       }
5    }


Write this code in Notepad for Windows or Text Editor for Linux and save the file as: Welcome.java (Source files must be named after the public class). Now you are ready to compile and run the program. To compile the program, open a command window or terminal, and change to the directory where the program is stored and type javac Welcome.java If the program contains no errors then a new file Welcome.class will be created in the same directory. Now you can run this byte codes file Welcome. class by typing the command java Welcome

Line 1: declares the user-defined class named Welcome. Every Java program consists at least one public class. The Welcome.java file creates a Welcome.class file when the source file is being complied.

Line 2: declares the main method, where the program starts to execute.

The following describes each element of Line 2:

public The access modifier of main() method is public, because the main() method can be accessed by anything including the Java technology interpreter.

static The main() is static method because on instance of the class is needed to execute static methods and static method is a single copy.

void The return type of the main() method is void, because the main() method does not return any value.

String[] args The main() method declares the single parameter of String array named args. If the program is given any arguments on its command line, these are passed into the main() method
through this args array of String type.

Line 3: displays or prints a line of text in the command window. System.out is known as the standard output object.

Line 4: end of the main() method.

Line 5: end of the Welcome class.