Java Notes Unit1&2
Java Notes Unit1&2
1 Features of Java
There is given many features of java. They are also known as java buzzwords. The Java Features given below are simple
and easy to understand.
1.Simple 2.Object-Oriented 3.Platform independent 4.Secured 5.Robust
6.Architecture neutral 7.Portable 8.Dynamic 9.Interpreted 10.High Performance 11.Multithreaded
1.1 Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection in java.
1.2 Object-oriented
Object-oriented means we organize our software as a combination of different types of objects that incorporates both
data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development and maintenance by providing
some rules.
Basic concepts of OOPs are:
Object ,Class, Inheritance, Polymorphism, Abstraction, Encapsulation
1.4 Secured
Java is secured because:
No explicit pointer
Java Programs run inside virtual machine sandbox
Classloader: adds security by separating the package for the classes of the local file system from those that are imported
from network sources.
Bytecode Verifier: checks the code fragments for illegal code that can violate access right to objects.
Security Manager: determines what resources a class can access such as reading and writing to the local disk.
These security are provided by java language. Some security can also be provided by application developer through SSL,
JAAS, Cryptography etc.
1.5 Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security
problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java.
All these points makes java robust.
1.6 Architecture-neutral
There are no implementation dependent features e.g. size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit
architecture. But in java, it occupies 4 bytes of memory for both 32 and 64 bit architectures.
1.7 Portable
We may carry the java bytecode to any platform.
1.8 High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a
compiled language (e.g., C++)
1.9 Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access
files by calling the methods from any machine on the internet.
1.10 Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at
once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area. Threads are important for multi-media, Web applications etc.
The work of the Java Community under the JCP program helps to ensure Java technology's standard of stability and cross-
platform compatibility, enabling it to operate on hundreds of millions of devices, from desktop computers to consumer
electronics to industrial robots.
In detail, the procedures of the JCP are complex, but in general they follow a simple, time-proven path, of course, still
open to revision. Three introductory pages may help you understand the process and answer your initial questions:
Timeline View Take a look at the overall schedule of events for the Java Specification Request (JSR) process
Glossary The JCP is built on a specific language of its own, and here are definitions to the terms you will need to know.
The JCP has gone through many revisions for improvement since its founding on December 8, 1998. The most current and
important procedures for working with the JCP is available at The Java Community Process Program. The Java
Community Process Program page is a good reference for anyone who plans to become a JCP Member and wants to
review the process and procedures in detail. Go to JCP Procedures Overview
Just as important, the JCP program continually grows the platform's specification portfolio to meet the emerging
technology needs of developers and organizations globally who depend on Java technology.
Java Specification Requests (JSRs) are the actual descriptions of proposed and final specifications for the Java platform.
At any one time there are numerous JSRs moving through the review and approval process.
A simple way to stay up to date and track the JSRs in each stage of review is to join the Mailing List. As a Mailing List
member, you can automatically receive emails on JSRs as they move through the stages in review.
Of course, at any time, you can see a list of all JSRs, by visiting the Java Specification Requests list. Using the links near
the top of the page, you can sort the list by JSR ID number, Title, and the Spec Lead Company Name.
Variable is name of reserved area allocated in memory. In other words, it is a name of memory location. It is a
combination of "vary + able" that means its value can be changed.
3.2.1 Eight primitive datatypes supported by Java. Primitive datatypes are predefined by the language and named by a
keyword. Let us now look into the eight primitive data types in detail.
byte
Byte data type is an 8-bit signed two's complement integer. Minimum value is -128 (-2^7). Maximum value is 127
(inclusive)(2^7 -1). Default value is 0. Byte data type is used to save space in large arrays, mainly in place of integers,
since a byte is four times smaller than an integer.
Example: byte a = 100, byte b = -50
short
Short data type is a 16-bit signed two's complement integer. Minimum value is -32,768 (-2^15). Maximum value is 32,767
(inclusive) (2^15 -1). Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an
integer Default value is 0.
Example: short s = 10000, short r = -20000
int
Int data type is a 32-bit signed two's complement integer.. Minimum value is - 2,147,483,648 (-2^31). Maximum value is
2,147,483,647(inclusive) (2^31 -1). Integer is generally used as the default data type for integral values unless there is a
concern about memory.. The default value is 0
Example: int a = 100000, int b = -200000
long
Long data type is a 64-bit signed two's complement integer. Minimum value is -9,223,372,036,854,775,808(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1). This type is used when a wider range than int is
needed. Default value is 0L
Example: long a = 100000L, long b = -200000L
float
Float data type is a single-precision 32-bit IEEE 754 floating point. Float is mainly used to save memory in large arrays of
floating point numbers. Default value is 0.0f. Float data type is never used for precise values such as currency
Example: float f1 = 234.5f
double
double data type is a double-precision 64-bit IEEE 754 floating point. This data type is generally used as the default data
type for decimal values, generally the default choice. Double data type should never be used for precise values such as
currency. Default value is 0.0d
Example: double d1 = 123.4
boolean
boolean data type represents one bit of information.There are only two possible values: true and false. This data type is
used for simple flags that track true/false conditions. Default value is false
Example: boolean one = true
char
char data type is a single 16-bit Unicode character. Minimum value is '\u0000' (or 0). Maximum value is '\uffff' (or 65,535
inclusive). Char data type is used to store any character
Example: char letterA = 'A'
3.2.2 Non-primitive data types are not defined by the programming language, but are instead created by the programmer.
They are sometimes called "reference variables," or "object references," since they reference a memory location, which
stores the data. In the Java programming language, non-primitive data types are simply called "objects" because they are
created, rather than predefined. While an object may contain any type of data, the information referenced by the object
may still be stored as a primitive data type. Reference variables are created using defined constructors of the classes. They
are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example,
Employee, Puppy, etc.
Class objects and various type of array variables come under reference datatype.
Default value of any reference variable is null.
A reference variable can be used to refer any object of the declared type or any compatible type.
Example: Animal animal = new Animal("giraffe");
4. Keywords
The Java programming language has total of 50 reserved keywords which have special meaning for the compiler and cannot be
used as variable names. Following are some noteworthy points regarding Java keywords
1. const and goto are reserved words but not used.
2. true, false and null are literals, not keywords.
3. all keywords are in lower-case.
5. Scoping rule The scope of a variable defines the section of the code in which the variable is visible. As a
general rule, variables that are defined within a block are not accessible outside that block. The lifetime of a variable refers
to how long the variable exists before it is destroyed. Destroying variables refers to deallocating the memory that was
allotted to the variables when declaring it.
5.1 Instance variables
Instance variables are those that are defined within a class itself and not in any method or constructor of the class. They
are known as instance variables because every instance of the class (object) contains a copy of these variables. The scope
of instance variables is determined by the access specifier that is applied to these variables. We have already seen about
it earlier. The lifetime of these variables is the same as the lifetime of the object to which it belongs. Object once created
do not exist for ever. They are destroyed by the garbage collector of Java when there are no more reference to that
object. We shall see about Java's automatic garbage collector later on.
5.2 Argument variables
These are the variables that are defined in the header oaf constructor or a method. The scope of these variables is the
method or constructor in which they are defined. The lifetime is limited to the time for which the method keeps
executing. Once the method finishes execution, these variables are destroyed.
5.3 Local variables
A local variable is the one that is declared within a method or a constructor (not in the header). The scope and lifetime
are limited to the method itself.
One important distinction between these three types of variables is that access specifiers can be applied to instance
variables only and not to argument or local variables.
In addition to the local variables defined in a method, we also have variables that are defined in bocks life an if block and
an else block. The scope and is the same as that of the block itself.
5.4 Static Variables
In java, only class variables can be declared as static i.e. Single copy of static variable must be available to all the
objects of class and should be accessible directly by using class name.
You cannot declare a static variable within ANY method. Static variables have to be declared at a class level .
For the other (numeric) primitive types, the basic rule is that implicit conversions can be done from one type to another if the range
of values of the first type is a subset of the range of values of the second type. For example, a byte can be converted to a short, int,
long or float; a short can be converted to an int, long, float, or double, etc.
double d = 5.6;
int k = (int)d;
short s = (short)(d * 2.0);
Casting can be used to convert among any of the primitive types except boolean. Please note that casting can lose information; for
example, floating-point values are truncated when they are cast to integers.
7. Arrays
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is
created. After creation, its length is fixed.
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration,
numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
type varName[];
Where type is valid data type in java and varName is a name of an array.
To allocate space for an array element use below general form or syntax.
Where varName is the name of the array and type is a valid java type and sizespecifies the number of elements in the
array.
Above statement will create an integer of an array with ten elements that can by accessed by iarr.
Example:
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
{System.out.println(a[i]);
}}
Test it Now
Output: 10
20
70
40
50
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
class Testarray3{
public static void main(String args[]){
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Test it Now
Output:1 2 3
245
445
A Java operator is a special symbol that performs specific operation on one, two, or three operands depending upon the
type of the operator and returns a result.
Java provides a rich set of operators that are classified on two bases. First, on the basis of number of operands an
operator performs upon. Second, on the type or nature of operation an operator performs.
By first classification, Java operators can be unary, binary, or ternary. Unary operators operate on one operand e.g., ++,
and --. Binary operators operator on two operands. All arithmetic operators are example of binary operators. Third,
special type operator is ternary operator. Ternary operator operates on three operands. Java has only one ternary
operator, which is also called conditional operator. It is a combination of two symbols ? and :.
Another classification is based on the type of operation they perform. On the basis of the type of operation operators
can be classified in following categories:
Arithmetic Operators
Increment Decrement Operators
Bitwise Operators
Relational Operators
Logical Operators
Assignment Operators
Miscellaneous Operators
Java Operators Precedence and Associativity
Java operators have two properties those are precedence, and associativity. Precedence is the priority order of an
operator, if there are two or more operators in an expression then the operator of highest priority will be executed first
then higher, and then high.
if all operators in an expression have same priority? In that case the second property associated with an operator comes
into play, which is associativity. Associativity tells the direction of execution of operators that can be either left to
right or right to left. For example, in expression a = b = c = 8 the assignment operator is executed from right to left that
means c will be assigned by 8, then b will be assigned by c, and finally a will be assigned by b. You can parenthesize this
expression as (a = (b = (c = 8))).
/ division
% modulus (remainder)
5 +- addition, subtraction Left -> Right
+ string concatenation
6 << left shift Left -> Right
>> signed right shift
>>> unsigned or zero-fill right shift
7 < less than Left -> Right
<= less than or equal to
> greater than
>= greater than or equal to
instanceof reference test
8 == equal to Left -> Right
!= not equal to
9 & bitwise AND Left -> Right
10 ^ bitwise XOR Left -> Right
11 | bitwise OR Left -> Right
12 && logical AND Left -> Right
13 || logical OR Left -> Right
14 ?: conditional (ternary) Right -> Left
15 = assignment and short hand assignment Right -> Left
+= operators
-=
*=
/=
%=
&=
^=
|=
<<=
>>=
>>>=
9. Expression
An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax
of the language, that evaluates to a single value. You've already seen examples of expressions, illustrated in bold below:
int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
The data type of the value returned by an expression depends on the elements used in the expression. The expression cadence =
0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, cadence is
an int. As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String.
The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type
required by one part of the expression matches the data type of the other. Here's an example of a compound expression:
1 * 2 * 3
Operators that have a higher precedence get evaluated first. In this particular example, the order in which the expression is evaluated is
unimportant because the result of multiplication is independent of order; the outcome is always the same, no matter in which order you apply
the multiplications. When writing compound expressions, be explicit and indicate with parentheses which operators should be evaluated first.
This practice makes code easier to read and to maintain.
…
case labeln: <statementn>
default: <statement>
} // end switch
When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the
middle of the switch statement code block, you must insert a break statement, which causes the program to continue
executing after the current code block.
10.2 LOOP/ITERATION STATEMENTS
10.2.1 While Statement
The while statement is a looping construct control statement that executes a block of code while a condition is true. You
can either have a single statement or a block of code within the while loop. The loop will never be executed if the testing
expression evaluates to false. The loop condition must be a boolean expression.
The syntax of the while loop is
while (<loop condition>)
<statements>
10.2.2 Do-while Loop Statement
The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead of at the
beginning. This ensures that the loop will be executed at least once.
The syntax of the do-while loop is
do
<loop body>
while (<loop condition>);
Below is an example that demonstrates the looping construct namely do-while loop used to print numbers from 1 to 10.
public class DoWhileLoopDemo {
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This will produce the following result −
Output
10
20
Java catch block is used to handle the Exception. It must be used after the try block only.You can use multiple catch
block with a single try. Let's see the solution of above problem by java try-catch block.
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not. Java finally block follows try or catch block.
Usage of Java finally
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Test it Now
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Test it Now
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Test it Now
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
10.3.5 Assert
"assert" statements are part of the Java assertion feature introduced in Java 1.4. Java assertion feature allows developer
to put "assert" statements in Java source code to help unit testing and debugging.
An "assert" statement has the following format:
assert boolean_expression : string_expression;
When this statement is executed:
If boolean_expression evaluates to true, the statement will pass normally.
If boolean_expression evaluates to false, the statement will fail with an "AssertionError" exception.
If you are using "assert" statements in your Java program for unit testing and debugging, you need to compile and
execute the program with extra command options to use them:
Compilation - "javac -source 1.4 MyClass.java". This tells the compiler to accept source code containing assertions.
Executionn - "java -ea MyClass". This tells the JVM to not skill "assert" statements. "-ea" is the same as "-
enableassertions".
Java 5 Java 6
Java 7 Java 7
- Upgrade to JDBC 4.1 and Rowset 1.1. - Upgrade class-loader architecture: A method that frees
- XRender pipeline for Java 2D, Create new platform APIs the underlying resources, such as open files, held by a
for 6u10 graphics features, Nimbus look-and-feel for URLClassLoader
Swing, Swing JLayer component, Gervill sound - Concurrency and collections updates: A lightweight
synthesizer. fork/join framework, flexible and reusable
- Upgrade the components of the XML stack to the most synchronization barriers, transfer queues, concurrent
recent stable versions: JAXP 1.4, JAXB 2.2a, and JAX-WS linked double-ended queues, and thread-local pseudo-
2.2. random number generators.
- Enhanced MBeans." Support for dynamically-typed - Internationalization Upgrade: Upgrade on Unicode 6.0,
languages (InvokeDynamic): Extensions to the JVM, the Locale enhancement and Separate user locale and user-
Java language, and the Java SE API to support the interface locale.
implementation of dynamically-typed languages at - More new I/O APIs for the Java platform (NIO.2), NIO.2
performance levels near to that of the Java language filesystem provider for zip/jar archives, SCTP, SDP, TLS
itself 1.2 support.
- Strict class-file checking: Class files of version 51 (SE 7) - Security & Cryptography implemented Elliptic-curve
or later must be verified with the typechecking verifier; cryptography (ECC).
the VM must not fail over to the old inferencing verifier.
- Small language enhancements (Project Coin): A set of
small language changes intended to simplify common,
day-to-day programming tasks: Strings in switch
statements, try-with-resources statements, improved
type inference for generic instance creation ("diamond"),
simplified varargs method invocation, better integral
literals, and improved exception handling (multi-catch).
Enhanced for loops are simple but inflexible. They can be used when you wish to step through the elements of the array
in first-to-last order, and you do not need to know the index of the current element. In all other cases, the "standard" for
loop should be preferred.
Example: Java enhanced for loop integer array
class EnhancedForLoop {
public static void main(String[] args) {
int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example,
instead of −
Example
System.out.printf("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the
string " + "is %s", floatVar, intVar, stringVar);
You can write −
String fs;
fs = String.format("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the
string " + "is %s", floatVar, intVar, stringVar);
System.out.println(fs);
String Methods
Here is the list of methods supported by String class −
Sr.No. Method & Description
int compareTo(Object o)
2
Compares this String to another Object.
byte getBytes()
12 Encodes this String into a sequence of bytes using the platform's
default charset, storing the result into a new byte array.
int hashCode()
15
Returns a hash code for this string.
String intern()
20
Returns a canonical representation for the string object.
int length()
25
Returns the length of this string.
char[] toCharArray()
39
Converts this string to a new character array.
String toLowerCase()
40 Converts all of the characters in this String to lower case using
the rules of the default locale.
42 String toString()
String toUpperCase()
43 Converts all of the characters in this String to upper case using
the rules of the default locale.
String trim()
45 Returns a copy of the string, with leading and trailing whitespace
omitted.
1. Class Fundamentals
A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.
Syntax to declare a class:
class <class_name>{
data member;
method;
}
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or
logical (tengible and intengible). The example of integible object is banking system.
An object has three characteristics:
state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user.
But,it is used internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is
its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the
instance(result) of a class.
Simple Example of Object and Class
In this example, we have created a Student class that have two data members id and name. We are creating the object of
the Student class by new keyword and printing the objects value.
class Student1{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
Example:
Rectangle myrect1 = new Rectangle();
this statement is used to create an object we are going to break down this statement in two separate statements –
Rectangle myrect1 ;
myrect1 = new Rectangle();
First statement will just create variable myrect1 which will store address of actual object.First Statement will not allocate
any physical memory for an object . Second Statement will create actual object ranndomly at any memory address where
it found sufficient memory.Actual memory address of Object is stored inside myrect1.
A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized
with a variable, either the variable name or the reference name may be used to refer to the variable.
Note: Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed
in when the method is invoked. When you invoke a method, the arguments used must match the declaration's
parameters in type and order.
Parameter Types
You can use any data type for a parameter of a method or a constructor. This includes primitive data types, such as
doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as objects and
arrays.
Here's an example of a method that accepts an array as an argument. In this example, the method creates a
new Polygon object and initializes it from an array of Point objects (assume that Point is a class that represents an x, y
coordinate):
public Polygon polygonFrom(Point[] corners) {
// method body goes here
}
The terms "arguments" and "parameters" are used interchangeably; they mean the same thing. We use the term formal
parameters to refer to the parameters in the definition of the method. In the example that follows, x and y are the formal
parameters.
We use the term actual parameters to refer to the variables we use in the method call. In the following example, length
and width are actual parameters.
// Method definition
public int mult(int x, int y)
{
return x * y;
}
Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses
Unicode and therefore can be internationalized.
These two abstract classes have several concrete classes that handle various devices such as disk files, network
connection etc.
DataOutputStream An output stream that contain method for writing java standard data type
These two abstract classes have several concrete classes that handle unicode character.
Reading Console Input:We use the object of BufferedReader class to take inputs from the keyboard.
Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns integer type value has we
need to use typecasting to convert it into char type.
int read() throws IOException
Below is a simple example explaining character input.
class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}
Reading Strings
To read string we have to use readLine() function with BufferedReader class's object.
String readLine() throws IOException
import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}
}
}
12
13 String passport = console.readLine("Enter your %d (th) passport number: ", 2);
Advantages:
1.Reading password without echoing the entered characters.
2. Reading methods are synchronized.
3. Format string syntax can be used.
Drawbacks:
Does not work in non-interactive environment (such as in an IDE).
Combined Example Program
For your convenient and reference purpose, we combine the above code snippet into a demo program whose source
code looks like this:
package net.codejava.io;
import java.io.*;
import java.util.*;
// using InputStreamReader
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
// using Scanner
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your nationality: ");
String nationality = scanner.nextLine();
System.out.println("Your nationality is: " + nationality);
// using Console
Console console = System.console();
if (console == null) {
System.out.println("No console: not in interactive mode!");
System.exit(0);
}
System.out.print("Enter your username: ");
String username = console.readLine();
System.out.print("Enter your password: ");
char[] password = console.readPassword();
System.out.println("Thank you!");
System.out.println("Your username is: " + username);
System.out.println("Your password is: " + String.valueOf(password));
class WriteConsoleOutput
{
public static void main(String args[])
{
int y;
y = 'X';
System.out.write(y);
System.out.write('\n');
}
}
This Java program will produce the following output:
You will not often use write() to perform console output (although doing so might be useful in some situations)
because print() and println() are substantially easier to use.
The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these
streams represent an input source and an output destination. The stream in the java.io package supports many data such
as primitives, object, localized characters, etc.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
InPutStream − The InputStream is used to read data from a source.
OutPutStream − The OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to files and networks but this tutorial covers very basic
functionality related to streams and I/O. We will see the most commonly used examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte
streams but the most frequently used classes are, FileInputStream andFileOutputStream. Following is an example which
makes use of these two classes to copy an input file into an output file −
Example
import java.io.*;
public class CopyFile {
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating output.txt file with the same
content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to
perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most
frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter
uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes
two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode
characters) into an output file −
Example
import java.io.*;
public class CopyFile {
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating output.txt file with the same
content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program can take input from a
keyboard and then produce an output on the computer screen. If you are aware of C or C++ programming languages,
then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similarly, Java provides the following
three standard streams −
Standard Input − This is used to feed the data to user's program and usually a keyboard is used as standard input stream
and represented as System.in.
Standard Output − This is used to output the data produced by the user's program and usually a computer screen is used
for standard output stream and represented as System.out.
Standard Error − This is used to output the error data produced by the user's program and usually a computer screen is
used for standard error stream and represented as System.err.
Following is a simple program, which createsInputStreamReader to read standard input stream until the user types a "q"
−
Example
import java.io.*;
public class ReadConsole {
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Let's keep the above code in ReadConsole.java file and try to compile and execute it as shown in the following program.
This program continues to read and output the same character until we press 'q' −
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
Reading and Writing Files
As described earlier, a stream can be defined as a sequence of data. The InputStream is used to read data from a source
and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.
The two important streams are FileInputStream andFileOutputStream, which would be discussed in this tutorial.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the keyword new and there are several
types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First we create a file object
using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or
to do other operations on the stream.
Sr.No. Method & Description
try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();
File APIs in NIO2 constitute one of the major new functional areas of the Java Platform that shipped with Java 7,
specifically a subset of the new file system API alongside Path APIs .
4.1 Setup
Setting up your project to use File APIs is just a matter of making this import:
1 import java.nio.file.*;
Since the code samples in this article will probably be running in different environments, let’s get a handle on the home
directory of the user, which will be valid across all operating systems:
private static String HOME = System.getProperty("user.home");
The Files class is one of the primary entry points of the java.nio.file package. This class offers a rich set of APIs for
reading, writing, and manipulating files and directories. The Files class methods work on instances of Path objects.
4.2 Checking a File or Directory
We can have a Path instance representing a file or a directory on the file system. Whether that file or directory it’s
pointing to exists or not, is accessible or not can be confirmed by a file operation.
For the sake of simplicity, whenever we use the term file, we will be referring to both files and directories unless stated
explicitly otherwise.
To check if a file exists, we use the exists API:
1 @Test
2 public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
3 Path p = Paths.get(HOME);
4
5 assertTrue(Files.exists(p));
6 }
To check that a file does not exist, we use the notExists API:
We can also check if a file is a regular file like myfile.txt or is just a directory, we use the isRegularFile API. There are
also static methods to check for file permissions. To check if a file is readable, we use the isReadable API: To check if it
is writable, we use the isWritable API: to check if it is executable: we use the isExecutable API. Creating Files
The file system API provides single line operations for creating files. To create a regular file, we use thecreateFile API
and pass to it a Path object representing the file we want to create.
All the name elements in the path must exist, apart from the file name, otherwise, we will get anIOException:
1 @Test
2 public void givenFilePath_whenCreatesNewFile_thenCorrect() {
3 String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
4 Path p = Paths.get(HOME + "/" + fileName);
5 assertFalse(Files.exists(p));
6
7 Files.createFile(p);
8
9 assertTrue(Files.exists(p));
10 }
In the above test, when we first check the path, it is inexistent, then after the createFile operation, it is found to be
existent.
To create a directory, we use the createDirectory API:
Deleting a File
To delete a file, we use the delete API. For clarity purpose, the following test first ensures that the file does not already
exist, then creates it and confirms that it now exists and finally deletes it and confirms that it’s no longer existent:
You can copy a file or directory by using the copy API: Files.copy(file1, file2);
You can move a file or directory by using the move API. It is in most ways similar to the copy operation. If the copy
operation is analogous to a copy and paste operation in GUI based systems, then move is analogous to a cut and
paste operation: Files.move(file1, file2);
6. Constructors
Constructor in java is a special type of method that is used to initialize the object.Java constructor is invoked at the time
of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
Default constructor (no-arg constructor)
Parameterized constructor
7. This Keyword
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
this keyword can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
this keyword can be used to invoke current class method (implicitly)
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this keyword can also be used to return the current class instance.
The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
class Student10{
int id;
String name;
Output:111 Karan
222 Aryan
2) this() can be used to invoked current class constructor.
The this() constructor call can be used to invoke the current class constructor (constructor chaining). This approach is
better if you have many constructors in the class and want to reuse that constructor.
//Program of this() constructor call (constructor chaining)
class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:Hello java
obj.m();
}
}
Output:A5@22b3ea59
A5@22b3ea59
8. Garbage Collector
In Java destruction of object from memory is done automatically by the JVM. When there is no reference to an object,
then that object is assumed to be no longer needed and the memory occupied by the object are released. This technique is
called Garbage Collection. This is accomplished by the JVM. Unlike C++ there is no explicit need to destroy object.
the Garbage Collection can not be forced explicitly. We may request JVM for garbage collection by
calling System.gc() method. But This does not guarantee that JVM will perform the garbage collection.
gc() Method
gc() method is used to call garbage collector explicitly. However gc() method does not guarantee that JVM will perform
the garbage collection. It only request the JVM for garbage collection. This method is present
inSystem and Runtime class.
9. finalize() method
Sometime an object will need to perform some specific task before it is destroyed such as closing an open connection or
releasing any resources held. To handle such situation finalize() method is used. finalize()method is called by garbage
collection thread before collecting object. Its the last chance for any object to perform cleanup utility.
Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created
any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).
}
}
Test it Now
Output:30
40
2) Example of Method Overloading by changing data type of argument
In this example, we have created two overloaded methods that differs in data type. The first sum method receives two
integer arguments and second sum method receives two double arguments.
class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
public static void main(String args[]){
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
Test it Now
Output:21.0
40
Why Method Overloading is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity.
Let's see how ambiguity may occur:
because there was problem:
class Calculation3{
int sum(int a,int b){System.out.println(a+b);}
}
}
Test it Now
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
class Rectangle {
int length;
int width;
Rectangle(int l, int b) {
length = l;
width = b;
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}
}
Explanation :
We can pass Object of any class as parameter to a method in java.
We can access the instance variables of the object passed inside the called method.
area = r1.length * r1.width
It is good practice to initialize instance variables of an object before passing object as parameter
to method otherwise it will take default initial values.
Different Ways of Passing Object as Parameter :
Way 1 : By directly passing Object Name
void area(Rectangle r1) {
int areaOfRectangle = r1.length * r1.width;
System.out.println("Area of Rectangle : "
+ areaOfRectangle);
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}
Way 2 : By passing Instance Variables one by one
package com.pritesh.programs;
class Rectangle {
int length;
int width;
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
r1.length = 20;
r1.width = 10;
r2.area(r1.length, r1.width);
}
}
Actually this is not a way to pass the object to method. but this program will explain you how to
pass instance variables of particular object to calling method.
Way 3 : We can pass only public data of object to the Method.
Suppose we made width variable of a class private then we cannot update value in a main
method since it does not have permission to access it.
private int width;
after making width private –
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
r1.length = 20;
r1.width = 10;
r2.area(r1.length, r1.width);
}
}
package com.pritesh.programs;
import java.io.File;
import java.io.IOException;
class Rectangle {
int length;
int breadth;
Rectangle(int l,int b) {
length = l;
breadth = b;
}
Rectangle getRectangleObject() {
Rectangle rect = new Rectangle(10,20);
return rect;
}
}
class RetOb {
public static void main(String args[]) {
Rectangle ob1 = new Rectangle(40,50);
Rectangle ob2;
ob2 = ob1.getRectangleObject();
System.out.println("ob1.length : " + ob1.length);
System.out.println("ob1.breadth: " + ob1.breadth);
}
}
Output of the Program :
ob1.length : 40
ob1.breadth: 50
ob2.length : 10
ob2.breadth: 20
Explanation :
In the above program we have called a method getRectangleObject() and the method creates object of class
from which it has been called.
All objects are dynamically allocated using new, you don’t need to worry about an object going out-of-scope because
the method in which it was created terminates.
The object will continue to exist as long as there is a reference to it somewhere in your program. When there are no
references to it, the object will be reclaimed the next time garbage collection takes place.
13. Recursion
Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called
recursive method.
It makes the code compact but complex to understand.
Syntax:
returntype methodname(){
//code to be executed
}
}
Test it Now
Output:Compile Time Error
final method is inherited but you cannot override it.
class Student8{
int rollno;
String name;
static String college ="ITS";
s1.display();
s2.display();
}
}
Test it Now
Output:111 Karan ITS
222 Aryan ITS
Counter(){
count++;
System.out.println(count);
}
}
}
Test it Now
Output:1
1
1
Counter2(){
count++;
System.out.println(count);
}
}
}
Test it Now
Output:1
2
3
class Student9{
int rollno;
String name;
static String college = "ITS";
16.1 Inner class are defined inside the body of another class (known as outer class). These classes can have access
modifier or even can be marked as abstract and final. Inner classes have special relationship with outer class instances.
This relationship allows them to have access to outer class members including private members too.
Inner classes can be defined in four different following ways as mentioned below:
1) Inner class
2) Method – local inner class
3) Anonymous inner class
4) Static nested class
1) Inner class
An inner class is declared inside the curly braces of another enclosing class. Inner class is coded inside a Top level class as
shown below:-
//Top level class definition
class MyOuterClassDemo {
private int myVar= 1;
}
2) Method–Local inner classes
A method local inner class is defined within a method of the enclosing class. If you want to use inner class , you must
instantiate the inner class in the same method, but after the class definition code. Only two modifiers are allowed for
method-local inner class which are abstract and final.The inner class can use the local variables of the method (in which it
is present), only if they are marked final.
//Top level class definition
class MyOuterClassDemo {
private int x= 1;
Example:
class Outer{
static class Nested{}
}
A static nested class can be instantiated like this:
class Outer{// outer class
static class Nested{}// static nested class
}
class Demo{
public static void main(string[] args){
// use both class names
Outer.Nested n= new Outer.Nested();
}
}
16.2 Nested Class
A class within another class is known as Nested class. The scope of the nested is bounded by the scope of its enclosing
class.
class Inner
{
class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}
Output :
Inside inner
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc
In java, string is basically an object that represents sequence of char values. An array of characters works same as java
string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(),
length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
3) String class overrides the equals() method of Object class. So you StringBuffer class doesn't override the
can compare the contents of two strings by equals() method. equals() method of Object class.
System.out.println(e.getName());
}}
Note: There are two ways to provide values to the object, one way is by constructor and second is by setter method.
JavaBean Property Naming Rules
If the property is not a boolean, the getter method's prefix must be get. For example, getSize()is a valid JavaBeans getter
name for a property named "size." Keep in mind that you do not need to have a variable named size (although some IDEs
expect it).
The name of the property is inferred from the getters and setters, not through any variables in your class. What you return
from getSize() is up to you.
If the property is a boolean, the getter method's prefix is either get or is. For example, getStopped() or isStopped() are
both valid JavaBeans names for a boolean property.
The setter method's prefix must be set. For example, setSize() is the valid JavaBean name for a property named size.
To complete the name of a getter or setter method, change the first letter of the property name to uppercase, and then
append it to the appropriate prefix (
get, is, or set).
Setter method signatures must be marked
public, with a void return type and an argument that represents the property type.
Getter method signatures must be marked
public, take no arguments, and have a return type that matches the argument type of the setter method for that property.
JavaBean Listener Naming Rules
Listener method names used to "register" a listener with an event source must use the prefix
add, followed by the listener type. For example, addActionListener() is a valid name for a method that an event source
will have to allow others to register for Action events.
Listener method names used to remove ("unregister") a listener must use the prefix
remove, followed by the listener type (using the same rules as the registration add method).
The type of listener to be added or removed must be passed as the argument to the method.
Listener method names must end with the word "Listener".
Examples of valid JavaBean method signatures are
public void setMyValue(int v)
public int getMyValue()
public boolean isMyStatus()
public void addMyListener(MyListener m)
public void removeMyListener(MyListener m)
Examples of invalid JavaBean method signatures are
void setCustomerName(String s) // must be public
public void modifyMyValue(int v) // can't use 'modify'
public void addXListener(MyListener m) // listener type mismatch
Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable,
constant, method etc.
But, it is not forced to follow. So, it is known as convention not rule.
All the classes, interfaces, packages, methods and fields of java programming language are given according to java
naming convention.
Advantage of naming conventions in java
By using standard Java naming conventions, you make your code easier to read for yourself and for other programmers.
Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.
Name Convention
class name should start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread etc.
interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc.
method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.
constants name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.