Java PPT Unit-I
Java PPT Unit-I
Examination Scheme
◦ Class Test: 20 Marks
◦ Theory Examination (Marks): 80
Marks
◦ Programming in java lab:50
◦ Total Marks=150
Unit 1: Introduction
• Features of Java, Java Virtual Machine, Byte Code, JIT Compiler
• Class fundamentals, Declaring objects, Nested and Inner Classes, Introducing Methods, Constructors, Garbage
Collection
• Overloading Methods, Using Objects as Parameters, Returning Objects, Access Control, Understanding static &
final keyword,
• Inheritance Basics, Using Super, Method Overriding, Abstract Classes, Using final keyword with inheritance
1. Simple
2. Platform independent
3.Portable
4. Architecture-neutral
5. Multi Threading
6. High-performance
7. Robust
8. Secured
9. Dynamic
10. Object-oriented
Simple
i. JAVA is free from pointers hence we can achieve less development time and less execution
time [whenever we write a JAVA program we write without pointers and internally it is
ii. Rich set of API (application protocol interface) is available to develop any complex
application.
iii. The software JAVA contains a program called garbage collector which is always used to
program. [Garbage collector is the system JAVA program which runs in the background
along with regular JAVA program to collect unreferenced memory locations by running at
iv. JAVA contains user friendly syntax’s for developing JAVA applications.
Platform Independent:
A program or technology is said to be platform independent if and only if which can run on all available
operating systems.
The languages like C, Cpp are treated as platform dependent languages since these languages are taking
various amount of memory spaces on various operating systems [the operating system dos understands
everything in the form of its native format called Mozart (MZ) whereas the operating system Unix
understands everything in its negative format called embedded linking format (elf). When we write a C or
Cpp program on dos operating and if we try to transfer that program to Unix operating system, we are
unable to execute since the format of these operating systems are different and more over the C, Cpp
software does not contain any special programs which converts one format of one operating system to
The language like JAVA will have a common data types and the common memory spaces on all operating
systems and the JAVA software contains the special programs which converts the format of one operating
system to another format of other operating system. Hence JAVA language is treated as platform
independent language.
Portable:
A portable language is one which can run on all operating systems and on all processors irrespective their architectures
and providers. The languages like C, Cpp are treated as non-portable languages whereas the language JAVA is
called portable language.
Architecture-neutral
2.A multi threaded program is one in which there exists multiple flow of controls
3.A program is said to be multi threaded program if and only of there exists n number of
subprograms. For each and every sub-program there exists a separate flow of control
All such flow of controls are executing concurrently , Such flow of controls is known
as threads. Such type of applications is known as multi threading applications.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled
language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.
Robust
Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
No explicit pointer
Java Programs run inside a virtual machine sandbox
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C
and C++.
Java supports dynamic compilation and automatic memory management (garbage
collection)
Object-oriented
◦ Object
◦ Class
◦ Inheritance
◦ Polymorphism
◦ Abstraction
◦ Encapsulation
Java Virtual Machine
What is Java Virtual Machine?
Java virtual machine is a platform-independent abstract
machine that provides a runtime environment in which the
Java byte code is executed.
It is a part of Java runtime environment that converts the Java
byte code into machine-readable language. The main method
that we have in a Java program is actually called by the Java
virtual machine.
Why Do We Need Java Virtual Machine?
Following are a few important differences between JDK, JVM, and JRE.
JDK stands for Java development kit, and JRE stands for Java runtime
environment.
JDK is for development whereas JRE is for the run time environment.
JVM is an essential part of JDK and JRE to run any Java program.
JVM is an integral part of Java programming and provides platform
independence.
JRE : The Java Runtime Environment (JRE) provides the libraries, the Java Virtual
Machine, and other components to run applets and applications written in the Java
programming language. JRE does not contain tools and utilities such as compilers or
debuggers for developing applets and applications.
Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an
assembler which is an alias representation of a C++ code. As soon as a java program
is compiled, java bytecode is generated. In more apt terms, java bytecode is the
machine code in the form of a .class file. With the help of java bytecode we achieve
platform independence in java.
How does it works?
When we write a program in Java, firstly, the compiler compiles that program and a
bytecode is generated for that piece of code. When we wish to run this .class file on
any other platform, we can do so. After the first compilation, the bytecode generated
is now run by the Java Virtual Machine and not the processor in consideration. This
essentially means that we only need to have basic java installation on any platforms
that we want to run our code on. Resources required to run the bytecode are made
available by theJava Virtual Machine, which calls the processor to allocate the
required resources. JVM's are stack-based so they stack implementation to read the
codes.
JIT Compiler:-
The key of java power "Write once, run everywhere" is bytecode. The way bytecodes
get converted to the appropriate native instructions for an application has a huge impact
on the speed of an application. These bytecode can be interpreted, compiled to native
code or directly executed on a processor whose Instruction Set Architecture is the
bytecode specification.
How does it work :-
The Just-In-Time (JIT) compiler is a component of the Java Runtime Environment that
improves the performance of Java applications at run time. Java programs consists of
classes, which contain platform neutral bytecode that can be interpreted by a JVM on
many different computer architectures. At run time, the JVM loads the class files,
determines the semantics of each individual bytecode, and performs the appropriate
computation. The additional processor and memory usage during interpretation means
that a Java application performs more slowly than a native application. The JIT compiler
helps improve the performance of Java programs by compiling bytecode into native
machine code at run time.
Fig:JIT compiler
Documentation Section
Package Statement
Import Statements
Class Definition
Main Method Class
◦ Main Method Definition
Structure of java program:-
1)Documentation Section -we can write a comment in this section.
-It is an optional part of the program
2)Package statement -A package is a group of classes that are defined by a
name.
-It is an optional part of the program, i.e., if you do
not want to declare any package, then there will be
no problem with it, and you will not get any errors
3)Import statements -This line indicates that if you want to use a class of
another package, then you can do this by importing it
directly into your program.
-It is an optional part of the program
3)Class Definition A Java program may contain several class
definitions. Classes are the main and essential
elements of any Java program.
4)Main Method Class Every Java stand-alone program requires the main
method as the starting point of the program. This is
an essential part of a Java program.
5)public static When the main method is declared public, it means that it
void main can also be used by code outside of its class, due to which
the main method is declared public.
The word static used when we want to access a method
without creating its object, as we call the main
method, before creating any class objects
The word void indicates that a method does not return a
value. main() is declared as void because it does not return a
value.
main is a method; this is a starting point of a Java
program.
//class definition
}
e.g.
System.out.println("Hello Java");
}
Imp Note about the Java programs:
You have to keep in mind that, Java code is case sensitive.
To write a Java program, you must have to define class first.
The name of the class in Java (which holds the main method) is the name of the
Java program, and the same name will be given in the filename.
CLASS:-
“A class is a way of binding the data and associated methods in a single
unit”
Any JAVA program if we want to develop then that should be developed with
respective class only i.e., without class there is no JAVA program.
Variable declaration;
Methods definition;
};
class Student
{
int id;
String name;
System.out.println(s1.id=101 );
System.out.println(s1.name=“ABC”);
}
}
Object Creation:-
Sr. Name of Method
No.
1 Using the new keyword
Using newInstance() method of Class
2
class
UsingnewInstance() method of
3
Constructor class
4 Using clone() method
5 Using deserialization
1) Using new keyword:-
Creation of Object involves two steps –
Step 1 : Declaration of Variable of Type Class
e.g.
Rectangle myrect1;
Above Declaration will just declare a variable of class type.
Declared Variable is able to store the reference to an object of Rectangle Type.
As we have not created any object of class Rectangle and we haven’t assigned any
reference to myrect1 , it will be initialized with null.
Step 2 : Allocation and Assigning Object to variable of
class Type
myrect1 = new Rectangle();
• Above Statement will create physical copy of an object.
• This Physical Copy is then assigned to an variable of Type Class i.e myrect1.
• Note : myrect1 holds an instance of an object not actual object. Actual Object is
created elsewhere and instance is assigned to myrect1.
class Rectangle
{
double length;
double breadth;
}
// This class declares an object of type Rectangle.
class RectangleDemo
{
public static void main(String args[])
{
Rectangle myrect = new Rectangle();
double area;
// assign values to myrect's instance variables
myrect.length = 10;
myrect.breadth = 20;
// Compute Area of Rectangle
area = myrect.length * myrect.breadth ;
System.out.println("Area is " + area);
}
}
Object and Class Example: main outside the class
class Student
{
int id;
String name;
}
Public class TestStudent1
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id=101);
System.out.println(s1.name=“XYZ”);
}
}
Ways to initialize object
There are 3 ways to initialize object in Java.
By reference variable
By method
By constructor
1) Object and Class Example: Initialization through
reference
Initializing an object means storing data into the object. Let's see a simple example
where we are going to initialize the object through a reference variable.
class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name=“XYZ";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
O/P- 101 xyz
• We can also create multiple objects and store information in it
through reference variable.
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name=“ABC";
s2.id=102;
s2.name=“XYZ";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
2) Object and Class Example: Initialization through method
<class_name>()
{
}
What is the purpose of a default constructor
The default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.
e.g.
class Student3
{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
What is o/p of this program
e.g 2
class Test
{
int a, b;
Test ()
{
System.out.println ("I AM FROM DEFAULT CONSTRUCTOR...");
a=10;
b=20;
System.out.println ("VALUE OF a = "+a);
System.out.println ("VALUE OF b = "+b);
}
};
class cons
{
public static void main (String [] args)
{
Test t1=new Test ();
}
};
Parameterized Constructors :
Syntax:
class <clsname>
{
…………………………;
…………………………;
<clsname> (list of parameters) //parameterized constructor
{
Block of statements (s);
}
…………………………;
…………………………;
}
class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);
}
class Test
{
int a, b;
Test (int n1, int n2)
{
System.out.println ("I AM FROM PARAMETER CONSTRUCTOR...");
a=n1;
b=n2;
System.out.println ("VALUE OF a = "+a);
System.out.println ("VALUE OF b = "+b);
}
};
class TestDemo1
{
public static void main (String args[])
Test t1=new Test (10, 20);
}
};
Basic Concepts of Java:-
Variable Declaration:-
1)Local Variable:-A variable declared inside the body of the method is called local variable.
2) Instance Variable:-A variable declared inside the class but outside the body of the method,
is called instance variable. It is not declared as static.
3) Static variable:-A variable which is declared as static is called
static variable.
e.g
class A
void method()
}//end of class
Data Type Default size
boolean 1 bit
char 2 byte
byte 1 byte
short 2 byte
int 4 byte
long 8 byte
float 4 byte
double 8 byte
Boolean Data Type:-The Boolean data type is used to store only two possible
values: true and false. This data type is used for simple flags that track true/false
conditions.
Boolean one = false
Byte Data Type :-It is an 8-bit signed two's complement integer. Its value-
range lies between -128 to 127.
The byte data type is used to save memory in large arrays where the
memory savings is most required.
byte a = 10, byte b = -20
Operators:-
Operator Type Category Precedence
postfix expr++ expr--
Unary ++expr --expr
prefix
+expr -expr ~ !
multiplicative */%
Arithmetic
additive +-
Shift shift << >> >>>
< > <= >=
comparison
Relational instanceof
equality == !=
bitwise AND &
bitwise exclusive
Bitwise ^
OR
bitwise inclusive OR |
logical AND &&
Logical
logical OR ||
Ternary ternary ?:
= += -= *= /= %=
Control Statements:-
If
If-else
switch
While
Do-while
for
if and if-else:-
E.g
public class exa
{
public static void main(String[] args)
{
int number=13;
if(number%2==0)
{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}
}
}
Switch:-
E.g.
class method
{
void add(int x,int y)
{
System.out.println("Addtion is:"+ x+y);
}
void add(float x, float y)
{
System.out.println("addtion is ="+ x+y);
}
};
class method1
{
public static void main(String[] args)
{
method o =new method();
o.add(10,20);
o.add(10.20f,25.7f);
E.g.2
class Rectangle
{
void area(int length, int width)
{
int areaOfRectangle = length * width;
System.out.println("Area of Rectangle : " + areaOfRectangle);
}
void area(double length, double width)
{
double areaOfRectangle = length * width;
System.out.println("Area of Rectangle : " + areaOfRectangle);
}
};
class RectangleDemo1 {
public static void main(String args[])
{
Rectangle r1 = new Rectangle();
r1.area(10, 20);
r1.area(10.50, 20.50);
}};
Different number of arguments :-
class D
{
void mul(int a, int b)
{
System.out.println("mul is="+(a*b)) ;
}
void mul(int a, int b,int c)
{
System.out.println("mul is="+(a*b*c));
}
public static void main(String[] args)
{
D m = new D();
m.mul(8,5);
m.mul(4,6,2);
}}
passing object as parameter to a method:-
class Rectangle
{
int length;
int width;
Rectangle(int l, int b)
{
length = l;
width = b;
}
void area(Rectangle r1)
{
int areaOfRectangle = r1.length * r1.width;
System.out.println("Area of Rectangle : " + areaOfRectangle);
}}
class RectangleDemo2 {
public static void main(String args[])
{ Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}}
This keyword:-
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,”ABC",5000);
Student s2=new Student(112,”XYZ",6000);
s1.display();
s2.display();
}}
Output:-
0 null 0.0
0 null 0.0
In the previous code, parameters (formal arguments) and instance variables are same.
So, we are using this keyword to distinguish local variable and instance variable.
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,”ABC",5000);
Student s2=new Student(112,”XYZ",6000);
s1.display();
s2.display();
}}
to invoke current class method:-You may invoke the method of the current class by
using the this keyword. If you don't use the this keyword, compiler automatically
adds this keyword while invoking the method. Let's see the example
class A
{
void m()
{System.out.println("hello m");}
void n()
{
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[])
{
A a=new A();
a.n();
}}
to invoke current class constructor”:-
class A
{
A(){System.out.println("hello a");
}
A(int x)
{
this();
System.out.println(x);
}
}
class TestThis
5{
public static void main(String args[])
{
A a=new A(10);
}}
Output:
hello a
10
Static keyword:-
keywords are the reserved words that cannot be used as identifiers. In
total there are 57 keywords in Java.
static keyword is mainly used for memory management. It can be used
with variables, methods, blocks and nested classes.
It is a keyword which is used to share the same variable or method of
a given class.
class Student{
int rollno;//instance variable
String name;
static String college =“MSSCET Jalna";//static variable
//constructor
Student(int r,String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of static variable
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,”ABC");
Student s2 = new Student(222,”XYZ");
s1.display();
s2.display();
}
}
static method:-
-If you apply static keyword with any method, it is known as static method.
-A static method can be invoked without the need for creating an instance of a class.
-A static method can access static data member and can change the value of it.
class Student public class TestStaticMethod
{ {
int rollno; public static void main(String
String name; args[])
static String college = “MSSCET"; {
static void change()
Student.change();//calling
{ change method
college = “Jalna";
//creating objects
}
Student s1 = new
Student(int r, String n)
Student(111,”ABC");
{
Student s2 = new
rollno = r;
Student(222,”XYZ");
name = n;
Student s3 = new
}
Student(333,”LMN");
void display()
s1.display();
{ s2.display();
System.out.println(rollno+" "+name+" "+college); s3.display();
} }
} }
Static Block:-Static block is used for initializing the static variables. This block gets
executed when the class is loaded in the memory. A class can have multiple Static blocks,
which will execute in the same sequence in which they have been written into the program.
Class StatBlock
{
static int num;
static String mystr;
static
{
num = 97;
mystr = "Static block in code";
}
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}}
Output:
Value of num: 97
Value of mystr: Static keyword in Java
Static class:-A class can be made static only if it is a nested class. Nested static class
doesn’t need a reference of Outer class.
class Example
{
static String str = "BeginnersBook";
//Static class
static class MyClass
{
public void disp()
{
System.out.println(str);
}
}
public static void main(String args[])
{
Example.MyClass obj = new Example.MyClass();
obj.disp();
}
}
final keyword:-
The final keyword in java is used to restrict the user.
The java final keyword can be used in many context. Final can be:
variable
method
class
The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized
final variable.
Java final Variable
In Java, we cannot change the value of a final
variable. For example,
class Main {
public static void main(String[] args)
{
// create a final variable
final int AGE = 32;
// try to change the final variable
AGE = 45; System.out.println("Age: " + AGE);
}
}
Final method:-
class X {
final void getMethod()
{
System.out.println(“X method has been called”);
}
class Y extends X
{
void getMethod() //cannot override
{
System.out.println(“Y method has been called”);
}
}
class FinalMethod
{
public static void main(String[] args)
{
Y obj = new Y();
obj.getMethod();
}
}
Final Class:- A class with final keyword is known as final class in
java.
final class X
}
Basis for
Compariso Static Final
n
Final keyword is
Static keyword is applicable to
applicable to class,
Applicable nested static class, variables,
methods and
methods and block.
variables.
It is compulsory to
It is not compulsory to initialize
initialize the final
Initialization the static variable at the time of
variable at the time of
its declaration.
its declaration.
The static variable can be The final variable can
Modification
reinitialized. not be reinitialized.
Static methods can only access
the static members of the class, Final methods can not
Methods
and can only be called by other be inherited.
static methods.
Static class's object can not be A final class can not
Class created, and it only contains be inherited by any
static members only. class.
Final keyword
Static block is used to initialize
Block supports no such
the static variables.
block.
Returning Objects:
• The process by which one class acquires the properties (data members)
and functionalities(methods) of another class is called inheritance.
• The aim of inheritance is to provide the reusability of code so that a
class has to write only the unique features and rest of the common
properties and functionalities can be extended from the another class.
• Child Class: The class that extends the features of another class is
known as child class, sub class or derived class.
• Parent Class:-The class whose properties and functionalities are
used(inherited) by another class is known as parent class, super class or
Base class.
Syntax-
• The extends keyword indicates that you are making a new class
that derives from an existing class.
• Types of Inheritance
• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
Single Inheritance :-In Single Inheritance one class
extends another class.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
class Base
{
int x=50;
int y = 60;
public int addition(){
return x+y;
}
}
public class Child extends Base
{ int z;
public void subtraction(){
z = addition() - x;
System.out.println(z);
}}
public class SingleInheritance {
public static void main(String[] args)
{
Child c = new Child(); //Child object
c.subtraction();
}
}
Multilevel Inheritance:-
class Animal{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal
{
void bark()
{System.out.println("barking...");}
}
class BabyDog extends Dog
{
void weep()
{System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
e.g.2
class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
class Cube extends Rectangle {
public void volume() {
System.out.println("Inside volume");
}
}
public class Tester {
public static void main(String[] arguments) {
Cube cube = new Cube();
cube.display();
cube.area();
cube.volume();
}
}
e.g.-3 Class Z extends Y
Class X {
{ public void methodZ()
public void methodX() {
{ System.out.println("class Z method");
System.out.println("Class X method"); }
}
public static void main(String args[])
}
{
Class Y extends X
Z obj = new Z();
{
obj.methodX(); //calling grand parent class
public void methodY() method
{
obj.methodY(); //calling parent class
System.out.println("class Y method"); method
} obj.methodZ(); //calling local method
} }
}
Hierarchical Inheritance
Methods that are only public and protected can be called by using
this keyword. In other words, Private methods and static methods
cannot be called using this.
To refer instance variable of an immediate parent class.
To refer to the method of an immediate parent class.
To refer the constructor of an immediate parent class.
Data abstraction is the process of hiding certain details and showing only
essential information to the user. Abstraction can be achieved with either
abstract classes or interfaces.
A class which is declared as abstract is known as an abstract class. It can
have abstract and non-abstract methods. It needs to be extended and its
method implemented.
An abstract class has an abstract method and non-
abstract method i.e. abstract method without body and
they can have methods with implementation also.
An abstract class is used to provide the most common
feature that is specific to different classes. Subclasses can
provide a different implementation of those abstract
methods according to their needs or requirement.
We cannot create an object of an abstract class using the
‘new ‘ operator, but we can still define its constructor
which can only be invoked in the constructor of its
subclass. Subclass constructor can access a superclass
constructor to initialize its variable which might be using
in the subclass for further requirement.
Example of abstract class
abstract class A{}
e.g.
abstract class Bike
{
abstract void run();
}
class Honda extends Bike
{
void run() {
System.out.println("running safely");
}
public static void main(String args[])
{
Honda obj = new Honda();
obj.run();
} }
o/p:- running safely
e.g.2
abstract class MyClass
{
public void disp()
{
System.out.println("Concrete method of parent class");
}
abstract public void disp2();
}
}
Cat c1 = new Cat();
c1.makeSound();
class Dog extends Animal {
}
public void makeSound() {
}
System.out.println("Bark bark.");
}
}
Output:
Bark bark
class Cat extends Animal {
Meows
public void makeSound() {
System.out.println("Meows ");
}
}
Array:-
declaration:-
datatype var-name[ ];
OR
datatype[ ] var-name;
Instantiating an Array:- When an array is declared, only a reference of
array is created. To actually create or give memory to array , it ll like
as follows
var-name = new type [size];
e.g.
int a[ ];
a=new int[20];
Which create a array a of size 20
public class Demo2
{
public static void main (String args[])
{
int[] a = new int[] {1,2,3,4,5};
for(int i=0; i<=a.length-1;i++)
{
System.out.println(a[i]);
}
}
}
public class arrayadd
{
public static void main(String[] args)
{
int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
class Main {
public static void main(String[] args) {
// create a string
String greet = "Hello! World";
System.out.println("The string is: " + greet);
class Main {
public static void main(String[] args) {
// create string
String greet = "Hello! ";
System.out.println("First String: " + greet);
Vector is like the dynamic array which can grow or shrink its size.
Unlike array, we can store n-number of elements in it as there is no
size limit.
The Vector class is an implementation of the List interface that allows
us to create resizable-arrays similar to the ArrayList class.
here exist some differences between them.
The Vector class synchronizes each individual operation. This means
whenever we want to perform some operation on vectors, the Vector
class automatically applies a lock to that operation.
It is because when one thread is accessing a vector, and at the same
time another thread tries to access it, an exception called
ConcurrentModificationException is generated. Hence, this
continuous use of lock for each operation makes vectors less efficient
Syantax:-
Vector<Type> vector = new Vector<>();
class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");
// Using get()
String element = animals.get(2);
System.out.println("Element at index 2: " + element);
// Using iterator()
Iterator<String> iterate = animals.iterator();
System.out.print("Vector: ");
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
} } }
Output
Element at index 2: Cat
Remove Vector Elements:-
remove(index) - removes an element from specified position
removeAll() - removes all the elements
clear() - removes all elements. It is more efficient than removeAll()
Wrapper Class is used for converting primitive data type into object
and object into a primitive data type.
For each primitive data type, a pre-defined class is present which is
known as Wrapper class.
Why Use Wrapper Classes?
As we knew that in Java when input is given by the user, it is in the
form of String. To convert a string into different data types,
Wrapper classes are used.
We can use wrapper class each time when want to convert primitive
to object or vice versa.
public class JavaExample{
public static void main(String args[]){
//Converting int primitive into Integer object
int num=100;
Integer obj=Integer.valueOf(num);
Output:
100 100
//Java program to convert primitive into objects
//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write
Integer.valueOf(a) internally
Output:
20 20 20
Reading input from console:-
There are three different ways to read the input
from Java Console, they are –
1. Using Java Bufferedreader Class
2. Scanner Class in Java
3. Console Class in Java
Syntax
Scanner object-name =new Scanner(System.in);
import java.util.Scanner;
class GetInputData
{
public static void main(String args[])
{
int num;
float fnum;
String str;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string: ");
str = in.nextLine();
System.out.println("Input String is: "+str);
System.out.println("Enter an integer: ");
num = in.nextInt();
System.out.println("Input Integer is: "+num);
//Get input float number
System.out.println("Enter a float number: ");
fnum = in.nextFloat();
System.out.println("Input Float number is: "+fnum);
}
}
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value
Command line argument:-
The command line argument is the argument that passed to a program during
runtime. It is the way to pass argument to the main method in Java. These
arguments store into the String type args parameter which is main method
parameter.
To access these arguments, you can simply traverse the args parameter in the loop
or use direct index value because args is an array of type String
E.g.
class Main {
public static void main(String[] args) {
System.out.println("Command-Line arguments are");