Unit 01 JAVA FUNDAMENTALS
Unit 01 JAVA FUNDAMENTALS
UNIT I
JAVA FUNDAMENTALS
An Overview of Java - Data Types, Variables, and Arrays – Operators - Control Statements –
Class Fundamentals – Declaring objects – Methods – Constructors – this keyword -
Overloading methods - Overloading constructors - Access Control – Static – Final.
7
1.16 Static Keyword
3
7
1.17 Final Keyword
5
7
Java Reserved Keywords
7
What is a Program?
A program is a set of instructions that a computer uses to perform a specific function.
A program is a collection of instructions that performs a specific task when executed
by a computer.
A program must be written in a programming language.
Definition of Java:
• Java is simple yet powerful, general purpose, Object Oriented, platform
independent, high level programming language.
Editions of Java
Java Standard Edition (Java SE)
o For building core java applications.
Java Enterprise Edition (Java EE)
o For building distributed java applications.
Java Micro Edition (Java ME)
o Developed to easily create mobile and embedded device applications.
JavaFX (Java special EFF-ECTS)
5. Execute: Java Virtual Machine uses a combination of interpretation and just in time
compilation to translate bytecodes into machine language. Applications are run on
user's machine, i.e., executed by interpreter with java command (java Welcome).
1. Documentation Section
It is used to improve the readability of the program.
It consists of comments in Java which include basic information such as the method’s
usage or functionality to make it easier for the programmer to understand it while
reviewing or debugging the code.
A Java comment is not necessarily limited to a confined space, it can appear anywhere
in the code.
The compiler ignores these comments during the time of execution and is solely
meant for improving the readability of the Java program.
There are three types of comments that Java supp orts
• Single line Comment: Single line comments can be written using
// Single line Comment
• Multi line Comment: Block comments are used to provide descriptions of files,
methods, data structures and algorithms. Block comments may be used at the
beginning of each file and before each method
R.M.K. College of Engineering and Technology 4
22CS202 Java Programming
/*
Here is a block comment
*/
• Documentation Comment: The JDK javadoc tool uses doc comments when
preparing automatically generated documentation.
/**
documentation comments
*/
2. Package Statement
Java that allows you to declare your classes in a collection called package.
There can be only one package statement in a Java program and it must be at the
beginning of the code before any class or interface declaration.
This statement is optional, for example, look at the statement below
package student;
3. Import Statement
Many predefined classes are stored in packages in Java, an import statement is used to
refer to the classes stored in other packages.
An import statement is always written after the package statement but it must be
before any class declaration, we can import a specific class or classes in an import
statement.
4. Interface Section
This section is used to specify an interface in Java.
It is an optional section which is mainly used to implement multiple inheritance in
Java.
An interface is a lot like a class in Java but it contains only constants and method
declarations.
5. Class Definition
A Java program may contain several class definitions, classes are an essential part of
any Java program.
It defines the information about the user defined classes in a program.
A class is a collection of variables and methods that operate on the fields.
Every program in Java will have at least one class with the main method.
String[] args
It is an array where each element is a string, which is named as args.
If you run the Java code through a console, you can pass the input parameter.
The main() takes it as an input.
System.out.println()
The statement is used to print the output on the screen where the system is a
predefined class, out is an object of the PrintWriter class.
The method println prints the text on the screen with a new line.
All Java statements end with a semicolon.
} //end of block
IDE Execution
Many Integrated Development Environment (IDE) are available, that helps in development
and execution of Java applications For E.g., Eclipse, JCreator, CodeBlocks, etc.
Refer: https://www.youtube.com/watch?v=jGAb70JyEQI
1. Download and Install IDE(Netbeans) and JDK (Refer:
https://www.eclipse.org/downloads/)
2. Open a new Java Project using the IDE.
3. Open a new class.
4. Add main method.
5. Compile and run using menus.
Online Compilers
Many online compilers are available for practicing Java program, which are simple to use.
1. https://www.onlinegdb.com/online_java_compiler
2. https://www.tutorialspoint.com/compile_java_online.php
3. https://compiler.javatpoint.com/opr/online java_compiler.jsp
4. https://www.jdoodle.com/online java compiler/
5. https://www.codechef.com/ide
C++ vs Java
Comparison
C++ Java
Index
Platform- C++ is platform- Java is platform-independent.
independent dependent.
Mainly used C++ is mainly used for Java is mainly used for application
for system programming. programming.
Goto C++ supports Java does not support the goto statement.
the goto statement.
Multiple C++ supports multiple Java does not support multiple inheritance
inheritance inheritance. through class. It can be achieved by
using interfaces in java.
Operator C++ supports operator Java does not support operator
Overloading overloading. overloading.
Pointers C++ supports pointers. Java supports pointer internally.
Compiler and C++ uses compiler only. Java uses both compiler and interpreter.
Interpreter
Call by Value C++ supports both call by Java supports call by value only. There is
and Call by value and call by no call by reference in java.
reference reference.
Structure and C++ supports structures Java does not support structures and
Union and unions. unions.
Thread C++ does not have built-in Java has built-in thread support.
Support support for threads.
Pros and Cons of Java programming.
7. Licensing concerns: While Java itself is open-source, some third-party libraries and
frameworks used in Java development may have different licensing requirements that
developers need to be aware of.
Java Tokens
In Java programming, tokens are the smallest individual units of a program. They are the
building blocks of the language and are categorized into several types. The different types of
Java tokens in detail:
1. Keywords: Keywords are reserved words in Java that have predefined meanings and
cannot be used as identifiers (variable names, class names, etc.). Some examples of
keywords in Java include class, public, static, void, if, else, while, and return.
2. Identifiers: Identifiers are used to name classes, variables, methods, and other
program entities. They are user-defined and follow certain rules. An identifier must
start with a letter, underscore (_), or dollar sign ($), and can be followed by letters,
digits, underscores, or dollar signs.
3. Literals: Literals represent constant values in a program. They can be of various
types:
a. Integer literals: Examples include 0, 10, and -5. They represent whole
numbers.
b. Floating-point literals: Examples include 3.14, 1.0, and -2.5. They represent
decimal numbers.
c. Character literals: Represented within single quotes (''), such as 'a', '1', or '\n'.
They represent individual characters.
d. String literals: Represented within double quotes (""), such as "Hello", "Java",
or "42". They represent a sequence of characters.
e. Boolean literals: The two Boolean literals are true and false. They represent
logical values.
4. Operators: Java includes various operators for performing different operations.
Examples of operators include arithmetic operators (+, -, *, /, %), assignment
operators (=, +=, -=, *=, /=), comparison operators (==, !=, <, >, <=, >=), logical
operators (&&, ||, !), and more.
5. Separators: Separators are used to separate different parts of a Java program.
Common separators include parentheses (), curly braces {}, square brackets [],
comma,, semicolon ;, period ., and colon :.
6. Comments: Comments are used to add explanatory notes within the code. They are
ignored by the compiler and are not executed. Java supports two types of comments:
a. Single-line comments: Denoted by //. Anything written after // on the same
line is considered a comment.
b. Multi-line comments: Denoted by /* at the beginning and */ at the end.
Anything between these symbols is treated as a comment, even if it spans
multiple lines.
7. Whitespace: Whitespace refers to spaces, tabs, and newlines that separate tokens in a
program. It is used for formatting and readability purposes. Whitespace is generally
ignored by the Java compiler.
Keywords
A Java keyword is one of 50 reserved terms that have a special function and a set
definition in the Java programming language.
The fact that the terms are reserved means that they cannot be used as identifiers for
any other program elements, including classes, subclasses, variables, methods,
and objects.
abstract continue for new switch
*** *
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** Instance return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
*
const float native super while
Object
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual
object.
Class does not consume any space.
Class declaration is required to define a valid Java class file.
Inheritance
When one object acquires all the properties and behaviours of a parent object, it is
known as inheritance.
It provides code reusability.
It is used to achieve runtime polymorphism.
Polymorphism
Abstraction
Hiding internal details and showing functionality is known as abstraction.
In the abstraction concept, we do not show the actual implementation to the end user,
instead we provide only essential things.
For example, phone call, we do not know the internal processing.
In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation.
Execution Flow
1.2.2 Variables
Java is a statically typed programming language. It means, all variables must be
declared before its use. Java is also a strictly typed language.
A variable is a container that holds the value while the Java program is executed.
A variable is assigned with a data type.
Variable is a name of a memory location.
There are three types of variables in java: local, instance, and static.
Variable declaration
Types:
All variables must have a type.
Primitive types such as int, float, boolean, etc. Or you can use reference types, such as
strings, arrays, or objects.
Example:
public class VariableDemo {
int data = 50; // instance variable
// static variable
static final int MAXIMUM_DATA = 100;
void method() {
int currentData = 90; // local variable
}
}// end of class
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared.
//Demonstrate dynamic initialization
class DynInit{
public static void main(String[] args){
double a=3.0, b=4.0;
//c is dynamically initialized
double c = Math.sqrt( a*a + b*b);
System.out.println("Hypotenuse is" +c);
}
}
Here, three local variables a, b, and c are declared. The first two, a and b, are initialized by
constants. However, c is initialized dynamically to the length of the hypotenuse.
{
int data=50; //instance variable
static int m=100; //static variable
void method()
{
int n=90; //local variable
System.out.println(n);
}
public static void main(String args[])
{
A a=new A();
System.out.println(a.data);
System.out.println(m);
a.method();
}
}//end of class
1.2.3 Identifiers
All Java variables must be identified with unique names. These unique names are
called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
It is recommended to use descriptive names to create understandable and maintainable
code:
Example
int minutesPerHour = 60;
int m = 60;
Assign an int value to a byte variable. A byte is smaller than an int. This kind of conversion is
sometimes called a narrowing conversion. Remainder of the number division 256 will be
stored as byte.
Type Promotion: One operand in expression is float entire expression is promoted as float. If
one operand is long, whole expression is promoted to long.
1.3 Operators
Operators are the symbols used to perform specific operations.
Various operators can be used for different purposes.
1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication, and division.
Operator Description
+ Additive operator (also used for string concatenation)
- Subtractive operator
* Multiplication operator
/ Division operator
% Modulus operator
Example
class Welcome
{
public static void main(String args[])
{
int numOne = 10;
int numTwo = 5;
System.out.println(numOne + numTwo); //Output will be 15
System.out.println(numOne - numTwo); //Output will be 5
System.out.println(numOne * numTwo); //Output will be 50
System.out.println(numOne / numTwo); //Output will be 2
System.out.println(numOne % numTwo); //Output will be 0
}
}
2. Logical Operators
Logical operators are used to combine two or more relational expressions or to negate the
result of a relational expression.
Assume A and B to be two relational expressions. The below tables show the result
for various logical operators based on the value of expressions, A and B.
3. Unary Operators
Unary operators act upon only one operand and perform operations such as increment,
decrement, negating an expression, or inverting a Boolean value.
Example
class Welcome
{
public static void main(String args[])
{
int numOne = 10;
int numTwo = 5;
boolean isTrue = true;
System.out.println(numOne++ + " " + ++numOne); //Output will be 10 12
System.out.println(numTwo-- + " " + --numTwo); //Output will be 5 3
System.out.println(!isTrue + " " + ~numOne); //Output will be false -13
}
}
4. Assignment Operator
The assignment operator is used to assign the value on the right-hand side to the variable on
the left-hand side of the operator. Some of the assignment operators are given below:
Operato
Description
r
Example
class Welcome
{
public static void main(String args[])
{
int numOne = 10; //The value 10 is assigned to numOne
System.out.println(numOne); //Output will be 10
numOne += 5;
System.out.println(numOne); //Output will be 15
numOne -= 5;
System.out.println(numOne); //Output will be 10
numOne *= 5;
System.out.println(numOne); //Output will be 50
numOne /= 5;
System.out.println(numOne); //Output will be 10
}
}
5. Ternary Operator
The ternary operator is used as a single-line replacement for if-then-else statements and acts
upon three operands.
Syntax:
<condition> ? <value if condition is true> : < value if condition is false>
Example
class Welcome
{
public static void main(String args[])
{
int numOne = 10;
int numTwo = 5;
int min = (numOne < numTwo) ? numOne : numTwo;
System.out.println(min); //Output will be 5
}
}
Here, first the condition (numOne < numTwo) is evaluated. The result is false and hence, min
will be assigned the value numTwo.
6. Relational operators
Relational operators are used to compare two values.
The result of all the relational operations is either true or false.
Operato Description
r
== Equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
Example
class Welcome
{
public static void main(String args[])
{
int numOne = 10;
int numTwo = 5;
System.out.println(numOne > numTwo); //Output will be true
}
}
7. Bitwise Operators
Bitwise operators are used to perform manipulation of individual bits of a number.
Let us understand how to convert a decimal number to a binary number and vice versa. The
decimal or the base 10 number system is used in everyday life but the binary number system
is the basis for representing data in computing systems.
2 25
2 1 1
2
2 6 0
2 3 0
2 1 1
0 1
The decimal number is equal to the sum of binary digits (dn) times their power of 2 (2n).
24 = 16 23 = 8 22 = 4 21 = 2 20 = 1
1 1 0 0 1
16 + 8 + 0 + 0 + 1 = 25
Bitwise OR (|)
It returns bit by bit OR of the input values.
If either of the bits is 1, then it gives 1, else it gives 0.
E.g. - The output of 10<<1 is 20 if the numbers are stored in a 32-bit system.
After left shifting by 1 bit, the result becomes 00000000 00000000 00000000 000010100
which is 20.
After right shifting by 1 bit, the result becomes 00000000 00000000 00000000 00000101
which is 5.
Example of a negative number
After right shifting by 1 bit, the result becomes 11111111 11111111 11111111 11111011 which
is -5.
After right shifting by 1 bit, the result becomes 00000000 00000000 00000000 00000101
which is 5.
Example of a negative number
After right shifting by 1 bit, the result becomes 01111111 11111111 11111111 11111011 which
is 214783643.
8. Shift Operators
Java Shift Operators are also a part of bitwise operators. There are the following types of shift
operators.
Left Shift - Shifts the bits of the number two places to the left and fills the voids with
0’s.
Right Shift - Shifts the bits of the number two places to the right and fills the voids
with 0’s The sign of the number decides the value of the left bit.
Unsigned Right Shift - It is also the same as the right shift however it changes the
leftmost digit’s value to 0.
9. instanceOf Operator
/= Division assignment
%= Modulus assignment
Advantages of Operators
1. Expressiveness: Operators in Java provide a concise and readable way to perform
complex calculations and logical operations.
2. Time-Saving: Operators in Java save time by reducing the amount of code required
to perform certain tasks.
3. Improved Performance: Using operators can improve performance because they are
often implemented at the hardware level, making them faster than equivalent Java
code.
Disadvantages of Operators
1. Operator Precedence: Operators in Java have a defined precedence, which can lead
to unexpected results if not used properly.
2. Type Coercion: Java performs implicit type conversions when using operators, which
can lead to unexpected results or errors if not used properly.
3. Overloading: Java allows for operator overloading, which can lead to confusion and
errors if different classes define the same operator with different behavior.
Expression Types
Infix Expression
o The expression in which the operator is used between operands is called infix
expression.
Postfix Expression
o The expression in which the operator is used after operands is called postfix
expression.
Prefix Expression
o The expression in which the operator is used before operands is called a prefix
expression.
if statement
In java, we use the if statement to test a condition and decide the execution of a block
of statements based on that condition result.
The if statement checks, the given condition then decides the execution of a block of
statements.
If the condition is True, then the block of statements is executed and if it is False, then
the block of statements is ignored.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
Example
public class Main
{
public static void main(String[] args)
{
int x = 20;
int y = 18;
if (x > y)
{
System.out.println("x is greater than y"); // Output : x is greater than y
}
}
}
Flow of execution
if-else statement
In java, we use the if-else statement to test a condition and pick the execution of a
block of statements out of two blocks based on that condition result.
The if-else statement checks the given condition then decides which block of
statements to be executed based on the condition result.
If the condition is True, then the true block of statements is executed and if it is False,
then the false block of statements is executed.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is false
}
Output
Enter the Two Numbers:
10 12
Flow of execution
if...else if Statement
To evaluate more than one conditions at the same time, you can use else if statement
in Java.
Multi selection enables the developer to determine the actions that must be
accomplished in certain conditions by imposing a requisite.
We can combine an else and an if to make an else if and test a whole range of
mutually exclusive possibilities.
Syntax
if (condition1)
{
// block of code to be executed if condition1 is true
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is true
}
else
{
// block of code to be executed if the condition1 is false and condition2 is false
}
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}
Output: C grade
Nested if statement
The nested if statement represents the if block within another if block.
Here, the inner if block condition executes only when the outer if block condition is
true.
Syntax
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}
Example
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number: ");
int num=sc.nextInt();
if( num < 100 )
{
System.out.println("The entered number is less than 100");
if(num > 50)
{
System.out.println("The entered number is greater than 50");
}
}
else
{
System.out.println("The entered number is greater than 100");
}
}
}
Output
Enter a number: 67
The entered number is less than 100
The entered number is greater than 50
switch statement
Using the switch statement, one can select only one option from a greater number of
options very easily.
In the switch statement, we provide a value that is to be compared with a value
associated with each option.
Whenever the given value matches the value associated with an option, the execution
starts from that option.
In the switch statement, every option is defined as a case.
Syntax
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
Flow of execution
Example
public class Main
{
public static void main(String[] args)
{
int day = 4;
switch (day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
}
}
Output: Thursday
for statement
The for statement is used to execute a single statement or a block of statements
repeatedly if the given condition is TRUE.
Syntax
for(initialization; condition; increment/decrement)
{
//statement or code to be executed
}
A simple for loop is the same as C/C++. We can initialize the variable, and check the
condition and increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition that is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is
an optional condition.
2. Condition: It is the second condition that is executed each time to test the condition
of the loop. It continues execution until the condition is false. It must return a Boolean
value of either true or false. It is an optional condition.
3. Increment/Decrement: Increments or decrements the variable value. It is an optional
condition.
4. Statement: The statement of the loop is executed each time until the second condition
is false.
{
int sum = 0;
int n = 1000;
// for loop
for (int i = 1; i <= n; ++i)
{
// body inside for loop
sum += i; // sum = sum + i
}
System.out.println("Sum = " + sum);
}
}
Output
Enter a number: 23
5
Flow of execution
for-each statement
The Java for-each statement was introduced since Java 5.0 version.
It provides an approach to traverse through an array or collection in Java.
The for-each statement also known as enhanced for statement.
The for-each statement executes the block of statements for each element of the given
array or collection.
Syntax
for(datatype variablename : Array)
{
//block of statement
}
statement after for
Example
public class ForEachTest {
public static void main(String[] args) {
int[] arrayList = {10, 20, 30, 40, 50};
for(int i : arrayList) {
System.out.println("i = " + i);
}
System.out.println("Statement after for-each!");
}
}
Flow of execution
while statement
The while statement is used to execute a single statement or block of statements
repeatedly if the given condition is TRUE.
The while statement is also known as Entry control looping statement.
Syntax:
while (condition)
{
//code to be executed
Increment/decrement statement
}
Output
Enter the number: 3
The multiplication table of 3 is:
3*1=3
3*2=6
3*3=9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
Flow of execution
do-while statement
The do-while statement is used to execute a single statement or block of statements
repeatedly if given the condition is TRUE.
The do-while statement is also known as the Exit control looping statement.
Syntax
do
{
//code to be executed / loop body
//update statement
}while (condition);
Example
public class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
Output
1
2
3
4
5
6
7
8
9
10
Flow of execution
break statement
The break statement in java is used to terminate a switch or looping statement.
That means the break statement is used to come out of a switch statement and a
looping statement like while, do-while, for, and for-each.
Syntax
jump-statement;
break;
Example
public class BreakExample
{
public static void main(String[] args)
{
//using for loop
for(int i=1;i<=10;i++)
{
if(i==5)
{
//breaking the loop
R.M.K. College of Engineering and Technology 43
22CS202 Java Programming
break;
}
System.out.println(i);
}
}
}
Output
1
2
3
4
Flow of execution
continue statement
The continue statement is used to move the execution control to the beginning of the
looping statement.
When the continue statement is encountered in a looping statement, the execution
control skips the rest of the statements in the looping block and directly jumps to the
beginning of the loop.
The continue statement can be used with looping statements like while, do-while, for,
and for-each.
When we use continue statement with while and do-while statements, the execution
control directly jumps to the condition.
When we use continue statement with for statement the execution control directly
jumps to the modification portion (increment/decrement/any modification) of the for
loop.
Syntax
jump-statement;
continue;
Flow of execution
Example
public class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}
Output
1
2
3
4
6
7
8
9
10
Example
import java.util.Scanner;
public class JavaLabelledStatement {
public static void main(String args[]) {
Scanner read = new Scanner(System.in);
reading: for (int i = 1; i <= 3; i++) {
System.out.print("Enter an even number: ");
int value = read.nextInt();
verify: if (value % 2 == 0) {
System.out.println("\nYou won!!!");
System.out.println("Your score is " + i*10 + " out of 30.");
break reading;
} else {
System.out.println("\nSorry try again!!!");
System.out.println("You let with " + (3-i) + " more options...");
continue reading;
}
}
}
}
return statement
In java, the return statement used to terminate a method with or without a value.
The return statement takes the execution control to the calling function.
That means the return statement transfer the execution control from called function to
the calling function by carrying a value.
In java, the return statement used with both methods with and without return type.
In the case of a method with the return type, the return statement is mandatory, and it
is optional for a method without return type.
When a return statement used with a return type, it carries a value of return type.
But, when it is used without a return type, it does not carry any value.
Instead, simply transfers the execution control.
Following are the important points must remember while returning a value:
1. The return type of the method and type of data returned at the end of the method
should be of the same type. For example, if a method is declared with the float return
type, the value returned should be of float type only.
2. The variable that stores the returned value after the method is called should be a
similar data type otherwise, the data might get lost.
3. If a method is declared with parameters, the sequence of the parameter must be the
same while declaration and method call.
Syntax:
The syntax of a return statement is the return keyword is followed by the value to be returned.
return returnvalue;
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operations fast.
The java.io package contains all the classes required for input and output operations.
Syntax
Scanner object_name=new Scanner(System.in);
Example
Scanner s=new Scanner(System.in);
Example
import java.util.*;
public class ScannerClassExample1
{
public static void main(String args[])
{
String s = "Hello, This is JavaTpoint.";
Scanner scan = new Scanner(s);
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
}
}
Output
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0
Java BufferedReader class is used to read the text from a character-based input
stream.
It can be used to read data line by line by readLine() method.
It makes the performance fast.
It inherits Reader class.
Syntax
BufferedReader Object_name=new BufferedReader(new InputStreamReader(System.in));
Example
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Example
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String args[]) throws Exception
{
String s = "Hello, This is JavaTpoint.";
//Create scanner Object and pass string in it
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
System.out.println("--------Enter Your Details-------- ");
System.out.print("Enter your name: ");
String name = scan.readLine();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = Integer.parseInt(scan.readLine());
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = Double.parseDouble(scan.readLine());
System.out.println("Salary: " + d);
}
}
Output
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0
Output Statement
In Java, System.out.println() is a statement that prints the argument passed to it.
The println() method display results on the monitor.
Example
System.out.println(“Welcome to Java Output”);
System.out.println(“Welcome”+a);
Class
It should start with the uppercase letter.
It should be a noun such as Color, Button, System, Thread, etc.
Use appropriate words, instead of acronyms.
Interface
It should start with the uppercase letter.
It should be an adjective such as Runnable, Remote, ActionListener.
Use appropriate words, instead of acronyms.
interface Printable
{
//code snippet
}
Method
It should start with lowercase letter.
It should be a verb such as main(), print(), println().
If the name contains multiple words, start it with a lowercase letter followed by an
uppercase letter such as actionPerformed().
class Employee
{
// method
void draw()
{
//code snippet
}
}
Variable
It should start with a lowercase letter such as id, name.
It should not start with the special characters like & (ampersand), $ (dollar), _
(underscore).
If the name contains multiple words, start it with the lowercase letter followed by an
uppercase letter such as firstName, lastName.
Avoid using one-character variables such as x, y, z.
class Employee
{
// variable
int id;
//code snippet
}
Package
It should be a lowercase letter such as java, lang.
If the name contains multiple words, it should be separated by dots (.) such as
java.util, java.lang.
//package
package employee;
class Employee
{
//code snippet
}
Constant
It should be in uppercase letters such as RED, YELLOW.
If the name contains multiple words, it should be separated by an underscore (_) such
as MAX_PRIORITY.
It may contain digits but not as the first letter.
class Employee
{
//constant
static final int MIN_AGE = 18;
//code snippet
}
1.7 Arrays
Java array is an object which contains elements of a similar data type.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It does not grow
its size at runtime. To solve this problem, a collection framework is used in Java
which grows automatically.
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
or
int intArray[] = new int[20]; // combining both statements in one
//Java Program to illustrate how to declare, instantiate, initialize, and traverse the
array.
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;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output
10
20
70
40
50
Output
enter how many numbers you want to sum: 5
enter the 5 numbers
enter number 1: 32
enter number 2: 12
enter number 3: 43
enter number 4: 212
enter number 5: 23
Syntax
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][];
Output
Enter 9 elements for first matrix:
1
2
3
4
5
6
7
8
9
Enter 9 elements for second matrix:
9
8
7
6
5
4
3
2
1
----Addition Result----
10 10 10
10 10 10
10 10 10
Output
Enter the base of squared matrices 2
Enter the elements of 1st matrix row wise
1
2
3
4
Enter the elements of 2nd matrix row wise
2
3
4
Multiplying the matrices...
The product is:
7 10
15 22
Exceptions in Array
NullPointerException
o In java, an array created without size and initialized to null remains null only.
o It does not allow us to assign a value.
o When we try to assign a value, it generates a NullPointerException.
ArrayIndexOutOfBoundsException
o In java, the JVM (Java Virtual Machine)
throws ArrayIndexOutOfBoundsException when an array is trying to access
with an index value of negative value, value equal to array size, or value more
than the array size.
Access Modifiers
Access Modifier Details
private Will be accessible within the class
Non-Access Modifiers
Modifier Description
final Attributes and methods cannot be overridden / modified
static Attributes and methods belong to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on methods.
The method does not have a body. For example abstract void run(); The
body is provided by the subclass (inherited from)
transient Attributes and methods are skipped when serializing the object containing
them
synchronized Methods can only be accessed by one thread at a time
volatile The value of an attribute is not cached thread-locally, and is always read
from the main memory.
Example:
class ParentClass
{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData()
{
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class ChildClass extends ParentClass
{
void accessData()
{
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();
obj.showData();
obj.accessData();
}
}
Output
Inside ParentClass
a = 10
b = 20
c = 30
d = 40
Inside ChildClass
a = 10
b = 20
c = 30
Definition:
Class is a detailed description, definition, and a logical template to
create objects that share common properties and methods.
Class is a detailed description, definition, and the template of what
an object will be. It is the building bock that leads to object-
oriented programming.
field / variable;
method;
}
Example
class Sample
{
int a,b; //variable declaration
public:
void get(); //method1
void display(); //method2
}
1.10 Object
An entity that has state, identity and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc.
Object Definitions
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behavior.
The object is an instance of a class.
Definition:
Object us a member of java class. Each object has an identity, a
behavior, and a state. State of an object is stored in fields
(variables), method (functions) displays the object behavior.
Syntax
classname objectname=new classname();
class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
class Student
{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation()
{
System.out.println(rollno+" "+name);
}
}
class TestStudent4
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Anonymous object
• Anonymous simply means nameless.
• An object which has no reference is known as an anonymous object.
• It can be used at the time of object creation only.
• If you must use an object only once, an anonymous object is a good approach.
new Calculation();//anonymous object
Example:
class Calculation
{
void fact(int n)
{
int fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
Example:
//Java Program to illustrate the use of Rectangle class which has length and width data
members
class Rectangle
{
int length;
int width;
void insert(int l,int w)
{
length=l;
width=w;
}
void calculateArea()
{
System.out.println(length*width);
}
}
class TestRectangle2
{
public static void main(String args[])
{
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:
55
45
1.11 Methods
A method is a block of statements under a name that gets executes only when it is
called.
Every method is used to perform a specific task.
The major advantage of methods is code re-usability (define the code once, and use it
many times).
In a java programming language, a method defined as a behaviour of an object. That
means, every method in java must belong to a class.
Every method in java must be declared inside a class.
Declaring Methods
Syntax
return_type method_name(argument_list)
{
//statements;
}
Methods in Java
• modifier − It defines the access type of the method and it is optional to use.
• returnType − Method may return a value.
• nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
• Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
• method body − The method body defines what the method does with the statements.
Creating a method
A method is created inside the class and it may be created with any access specifier.
However, specifying access specifier is optional.
Syntax
class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
}
Rules:
The methodName must begin with an alphabet, and the Lower-case letter is preferred.
The methodName must follow all naming rules.
If you do not want to pass parameters, we ignore it.
If a method defined with return type other than void, it must contain the return
statement, otherwise, it may be ignored.
Calling a method
In java, a method call precedes with the object name of the class to which it belongs
and a dot operator.
It may call directly if the method defined with the static modifier.
Every method call must be made, as to the method name with parentheses (), and it
must terminate with a semicolon.
Syntax
<objectName>.<methodName>( actualArguments );
Rules
The objectName must begin with an alphabet, and a Lower-case letter is preferred.
The objectName must follow all naming rules.
Example
class Rectangle
{
int length;
int width;
void insert(int l, int w)
{
length=l;
width=w;
}
void calculateArea()
{
System.out.println(length*width);
}
}
class TestRectangle1
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output
55
45
Syntax
<returnType> <methodName>(dataType...parameterName);
Example
public class JavaMethodWithVariableArgs
{
void display(int...list)
{
System.out.println("\nNumber of arguments: " + list.length);
for(int i : list)
{
System.out.print(i + "\t");
}
}
public static void main(String[] args)
{
JavaMethodWithVariableArgs obj = new JavaMethodWithVariableArgs();
obj.display(1, 2);
obj.display(10, 20, 30, 40, 50);
}
}
Output
Number of arguments: 2
1 2
Number of arguments: 5
10 20 30 40 50
1.12 Constructors
• In Java, constructor is a block of codes like method.
• It is called when an instance of object is created and memory is allocated for the
object.
• It is a special type of method which is used to initialize an object.
A constructor is a special method of a class that has the same name as the class
name.
The constructor gets executes automatically on object creation.
It does not require the explicit method call.
A constructor may have parameters and access specifiers too.
In java, if you do not provide any constructor the compiler automatically creates a
default constructor.
• Constructors are called only once at the time of Object creation while method(s) can
be called any number of times.
No-argument constructor
• A constructor that has no parameter is known as the No-argument or Zero argument
constructor.
• If we do not define a constructor in a class, then the compiler creates a constructor
(with no arguments) for the class.
• And if we write a constructor with arguments or no arguments then the compiler does
not create a default constructor.
class A{
A(){
System.out.println("Hi");
}
public static void main(String[] args){
A ob = new A();
}
}
Example:
package com.journaldev.constructor;
Parameterized constructor
A constructor which has a specific number of parameters is called parameterized
constructor.
Parameterized constructor is used to provide different values to the distinct objects.
class A{
A(int i){
System.out.println(i);
}
public static void main(String[] args){
A ob = new A(5);
}
Example:
package com.journaldev.constructor;
public class Data {
private String name;
public Data(String n) {
System.out.println("Parameterized Constructor");
this.name = n;
}
public String getName() {
return name;
}
public static void main(String[] args) {
Data d = new Data("Java");
System.out.println(d.getName());
}
}
Default Constructor
A constructor is called "Default Constructor" when it does not have any parameter.
class A{
int a;
float b;
public static void main(String[] args){
A ob = new A();
System.out.println(ob.a);
System.out.println(ob.b);
}
}
Example:
package com.journaldev.constructor;
public class Data {
public static void main(String[] args) {
Data d = new Data();
}
}
1. Default constructor only role is to initialize the object and return it to the calling code.
2. Default constructor is always without argument and provided by java compiler only
when there is no existing constructor defined.
3. Most of the time we are fine with default constructor itself as other properties can be
accessed and initialized through getter setter methods.
Example
class Student
{
int id;
String name;
int age;
Student(int i,String n)
{
id = i;
name = n;
}
Student(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}
Example
class Adder
{
int add(int a,int b)
{
return a+b;
}
int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
Adder a=new Adder();
System.out.println(a.add(11,11));
System.out.println(a.add(11,11,11));
}
}
Output
22
33
Method Overloading: Changing data type of arguments
In this example, we have created two methods that differ in data type. The first add
method receives two integer arguments and the second add method receives two double
arguments.
Example
class Adder
{
int add(int a, int b)
{
return a+b;
}
double add(double a, double b)
{
return a+b;
}
}
class TestOverloading
{
public static void main(String[] args)
{
Adder a=new Adder();
System.out.println(a.add(11,11));
System.out.println(a.add(12.3,12.6));
}
}
Output
22
24.9
Example:
class TestOverloading4{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
}
Output:
main with String[]
}
}
Output:40
60
class OverloadingCalculation2{
void sum(int a,int b){System.out.println("int arg method invoked");}
void sum(long a,long b){System.out.println("long arg method invoked");}
}
}
Output: int arg method invoked
class OverloadingCalculation3{
void sum(int a,long b){System.out.println("a method invoked");}
void sum(long a,int b){System.out.println("b method invoked");}
Example
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Output
111 ankit 5000.0
112 sumit 6000.0
The static variable will get the memory only once, if an object changes the value of
the static variable, it will retain its value.
//Java Program to illustrate the use of static variables which is shared with all objects.
class Counter2
{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;//incrementing the value of the static variable
System.out.println(count);
}
public static void main(String args[]){
//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Output
1
2
3
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
public static void main(String args[])
{
int result=Calculate.cube(5);
System.out.println(result);
}
}
Output
125
// static variable
static int age;
// static block
static {
age = 23;
}
}
Here we can see that we have used a static block with the syntax
static {
// variable initialization
}
The static block is executed only once when the class is loaded in memory.
The class is loaded if either the object of the class is requested in code or the static
members are requested in code.
Advantages:
Stop value change
Stop method overriding
Stop inheritance
class ParentClass{
int num = 10;
final void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}
public class FinalKeywordExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
obj.showData();
}
}
Keyword Description
abstract A non-access modifier. Used for classes and methods: An abstract
Note: true, false, and null are not keywords, but they are literals and reserved words that
cannot be used as identifiers.