Facebook

adsense

Showing posts with label JAVA NOTES. Show all posts
Showing posts with label JAVA NOTES. Show all posts

Monday, 11 May 2015

File I/O Streams



You can write data to a file instead of the computer screen. You can write certain data to a file while still putting other data on the screen. Or you may need access to multiple files simultaneously. Or you may want to query the user for input rather than accepting it all on the command line. Or maybe you want to read data out of a file that's in a particular format. In Java all these methods take place as streams. < > Using File I/O streams. The System.out.println() statement we've been using all along is an implementation of Streams.

A program that writes a string to a file

In order to use the Java file classes, we must import the Java input/output package (java.io) in the following manner

import  java.io.*;

Inside the main method of our program, we must declare a FileOutputStream object. In this case, we wish to write a string to the file, and so we create a new PrintStream object that takes as its constructor the existing FileOutputStream. Any data we send from PrintStream will now be passed to the FileOutputStream, and ultimately to disk. We then make a call to the println method, passing it a string, and then close the connection.
Source Code
/*
* FileOutput
* Demonstration of FileOutputStream and PrintStream classes
*/

import java.io.*;

class FileOutput 


public static void main(String args[])

FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

try
{
// Create a new file output stream connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");

// Connect print stream to the output stream
p = new PrintStream( out );

p.println ("This is written to a file myFile.txt");

p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to the file myFile.txt");
}
}
}

Interactively communicating with the user

Program asking  the user for their name and then prints a personalized greeting.
Source Code
import java.io.*;

class PersonalHello {

  public static void main (String args[])
    {
    
      byte name[] = new byte[100];
      int nr_read = 0;

      System.out.println("Your name Please?");
      try {
        nr_read = System.in.read(name);
        System.out.print("Hello ");
        System.out.write(name,0,nr_read);
      }
      catch (IOException e) {
        System.out.print("I did not get your name.");
      }
      
    }
    
}
In code that does any significant input or output you'll want to begin by importing all the various java.io classes. import.java.io.*; Most of the reading and writing you do in Java will be done with bytes. Here we've started with an array of bytes that will hold the user's name.
First we print a query requesting the user's name. Then we read the user's name using the System.in.read() method. This method takes a byte array as an argument, and places whatever the user types in that byte array. Then, like before, we print "Hello." Finally we print the user's name.
The program doesn't actually see what the user types until he or she types a carriage return. This gives the user the chance to backspace over and delete any mistakes. Once the return key is pressed, everything in the line is placed in the array.

Reading Numbers

Often strings aren't enough. A lot of times you'll want to ask the user for a number as input. All user input comes in as strings so we need to convert the string into a number.
The getNextInteger() method that will accept an integer from the user. Here it is:
  static int getNextInteger() {
  
    String line;
  
    DataInputStream in = new DataInputStream(System.in);
    try {
      line = in.readLine();
      int i = Integer.valueOf(line).intValue();
      return i;
    }
    catch (Exception e) {
      return -1;
    }
       
  } // getNextInteger ends here

Reading Formatted Data

It's often the case that you want to read not just one number but multiple numbers. Sometimes you may need to read text and numbers on the same line. For this purpose Java provides the StreamTokenizer class.
Writing a text file
Sometimes you want to save your output in a  file. To do this we'll need to learn how to write data to a file. 
Source Code
// Write the Fahrenheit to Celsius table in a file

import java.io.*;

class FahrToCelsius  {

  public static void main (String args[]) {

    double fahr, celsius;
    double lower, upper, step;

    lower = 0.0;    // lower limit of temperature table
    upper = 300.0;  // upper limit of temperature table
    step  = 20.0;   // step size

    fahr = lower;
  
    try {

      FileOutputStream fout =  new FileOutputStream("test.out");

      // now to the FileOutputStream into a PrintStream
      PrintStream myOutput = new PrintStream(fout);
  
      while (fahr <= upper) {  // while loop begins here
        celsius = 5.0 * (fahr-32.0) / 9.0;
        myOutput.println(fahr + " " + celsius);
        fahr = fahr + step;
      } // while loop ends here
  
    }  // try ends here
    catch (IOException e) {
      System.out.println("Error: " + e);
      System.exit(1);
    }
  
  } // main ends here

}
There are only three things necessary to write formatted output to a file rather than to the standard output:
  1. Open a FileOutputStream using a line like
    FileOutputStream fout =  new FileOutputStream("test.out");
    This line initializes the FileOutputStream with the name of the file you want to write into.
  2. Convert the FileOutputStream into a PrintStream using a statement like
    PrintStream myOutput = new PrintStream(fout);
    The PrintStream is passed the FileOutputStream from step 1.
  3. Instead of using System.out.println() use myOutput.println()System.out and myOutput are just different instances of the PrintStream class. To print to a differentPrintStream we keep the syntax the same but change the name of the PrintStream.

Reading a text file

Now that we know how to write a text file, let's try reading one. The following code accepts a series of file names on the command line and then prints those filenames to the standard output in the order they were listed.
// Imitate the Unix cat utility

import java.io.*;

class cat  {

  public static void main (String args[]) {
  
  String thisLine;

  //Loop across the arguments
  for (int i=0; i < args.length; i++) {
 
  //Open the file for reading
  try {
    FileInputStream fin =  new FileInputStream(args[i]);

    // now turn the FileInputStream into a DataInputStream
    try {
      DataInputStream myInput = new DataInputStream(fin);
  
      try {
        while ((thisLine = myInput.readLine()) != null) {  // while loop begins here
          System.out.println(thisLine);
        } // while loop ends here
      }
      catch (Exception e) {
       System.out.println("Error: " + e);
      }
    } // end try
    catch (Exception e) {
      System.out.println("Error: " + e);
    }
  
   } // end try
   catch (Exception e) {
    System.out.println("failed to open file " + args[i]);
    System.out.println("Error: " + e);
  }
  } // for end here
  
  } // main ends here

}
  

Tuesday, 28 April 2015

JAVA PRACTICE QUESTION

These question are really helpful to improve your java concept and learn how to handle different situation in java.These question will check your java programming skills .In your practical life when you will go for an interview these types of question are asked so these question are also helpful for these who are scared about there interview .

Actually these question cover the main java concept,how to handle different tactics/problems in java and some tricky and interesting part in java 

    -  QUESTION 1
    -  QUESTION 2 
    -  QUESTION 3
    -  QUESTION 4
    -  QUESTION 5
    -  QUESTION 6
    -  QUESTION 7
    -  QUESTION 8
    -  QUESTION 9
    -  QUESTION 10
     -  QUESTION 11
    -  QUESTION 12
    -  QUESTION 13
    -  QUESTION 14
    -  QUESTION 15
NEW:
      -  QUESTION 16
     -  QUESTION 17
    -  QUESTION 18
    -  QUESTION 19
    -  QUESTION 20

     





NOTE :
-If you want me to post more question's like that ,than please answer these question in the comment below and also give me your review about the blog.

QUESTION 1

Q) What will happen when you attempt to compile and run the following code?

int Output = 10;
boolean b1 = false;
if((b1 == true) && ((Output += 10) == 20))
{
       System.out.println("We are equal " + Output);
}
else
{
        System.out.println("Not equal! " + Output);
}
---------------------------------------------------------
A)  Compilation error, attempting to perform binary comparison on logical data type.                                   B)  Compilation and output of "We are equal 10".          C)  Compilation and output of "Not equal! 20".            D)  Compilation and output of "Not equal! 10".
                    Main Page ||NEXT >
Give your answers in the comment below

Sunday, 12 April 2015

How to install JDK(Java development kit)?

These instructions are to help you download and install Java on your personal computer. You must install Java before installing Eclipse, and you will need both.


Downloading and Installing Java On Windows:


Prevent Errors like --> 'javac' is not recognized as an internal or external command

1. Click on "download" to download the latest Version of Jave SDK or any Jace SDK as per your requirement and install on your system.

2. Accept all of the defaults and suggestions, but make sure that the location where Java will be installed is at the top level of your C: drive. Click on "Finish." You should have a directory (folder) named C:\j2sdk1.5.0_04, with subfolders C:\j2sdk1.5.0_04\bin and C:\j2sdk1.5.0_04\lib

4. Modify your system variable called "PATH" (so that programs can find where Java is located).
To do this for Windows 2000 or XP, either right-click on the My Computer icon or select "System" on the control panel. When the window titled "System Properties" appears, choose the tab at the top named "Advanced." Then, click on "Environment Variables." In the bottom window that shows system variables, select "Path" and then click on "Edit..." Add C:\j2sdk1.5.0_04\bin as the first item in the list. Note that all items are separated by a semicolon, with no spaces around the semicolon. You should end up with a path variable that looks something like
C:\j2sdk1.5.0_04\bin;C:\WINNT\system32;C:\WINNT;C:\WINNT\system32\Wbem

For Windows 98 or ME, open the file AUTOEXEC.BAT in Notepad. You should find a line in this file that begins
SET PATH=...
Modify this line to add C:\j2sdk1.5.0_04\bin; immediately after the equals sign.

5. Modify or create a system variable called "CLASSPATH," as follows. In the lower "System Variables" pane choose "New..." and type in Variable Name "CLASSPATH" and value (note that it begins with dot semicolon)
.;C:\j2sdk1.5.0_04\lib

6. To test Java to see if everything is installed properly, open a command window (a DOS window) and type the command "javac" The result should be information about the Usage of javac and its options. If you get a result that "'javac' is not recognized as an internal or external command, operable program or batch file" then there is a problem and Java will not work correctly.

Sunday, 5 April 2015

Method Overloading in java

When a class has more than one method with same name, then we call that method is overloaded. The overloaded methods will have different number of arguments or different types of arguments, but name of the methods remains same.
Compiler checks method signature for duplicate methods or for method overloading. method signature consist of three things,
 1) Method Name   
 2) Number Of Arguments  
 3) Types of arguments.
If these three things are same for any two methods in a class, then compiler gives duplicate method error.
Compiler first checks method name. If it is same, then it checks number of arguments. If methods differs in number of arguments, then it does not check types of argument. It treats as methods are overloaded. If number of arguments are same then compiler checks types of arguments. If types of arguments are also same, then compiler will give duplicate method error. If types of arguments are not same, then compiler will treat them as methods are overloaded.
For method overloading to be successful, method name must be same and methods must have different number of arguments or different types of arguments. If method names are different, then those methods will be treated as two different methods.
Go through this example,
public class MethodOverloading
{
void methodOverloaded()
{
//No argument method
}
void methodOverloaded(int i)
{
//One argument is passed
}
void methodOverloaded(double d)
{
//One argument is passed but type of argument is different
}
void methodOverloaded(int i, double d)
{
//Two argument method
//Method signature of this method is methodOverloaded(int, double)
}
void methodOverloaded(double d, int i)
{
//It is also two argument method but type of arguments changes
//Method signature of this method is methodOverloaded(double, int)
}
void methodOverloaded(double d1, int i1)
{
                //It has same method signature methodOverloaded(double, int) as of above method
//So, it is a Duplicate method, You will get compile time error here
}
    void differentMethod()
{
//Different method
}
}
Overloaded methods may have same return types or different return types. It does not effect method overloading.
public class MethodOverloading
{
void methodOverloaded()
{
//No argument method, return type is void
}
int methodOverloaded(int i)
{
        //Returns int type
return i;
}
int methodOverloaded(double d)
{
        //Same return type as of above method
return 0;
}
void methodOverloaded(double d)
{
//Duplicate method because it has same method signature as of above method
}
}
Important Note :
 If two methods have same signature and different return types, then those methods will not be treated as two different methods or methods overloaded. For duplication, compiler checks only method signature not return types. If method signature is same, straight away it gives duplicate method error.
Overloaded methods may have same access modifiers or different access modifiers. It also does not effect method overloading.
public class MethodOverloading
{
private void methodOverloaded()
{
//No argument, private method
}
private int methodOverloaded(int i)
{
//One argument private method
return i;
}
protected int methodOverloaded(double d)
{
//Protected Method
return 0;
}
public void methodOverloaded(int i, double d)
{
//Public Method
}
}
Overloaded methods may be static or non-static. This also does not effect method overloading.
public class MethodOverloading
{
private static void methodOverloaded()
{
//No argument, private static method
}
private int methodOverloaded(int i)
{
//One argument private non-static method
return i;
}
static int methodOverloaded(double d)
{
//static Method
return 0;
}
public void methodOverloaded(int i, double d)
{
//Public non-static Method
}
}
From the above examples, it is clear that compiler will check only method signature for method overloading or for duplicate methods. It does not check return types, access modifiers and static or non-static.

Wednesday, 1 April 2015

20 Things You Should Know About Strings In Java

Strings in java are most used data types while developing any kind of applications. Hence, strings are treated as very special in java. This article contains 20 important points about strings in java. These points are also most discussed ones in the java interviews.

1) In Java, you can create string objects in two ways. One is using new operator and another one is using string literals.

String s1 = "abc";        //Creating string object using string literal

String s2 = new String("abc");          //Creating string object using new operator

2) String objects created using string literals are stored in String Constant Pool and string objects created using new operator are stored in the heap memory.

3) What Is String Constant Pool?

String objects are most used data objects in Java. Hence, java has a special arrangement to store the string objects. String Constant Pool is one such arrangement. String Constant Pool is the memory space in heap memory specially allocated to store the string objects created using string literals. In String Constant Pool, there will be no two string objects having the same content.

Whenever you create a string object using string literal, JVM first checks the content of the object to be created. If there exist an object in the string constant pool with the same content, then it returns the reference of that object. It doesn’t create a new object. If the content is different from the existing objects then only it creates new object.

4) String is a derived type, not a primitive type like int, double etc. Strings are objects in java.

5) String objects in java are immutable. That means, once you create String objects, you can’t modify them. If you try to modify them, a new object will be created with modifications.

6) To overcome the immutability of String objects, two more classes are introduced in Java. They are StringBuffer and StringBuilder classes. Objects of StringBuffer and StringBuilder class are mutable.

7) All three classes – String, StringBuffer and StringBuilder are final. That means you can’t extend them. All three classes are members of java.lang package.

8) In all three classes – String, StringBuffer and StringBuilder, toString() method is overridden. That means, whenever you use references to objects of these classes, actual content of those objects will be retrieved.

9) equals() and hashCode() methods are overridden in String class but they are not overridden in StringBuffer and StringBuilder classes.

10) String and StringBuffer objects are thread safety where as StringBuilder objects are not thread safety.

11) Using “==“, equals() and hashCode() on String objects.

All three – “==”, equals() and hashCode() are used to check the equality of two string objects. If you want to check the equality of two string objects based on their physical address, then use “==” operator. If you want to check the equality of two string objects based on their content, then use equals() method. It is recommended not to use hashCode() method to compare the string objects. You may get unexpected results. Click here to see when to use “==”, equals() and hashcode() on strings.

12) Strings in java are backed by character array. You can retrieve this array using toCharArray() method of String class.

13) If you are performing lots of string concatenation in your code, then use either StringBuffer or StringBuilder classes. These two classes give better performance than String class. Click here to see the differences between String, StringBuffer and StringBuilder classes.

14) Java doesn’t support operator overloading except ‘+‘ operator. ‘+‘ can be used for number addition as well as to concatenate two string objects. This is the special treatment given by the Java to string objects.

15) Java provides 4 methods to compare the strings.

1) equals() – This method returns true if contents of two string objects are same.
2) equalsIgnoreCase() – This method compares two string objects but ignores the case of the characters when comparing.
3) compareTo() – This method compares one string with another and returns an integer if the string is smaller or equal or greater than the other string.
4) compareToIgnoreCase() – This method is same as compareTo() but ignores the case of the characters when comparing.

16) You need not to create objects to access the String class methods. You can do so using string literals also. Look at the below example.

public class MainClass
{
public static void main(String[] args)
{
System.out.println("abc".charAt(0));          //Output : a

System.out.println("abc".equalsIgnoreCase("ABC"));      //Output : true

System.out.println("abc".compareTo("abc"));         //Output : 0

System.out.println("abc".indexOf('c'));        //Output : 2
}
}
17) What Is String Intern?

String object in the string constant pool is called as String Intern. You can create an exact copy of heap memory string object in string constant pool. This process of creating an exact copy of heap memory string object in string constant pool is called interning. intern() method is used for interning. Click here to see more about string intern in java.

18) indexOf(), lastIndexOf() and matches(String regex) are the methods to perform search within a string.

19) Unlike in C and C++, Strings in java are not terminated with null character. Strings are treated as objects in java.

20) Java provides lots of in built methods to manipulate the string objects. click here to see the documentation of String class.

Tuesday, 31 March 2015

TEST YOUR JAVA SKILLS


1) Which is true about Static Initialization Block?

A. We can use only static members of a class inside the Static Initialization Block.
B. Static Initialization Blocks are mainly used to initialize static fields of a class.
C. Static Initialization Block is the first block to be executed after class is loaded in the memory.
D. All of the above.


2) Where the static initialization blocks are stored in the memory?


3) What will be the output of this program?

class A
{
static int i;

static
{
System.out.println(1);

i = 100;
}
}

public class StaticInitializationBlock
{
static
{
System.out.println(2);
}

public static void main(String[] args)
{
System.out.println(3);

System.out.println(A.i);
}
}

4) What happens when you compile the below class?

class A
{
int i;

static
{
System.out.println(i);
}
}

5) Is the below code written correctly?

class A
{
static
{
static
{
System.out.println(1);
}
}
}
6) How many static initialization blocks are there in the below Class A?

class A
{
static int a = 50;

static
{
a = 50;
}

static
{
a = 50;
}
}

7) What will be the outcome of the following program?

public class A
{
static
{
System.out.println(1);
}

static
{
System.out.println(2);
}

static
{
System.out.println(3);
}

public static void main(String[] args)
{
A a;
}
}

8) What will be the output of this program?

class A
{
static int first;

static String second;

static
{
System.out.println(1);

first = 100;
}

static
{
System.out.println(2);

second = "SECOND";
}
}

public class StaticInitializationBlock
{
static
{
System.out.println(3);
}

public static void main(String[] args)
{
System.out.println(4);

System.out.println(A.first);

System.out.println(A.second);
}
}

9) What will be the output of the below program?

class A
{
static int i;

static
{
i = 100;

System.out.println(1);
}

static void staticMethod()
{
System.out.println(i);

System.out.println(2);
}
}

public class B
{
static
{
System.out.println(3);
}

public static void main(String[] args)
{
System.out.println(4);

System.out.println(A.i);

A.staticMethod();
}
}

10) What is the difference between SIB and IIB?

11) Can we invoke static method inside the SIB – Static Initialization Block?


12) What will be the output of following program?

class A
{
{
System.out.println(1);
}

public A()
{
System.out.println(2);
}

public static void main(String[] args)
{
System.out.println(3);

A a = new A();
}
}

13) What will be the output of the below program?

public class A
{
{
System.out.println("First");
}

{
System.out.println("Second");
}

{
System.out.println("Third");
}

public A()
{
System.out.println("Fourth");
}

public static void main(String[] args)
{
System.out.println("Fifth");

A a = new A();
}
}

14) Which one of these are executed first while creating an object to the class?

a) Statements of IIB block
b) Statements of constructor


15) What will be the outcome of the below program?

public class A
{
int i;

{
System.out.println("IIB-1");

i = 100;
}

{
System.out.println("IIB-2");

System.out.println(i);

i = 200;
}

public static void main(String[] args)
{
System.out.println("main");

A a = new A();

System.out.println(a.i);
}
}

       

Try to solve these conceptual question of java to know how much java do you know, and write your answers in the comment below like, "Q no) answer" or click on answer link , I will post the answer after somedays if I will get a large number of clicks on answer links 

            


Saturday, 28 March 2015

10 Tricky Core java Question and Answers

(click for Answers).

1) Can you instantiate this class?

public class A
{
    A a = new A();
}

2) Is the below code written correctly? If yes, what will be the output?

class A
{
    static void staticMethod()
    {
        System.out.println("Static Method");
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        A a = null;

        a.staticMethod();
    }
}

3) What will be the output of the following program?

class A
{
    static int i = 1111;

    static
    {
        i = i-- - --i;
    }

    {
        i = i++ + ++i;
    }
}

class B extends A
{
    static
    {
        i = --i - i--;
    }

    {
        i = ++i + i++;
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        B b = new B();

        System.out.println(b.i);
    }
}

4) What happens when you call methodOfA() in the below class?


class A
{
    int methodOfA()
    {
        return (true ? null : 0);
    }
}

5) What will be the output of the below program?

public class MainClass
{
    public static void main(String[] args)
    {
        Integer i1 = 127;

        Integer i2 = 127;

        System.out.println(i1 == i2);

        Integer i3 = 128;

        Integer i4 = 128;

        System.out.println(i3 == i4);
    }
}

6) Can we override method(int) as method(Integer) like in the below 

class A
{
    void method(int i)
    {
        //method(int)
    }
}

class B extends A
{
    @Override
    void method(Integer i)
    {
        //method(Integer)
    }
}

7) Which statements in the below class shows compile time error (Line 5 or Line 7 or both)?

public class MainClass
{
    public static void main(String[] args)
    {
        Integer i = new Integer(null);

        String s = new String(null);
    }
}
8) What will be the output of the following program?


public class MainClass
{
    public static void main(String[] args)
    {
        String s = "ONE"+1+2+"TWO"+"THREE"+3+4+"FOUR"+"FIVE"+5; 

        System.out.println(s);
    }
}

9) What will be the output of the below program?

public class MainClass
{
    static int methodOne(int i)
    {
        return methodTwo(i *= 11);
    }

    static int methodTwo(int i)
    {
        return methodThree(i /= 11);
    }

    static int methodThree(int i)
    {
        return methodFour(i -= 11);
    }

    static int methodFour(int i)
    {
        return i += 11;
    }

    public static void main(String[] args)
    {
        System.out.println(methodOne(11));
    }
}

10) What will be the output of the following program?

public class MainClass
{
    public static void main(String[] args)
    {
        int i = 10 + + 11 - - 12 + + 13 - - 14 + + 15;

        System.out.println(i);
    }
}

/////////////////////////////////////////////////////////////////////////////////
ANSWERS

1) Not possible. Because while instantiating, constructor will be called recursively.

2) Yes, the code is correct. You can call static methods through reference variable which is pointing to null. Output will be,
Static Method

3) 6

4) Throws NullPointerException at run time.

5)
true
false

6) No. It gives compile time error. Compiler treats int and Integer as two different types while overriding. Auto-boxing doesn’t happen here.

7) Only Line 7 shows compile time error. Because, compiler will be in an ambiguous situation of which constructor to call. Because, String class has five constructors which take one argument of derived type . Where as Integer class has only one constructor which takes one argument of derived type.

8) ONE12TWOTHREE34FOURFIVE5

9) 11

10) 75