java unit3
java unit3
Wrapper classes
Parser methods
Converting Back from String object to Primitives:
The six parser methods are
parseInt
parseFloat
parseDouble
parseShort
parseByte
parselong
They take String as an argument convert it to the corresponding primitive.
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper
class is known as autoboxing, for example, byte to Byte, char to Character, int to
Integer, long to Long, float to Float, boolean to Boolean, double to Double, and
short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.
Wrapper class Example: Primitive to Wrapper
1. //Java program to convert primitive into objects
2. //Autoboxing example of int to Integer
3. public class WrapperExample1{
4. public static void main(String args[]){
5. //Converting int into Integer
6. int a=20;
7. Integer i=Integer.valueOf(a);//converting int into Integer explicitly
8. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
2
9.
10. System.out.println(a+" "+i+" "+j);
11. }}
Output:
20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is
known as unboxing. It is the reverse process of autoboxing. Since Java 5, we do
not need to use the intValue() method of wrapper classes to convert the wrapper
type into primitives.
Wrapper class Example: Wrapper to Primitive
1. //Java program to convert object into primitives
2. //Unboxing example of Integer to int
3. public class WrapperExample2{
4. public static void main(String args[]){
5. //Converting Integer to int
6. Integer a=new Integer(3);
7. int i=a.intValue();//converting Integer to int explicitly
8. int j=a;//unboxing, now compiler will write a.intValue() internally
9.
10. System.out.println(a+" "+i+" "+j);
11. }}
Output:
333
Java Wrapper classes Example
1. //Java Program to convert all primitives into its corresponding
2. //wrapper objects and vice-versa
3. public class WrapperExample3{
4. public static void main(String args[]){
5. byte b=10;
6. short s=20;
7. int i=30;
8. long l=40;
3
9. float f=50.0F;
10. double d=60.0D;
11. char c='a';
12. boolean b2=true;
13.
14. //Autoboxing: Converting primitives into objects
15. Byte byteobj=b;
16. Short shortobj=s;
17. Integer intobj=i;
18. Long longobj=l;
19. Float floatobj=f;
20. Double doubleobj=d;
21. Character charobj=c;
22. Boolean boolobj=b2;
23.
24. //Printing objects
25. System.out.println("---Printing object values---");
26. System.out.println("Byte object: "+byteobj);
27. System.out.println("Short object: "+shortobj);
28. System.out.println("Integer object: "+intobj);
29. System.out.println("Long object: "+longobj);
30. System.out.println("Float object: "+floatobj);
31. System.out.println("Double object: "+doubleobj);
32. System.out.println("Character object: "+charobj);
33. System.out.println("Boolean object: "+boolobj);
34.
35. //Unboxing: Converting Objects to Primitives
36. byte bytevalue=byteobj;
37. short shortvalue=shortobj;
38. int intvalue=intobj;
39. long longvalue=longobj;
40. float floatvalue=floatobj;
41. double doublevalue=doubleobj;
42. char charvalue=charobj;
43. boolean boolvalue=boolobj;
4
44.
45. //Printing primitives
46. System.out.println("---Printing primitive values---");
47. System.out.println("byte value: "+bytevalue);
48. System.out.println("short value: "+shortvalue);
49. System.out.println("int value: "+intvalue);
50. System.out.println("long value: "+longvalue);
51. System.out.println("float value: "+floatvalue);
52. System.out.println("double value: "+doublevalue);
53. System.out.println("char value: "+charvalue);
54. System.out.println("boolean value: "+boolvalue);
55. }}
Output:
---Printing object values---
Byte object: 10
Short object: 20
Integer object: 30
Long object: 40
Float object: 50.0
Double object: 60.0
Character object: a
Boolean object: true
---Printing primitive values---
byte value: 10
short value: 20
int value: 30
long value: 40
float value: 50.0
double value: 60.0
char value: a
boolean value: true
String class
5
index (position)
substrings
StringBuffer class
StringBuffer class is used to create a mutable string object i.e its state can be
changed after it is created. It represents growable and writable character sequence.
As we know that String objects are immutable, so if we do a lot of changes
with String objects, we will end up with a lot of memory leak.
So StringBuffer class is used when we have to make lot of modifications to our
string. It is also thread safe i.e multiple threads cannot access it simultaneously.
StringBuffer defines 4 constructors. They are,
1. StringBuffer ( )
2. StringBuffer ( int size )
3. StringBuffer ( String str )
4. StringBuffer ( charSequence [ ]ch )
strB.append("tonight");
System.out.println(strB); // Output: studytonight
}
}
Reason:
Output is such because String objects are immutable objects. Hence, if we
concatenate on the same String object, it won't be altered(Output: study). But
StringBuffer creates mutable objects. Hence, it can be altered(Output:
studytonight)
StringBuffer append(int n)
test123
insert()
This method inserts one string into another. Here are few forms of insert() method.
StringBuffer insert(int index, String str)
test123
reverse()
This method reverses the characters within a StringBuffer object.
StringBuffer str = new StringBuffer("Hello");
str.reverse();
System.out.println(str);
olleH
13
replace()
This method replaces the string from specified start index to the end index.
<
StringBuffer str = new StringBuffer("Hello World");
str.replace( 6, 11, "java");
System.out.println(str);
Hello java
capacity()
This method returns the current capacity of StringBuffer object.
StringBuffer str = new StringBuffer();
System.out.println( str.capacity() );
16
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Java try and catch
The try statement allows you to define a block of code to be tested for errors while
it is being executed.
The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
The try and catch keywords come in pairs:
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Consider the following example:
This will generate an error, because myNumbers[10] does not exist.
public class MyClass {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
17
If an error occurs, we can use try...catch to catch the error and execute some code
to handle it:
Example
public class MyClass {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
Finally
The finally statement lets you execute code, after try...catch, regardless of the
result:
Example
public class MyClass {
public static void main(String[] args) {
18
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
There is no need to override any of the above methods available in the Exception
class, in your derived class. But practically, you will require some amount of
customizing as per your programming needs.
NOTE:
The keyword “throw” is used to create a new Exception and throw it to the catch
block.
Risk Factor
Proper co-ordination is required between threads accessing common variables
[use of synchronized and volatile] for consistence view of data
overuse of java threads can be hazardous to program’s performance and its
maintainability.
Threads in Java
Java threads facility and API is deceptively simple:
Every java program creates at least one thread [ main() thread ]. Additional threads
are created through the Thread constructor or by instantiating classes that extend
the Thread class.
Example:
A thread goes through various stages in its life cycle. For example, a thread is born,
started, runs, and then dies. The following diagram shows the complete life cycle
of a thread.
Properties :
It is the thread from which other “child” threads will be spawned.
Often, it must be the last thread to finish execution because it performs various
shutdown actions
Flow diagram :
ct.getPriority());
Thread Priority
When a Java thread is created, it inherits its priority from the thread that created
it.
You can modify a thread’s priority at any time after its creation using
the setPriority method.
30
void write(byte[] ary, It is used to write len bytes from the byt
int off, int len) starting at offset off to the file output str
8. fout.write(b);
9. fout.close();
10. System.out.println("success...");
11. }catch(Exception e){System.out.println(e);}
12. }
13. }
Output:
Success...
The content of a text file testout.txt is set with the
data Welcome to javaTpoint.
testout.txt
Welcome to javaTpoint.
Java Scanner
Scanner class in Java is found in the java.util package. Java
provides various ways to read input from the keyboard, the
java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a
delimiter which is whitespace by default. It provides many
methods to read and parse various primitive values.
The Java Scanner class is widely used to parse text for strings and
primitive types using a regular expression. It is the simplest way
to get input in Java. By the help of Scanner in Java, we can get
input from the user in primitive types such as int, long, double,
byte, float, short, etc.
The Java Scanner class extends Object class and implements
Iterator and Closeable interfaces.
37
delimiters.
nextBigDecimal() method or
not.
method or not.
6 ) representation of Scanner
) using.
Example 1
Let's see a simple example of Java Scanner where we are getting
a single input from the user. Here, we are asking for a string
through in.nextLine() method.
1. import java.util.*;
2. public class ScannerExample {
3. public static void main(String args[]){
4. Scanner in = new Scanner(System.in);
5. System.out.print("Enter your name: ");
6. String name = in.nextLine();
7. System.out.println("Name is: " + name);
8. in.close();
9. }
10. }
Output:
Enter your name: sonoo jaiswal
Name is: sonoo jaiswal
Example 2
1. import java.util.*;
2. public class ScannerClassExample1 {
3. public static void main(String args[]){
4. String s = "Hello, This is JavaTpoint.";
5. //Create scanner Object and pass string in it
44
File argument.
Method
Modifier and Method Method
Type
Example
1. import java.io.IOException;
import java.io.RandomAccessFile;
2.
3. public class RandomAccessFileExample {
4. static final String FILEPATH ="myFile.TXT";
5. public static void main(String[] args) {
6. try {
7. System.out.println(new String(readFromFile(FILEPATH, 0,
18)));
8. writeToFile(FILEPATH, "I love my country and my people",
31);
9. } catch (IOException e) {
10. e.printStackTrace();
11. }
12. }
13. private static byte[] readFromFile(String filePath, int positi
on, int size)
14. throws IOException {
15. RandomAccessFile file = new RandomAccessFile(filePath,
"r");
16. file.seek(position);
17. byte[] bytes = new byte[size];
18. file.read(bytes);
19. file.close();
20. return bytes;
21. }
52