KEMBAR78
Java Unit-1 | PDF | Java (Programming Language) | Java Virtual Machine
0% found this document useful (0 votes)
14 views60 pages

Java Unit-1

Java is a high-level, object-oriented programming language developed by Sun Microsystems, now part of Oracle. It is in high demand, with Java programmers earning around $120,000 annually in the U.S., and is used by major companies like Google and Amazon. Java's features include platform independence, security, and a robust community, making it suitable for various applications including desktop, web, enterprise, and mobile.

Uploaded by

rajputbhargav001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views60 pages

Java Unit-1

Java is a high-level, object-oriented programming language developed by Sun Microsystems, now part of Oracle. It is in high demand, with Java programmers earning around $120,000 annually in the U.S., and is used by major companies like Google and Amazon. Java's features include platform independence, security, and a robust community, making it suitable for various applications including desktop, web, enterprise, and mobile.

Uploaded by

rajputbhargav001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

What is Java?

Java is a programming language and


a platform. Java is a high level, robust,
object-oriented and secure programming
language.
Java was developed by Sun
Microsystems (which is now the
subsidiary of Oracle).
Java Jobs
Java is very high in demand and all the
major companies are recruiting Java
Programmers to develop their Desktop,
Web and Mobile applications.
Today a Java Programmer with 3-5
years of experience is asking for around
$120,000 annual package and this is the
most demanding programming language
in America. Though it can vary
depending on the location of the Job.
Following are the great companies who
are using Java and they need good
Java Programmers:
●​Google
●​Microsoft
●​Facebook
●​IBM
●​Amazon
●​Netflix
●​Pinterest
●​Uber
●​JetBrains
There are many other good reasons
which makes Java as the first choice of
any programmer:
●​Java is Open Source which means
its available free of cost.
●​Java is simple and so easy to learn
●​Java is much in demand and ensures
high salary
●​Java has a large vibrant community
●​Java has powerful development tools
●​Java is platform independent
Java is −
●​Object Oriented − In Java,
everything is an Object. Java can be
easily extended since it is based on
the Object model.
●​Platform Independent − Unlike
many other programming languages
including C and C++, when Java is
compiled, it is not compiled into
platform specific machine, rather into
platform independent byte code. This
byte code is distributed over the web
and interpreted by the Virtual
Machine (JVM) on whichever
platform it is being run on.
●​Simple − Java is designed to be
easy to learn. If you understand the
basic concept of OOP Java, it would
be easy to master.
●​Secure − With Java's secure feature
it enables to develop virus-free,
tamper-free systems. Authentication
techniques are based on public-key
encryption.
●​Portable − Being architecture-neutral
and having no implementation
dependent aspects of the
specification makes Java portable.
Compiler in Java is written in ANSI C
with a clean portability boundary,
which is a POSIX subset.
●​Robust − Java makes an effort to
eliminate error prone situations by
emphasizing mainly on compile time
error checking and runtime checking.
●​Multithreaded − With Java's
multithreaded feature it is possible to
write programs that can perform
many tasks simultaneously. This
design feature allows the developers
to construct interactive applications
that can run smoothly.
●​High Performance − With the use of
Just-In-Time compilers, Java enables
high performance.
●​Distributed − Java is designed for
the distributed environment of the
internet.
●​Dynamic − Java is considered to be
more dynamic than C or C++ since it
is designed to adapt to an evolving
environment. Java programs can
carry extensive amount of run-time
information that can be used to verify
and resolve accesses to objects on
run-time.
Application
According to Sun, 3 billion devices run
Java. There are many devices where Java
is currently used. Some of them are as
follows:
1.​Desktop Applications such as acrobat
reader, media player, antivirus, etc.
2.​ Web Applications such as irctc.co.in,
javatpoint.com, etc.
3.​ Enterprise Applications such as
banking applications.
4.​ Mobile
5.​ Embedded System
6.​ Smart Card
7.​Robotics
8.​ Games, etc.
Types of Java Applications
There are mainly 4 types of applications
that can be created using Java
programming:
1) Standalone Application
Standalone applications are also known
as desktop applications or
window-based applications. These are
traditional software that we need to
install on every machine. Examples of
standalone application are Media player,
antivirus, etc.
2) Web Application
An application that runs on the server
side and creates a dynamic page is called
a web application.
Currently, Servlet, JSP, Struts, Spring, Hib
ernate, JSF, etc. technologies are used for
creating web applications in Java.
3) Enterprise Application
An application that is distributed in
nature, such as banking applications, etc.
is called an enterprise application. It has
advantages like high-level security, load
balancing, and clustering. In Java, EJB is
used for creating enterprise applications.
4) Mobile Application
An application which is created for
mobile devices is called a mobile
application. Currently, Android and Java
ME are used for creating mobile
applications.
JDK,JRE,JVM
1. JDK (Java Development Kit) is a Kit
that provides the environment
to develop and execute(run) the Java
program. JDK is a kit(or package) that
includes two things
●​Development Tools(to provide an
environment to develop your java
programs)
●​JRE (to execute your java program).

2. JRE (Java Runtime Environment) is


an installation package that provides an
environment to only run(not
develop) the java program(or
application)onto your machine. JRE is
only used by those who only want to run
Java programs that are end-users of
your system.​

3. JVM (Java Virtual Machine) is a very


important part of both JDK and JRE
because it is contained or inbuilt in both.
Whatever Java program you run using
JRE or JDK goes into JVM and JVM is
responsible for executing the java
program line by line, hence it is also
known as an interpreter.

Working of a Java Program:

Bytecode is the intermediate


representation of a Java program,
allowing a JVM to translate a program
into machine-level assembly
instructions.(outputting the byte code
to a class file )
The JVM, which is part of the Java
Runtime Environment, interprets the
bytecode and converts it to machine
language specific to the intended
platform.

Popular Java Editors


To write your Java programs, you will
need a text editor. There are even more
sophisticated IDEs available in the
market. But for now, you can consider
one of the following −
●​Notepad − On Windows machine,
you can use any simple text editor
like Notepad (Recommended for this
tutorial), TextPad.
●​Netbeans − A Java IDE that is
open-source and free which can be
downloaded
from https://www.netbeans.org/index.
html.
●​Eclipse − A Java IDE developed by
the eclipse open-source community
and can be downloaded
from https://www.eclipse.org/.
Basic Syntax
About Java programs, it is very
important to keep in mind the following
points.
●​Case Sensitivity − Java is case
sensitive, which means
identifier Hello and hello would have
different meaning in Java.
●​Class Names − For all class names
the first letter should be in Upper
Case. If several words are used to
form a name of the class, each inner
word's first letter should be in Upper
Case.
Example: class MyFirstJavaClass
●​Method Names − All method names
should start with a Lower Case letter.
If several words are used to form the
name of the method, then each inner
word's first letter should be in Upper
Case.
●​Program File Name − Name of the
program file should exactly match the
class name.
When saving the file, you should
save it using the class name
(Remember Java is case sensitive)
and append '.java' to the end of the
name (if the file name and the class
name do not match, your program
will not compile).
But please make a note that in case
you do not have a public class
present in the file then file name can
be different than class name. It is
also not mandatory to have a public
class in the file.
Example: Assume
'MyFirstJavaProgram' is the class
name. Then the file should be saved
as 'MyFirstJavaProgram.java'
●​public static void main(String
args[]) − Java program processing
starts from the main() method which
is a mandatory part of every Java
program.

Java Modifiers
Like other languages, it is possible to
modify classes, methods, etc., by using
modifiers. There are two categories of
modifiers −
●​Access Modifiers − default, public ,
protected, private
●​Non-access Modifiers − final,
abstract, strictfp

Java provides a rich set of operators to


manipulate variables. We can divide all
the Java operators into the following
groups −
●​Arithmetic Operators
●​Relational Operators
●​Bitwise Operators
●​Logical Operators
●​Assignment Operators
●​Misc Operators
Java Control Statements | Control Flow
in Java
Java compiler executes the code from top
to bottom. The statements in the code
are executed according to the order in
which they appear.
However, Java provides statements that
can be used to control the flow of Java
code. Such statements are called control
flow statements. It is one of the
fundamental features of Java, which
provides a smooth flow of program.
Java provides three types of control flow
statements.
1.​Decision Making statements
o​if statements
o​switch statement
2.​ Loop statements
o​do while loop
o​while loop
o​for loop
o​for-each loop
3.​ Jump statements
o​break statement
o​continue statement
Decision-Making statements:
As the name suggests, decision-making
statements decide which statement to
execute and when. Decision-making
statements evaluate the Boolean
expression and control the program flow
depending upon the result of the
condition provided. There are two types
of decision-making statements in Java,
i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to
evaluate a condition. The control of the
program is diverted depending upon the
specific condition. The condition of the If
statement gives a Boolean value, either
true or false. In Java, there are four types
of if-statements given below.
1.​Simple if statement
2.​ if-else statement
3.​ if-else-if ladder
4.​ Nested if-statement
Let's understand the if-statements one by
one.
1) Simple if statement:
It is the most basic statement among all
control flow statements in Java. It
evaluates a Boolean expression and
enables the program to enter a block of
code if the expression evaluates to true.
Syntax of if statement is given below.
1.​if(condition) {
2.​ statement 1; //executes when condition
is true
3.​ }
Consider the following example in which
we have used the if statement in the java
code.
Student.java
public class Student
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y > 20)
{
System.out.println
("x + y is greater than 20");
}
}
}

2) if-else statement
The if-else statement is an extension to
the if-statement, which uses another
block of code, i.e., else block. The else
block is executed if the condition of the
if-block is evaluated as false.
Syntax:
if(condition)
{
statement 1; //executes when condition is
true
}
else
{
statement 2; //executes when condition is
false
}
Consider the following example.
Student.java
public class Student
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y < 10)
{
System.out.println("x + y is less than 10
");
}
else
{
System.out.println("x + y is greater than 2
0");
}
}
}
Syntax of if-else-if statement is given
below.
if(condition 1)
{
statement 1; //executes when condition 1 i
s true
}
else if(condition 2)
{
statement 2; //executes when condition 2
is true
}
else
{
statement 2; //executes when all the con
ditions are false
}
Consider the following example.
city.java
public class Student
{
public static void main(String[] args)
{
String city = "Delhi";
if(city == "Meerut")
{
System.out.println("city is meerut");
}
else if (city == "Noida")
{
System.out.println("city is noida");
}
else if(city == "Agra")
{
System.out.println("city is agra");
}
else
{
System.out.println(city);
}
}
}

Nested if-statement
In nested if-statements, the if statement
can contain a if or if-else statement inside
another if or else-if statement.
Syntax of Nested if-statement is given
below.
if(condition 1)
{
statement 1; //executes when condition 1 i
s true
if(condition 2)
{
statement 2; //executes when condition 2
is true
}
else
{
statement 2; //executes when condition 2
is false
}
}
Nestedif.java

public class Student {


public static void main(String[] args)
{
String address = "Delhi, India";

if(address.endsWith("India"))
{
if(address.contains("Meerut"))
{
System.out.println("Your city is Meerut");

}
else if(address.contains("Noida"))
{
System.out.println("Your city is Noida");
}
else
{
System.out.println(address.split(",")[0]);
}
}
else
{
System.out.println("You are not living in In
dia");
}
}
}

A for-each loop is a loop that can only


be used on a collection of items. It
will loop through the collection and
each time through the loop it will use
the next item from the collection. It
starts with the first item in the array (the
one at index 0) and continues through in
order to the last item in the array.

for-each Loop Sytnax


The syntax of the Java for-each loop is:
for(dataType item : array) { ... }
array - an array or a collection.
item - each item of array/collection is
assigned to this variable.
dataType - the data type of the
array/collection.

Syntax:
for (type var : array)
{
statements using var;

}
is equivalent to: ​

for (int i=0; i<arr.length; i++)


{
type var = arr[i];
statements using var;
}
class For_Each​
{
​ public static void main(String[] arg)
​ {
​ ​ {
​ ​ ​ int[] marks = { 125, 132, 95,
116, 110 };
​ ​ ​ int highest_marks =
maximum(marks);
​ ​ ​ System.out.println("The
highest score is " + highest_marks);
​ ​ }
​ }
​ public static int maximum(int[]
numbers)
​ {
​ ​ int maxSoFar = numbers[0];
​ ​ for (int num : numbers)
​ ​ {
​ ​ ​ System.out.println(num);
​ ​ ​ if (num > maxSoFar)
​ ​ ​ {
​ ​ ​ ​ maxSoFar = num;
​ ​ ​ }
​ ​ }
​ return maxSoFar;
​ }
}
Output: ​

The highest score is 132


Limitations of for-each loop ​
1.​ For-each loops are not appropriate
when you want to modify the array:​
for (int num : marks)
{
// only changes num, not the
array element
num = num*2;
}
2. For-each loops do not keep track
of index. So we can not obtain array
index using For-Each loop ​
for (int num : numbers)
{
if (num == target)
{
return ???; // do not
know the index of num
}
}
3. For-each only iterates forward
over the array in single steps ​
// cannot be converted to a
for-each loop
for (int i=numbers.length-1;
i>0; i--)
{

System.out.println(numbers[i]);
}

Break Statement in Java

Using break to exit a loop


Using break, we can force immediate
termination of a loop, bypassing the
conditional expression and any
remaining code in the body of the loop.
When we use break inside the nested
loops, it will only break out of the
innermost loop.
// Java program to demonstrate
using
// break to exit a loop
class break {
​ public static void
main(String[] args)
​ {
​ ​ // Initially loop is set
to run from 0-9
​ ​ for (int i = 0; i < 10;
i++) {
​ ​ ​ // Terminate the loop
when i is 5
​ ​ ​ if (i == 5)
​ ​ ​ ​ break;
​ ​ ​ System.out.println("i:
" + i);
​ ​ }
​ ​ System.out.println("Out of
Loop");
​ }
}
Output
i: 0
i: 1
i: 2
i: 3
i: 4
Out of Loop
Continue statement in JAVA:

public class ContinueExample


{
public static void main(String[] args)
{
//for loop
for(int i=1;i<=10;i++)
{
if(i==5)
{
//using continue statement
continue;//it will skip the rest state
ment
}
System.out.println(i);
}
}
}
Array in Java

class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instan
tiation
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 pr
operty of array
System.out.println(a[i]);
}}

1st way
int a[]=new int[5];//declaration and instan
tiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;

2nd way
Int marks[] ={123,12,56,78,23}

String class in Java | Set 1


String is a sequence of characters. In
java, objects of String are immutable
which means a constant and cannot be
changed once created.
Creating a String
There are two ways to create string in
Java:
●​String literal
String s = “Welcome”;(station
allocation – string constant
pool(separate place in heap))
●​Using new keyword
String s = new String
(“Welcome”);(dynamic
allocation- heap)
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by Java st
ring literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting cha
r array to string
String s3=new String("example");//creatin
g Java string by new keyword
System.out.println("\n"+s1+"\n");
System.out.println("\n"+s2);
System.out.println("\n"+s3);
}
}

Strings Operations:
Java String class provides a lot of
methods to perform operations on
strings such as compare(), concat(),
equals(), split(),
length(),substring() etc
1.String concatenation
Immutable String in Java
A String is an unavoidable type of
variable while writing any application
program. String references are used to
store various attributes like username,
password, etc. In Java, String objects are
immutable. Immutable simply means
unmodifiable or unchangeable.
Once String object is created its data or
state can't be changed but a new String
object is created.
Let's try to understand the concept of
immutability by the example given
below:
Testimmutablestring.java
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() metho
d appends the string at the end
System.out.println(s);//will print Sachin
because strings are immutable objects
}
}
Output:Sachin
A string constant pool is a separate
place in the heap memory where the
values of all the strings which are
defined in the program are stored.
Now it can be understood by the diagram
given below. Here Sachin is not changed
but a new object is created with Sachin
Tendulkar. That is why String is known as
immutable.
As you can see in the above figure that
two objects are created but s reference
variable still refers to "Sachin" not to
"Sachin Tendulkar".
But if we explicitly assign it to the
reference variable, it will refer to "Sachin
Tendulkar" object.
For example:
Testimmutablestring1.java
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:
Sachin Tendulkar
In such a case, s points to the "Sachin
Tendulkar". Please notice that still Sachin
object is not modified.
2. Get length of a String
To find the length of a string, we use
the length() method of the String. For
example,

class Main {
public static void main(String[] args) {

// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);

// get the length of greet


int length = greet.length();
SyIn the above example,
the length() method calculates the
total number of characters in the string
and returns it.stem.out.println("Length: "
+ length);
}
}
3. Compare two Strings
In Java, we can make comparisons
between two strings using
the equals() method. For example,
class Main {
public static void main(String[] args) {

// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";

// compare first and second strings


boolean result1 = first.equals(second);
System.out.println("Strings first and
second are equal: " + result1);

// compare first and third strings


boolean result2 = first.equals(third);
System.out.println("Strings first and
third are equal: " + result2);
}
}

StringBuffer class in Java

StringBuffer is a peer class of String that


provides much of the functionality of
strings. The string represents
fixed-length, immutable character
sequences while StringBuffer represents
growable and writable character
sequences. StringBuffer may have
characters and substrings inserted in
the middle or appended to the end.
It will automatically grow to make room
for such additions and often has more
characters preallocated than are
actually needed, to allow room for
growth.

●​StringBuffer class is used to created


mutable (modifiable) string. The
StringBuffer class in java is same as
String class except it is mutable i.e. it
can be changed.

1) append() method

The append() method concatenates


the given argument with this string.

class StringBuffer_append{
​ public static void main(String args[]){
​ ​ StringBuffer sb=new
StringBuffer("Hello ");
​ ​ sb.append("Java");//now original
string is changed
​ ​ System.out.println(sb);
​ }
}
Here world gets added after hello

2) Insert() method
The insert() method inserts the given
string with this string at the given
position.

class StringBuffer_insert{
​ public static void main(String args[]){
​ ​ StringBuffer sb=new
StringBuffer("Hello ");
​ ​ sb.insert(1,"Java");​ ​ ​ ​ ​
//now original string is changed
​ ​ System.out.println(sb);​ ​ ​
​ }
}
Output:HJavaello

3) replace() method
The replace() method replaces the
given string from the specified
beginIndex and endIndex-1

class StringBuffer_replace{
​ public static void main(String args[]){
​ ​ StringBuffer sb=new
StringBuffer("Hello");
​ ​ sb.replace(1,3,"Java");
​ ​ System.out.println(sb);
​ }
}

Command line arguments:


Java Command Line Arguments

The java command-line argument is an


argument i.e. passed at the time of
running the java program.
The arguments passed from the console
can be received in the java program and
it can be used as an input.
So, it provides a convenient way to check
the behavior of the program for the
different values. You can pass N (1,2,3 and
so on) numbers of arguments from the
command prompt.

class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is:
"+args[0]);
}
Example of command-line argument
that prints all the values
In this example, we are printing all the
arguments passed from the command-line.
For this purpose, we have traversed the array
using for loop.
class CommandLineExample_2{
public static void main(String args[]){

for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
}
args contains the command
line arguments that are passed to the
program.​
args.length is the length of the arguments.
For example if you run:
java myJavaProgram first second
args.length will be 2 and it'll
contain ["first", "second"].
And the length of the array args is
automatically set to 2 (number of your
parameters), so there is no need to set
the length of args.
Simple calculator program
class SimpleCalculator
{
public static void main (String args[])
{
int operand1 = Integer.parseInt(args[0]);
String op = args[1];
int operand2 = Integer.parseInt(args[2]);
int result = 0;
if (op.equals("+"))
result = operand1 + operand2;
else if (op.equals("-"))
result = operand1 - operand2;
else if (op.equals("x"))
result = operand1 * operand2;
else if (op.equals("/"))
result = operand1 / operand2;
else
throw new java.lang.Error("Operator not
recognized");
System.out.println("\n" + operand1 + op +
operand2 + " = "+result);

}
}
Ternary operator program
class MaximumNumber {
public static void main(String args[])
{
int a = 10, b = 25, c = 15, max;
max = (a > b) ? (a > c ? a : c) : (b > c ? b
: c);
System.out.println("Maximum
number among " + a + ", " + b + " and " + c
+ " is "
+ max);
}
}

Second largest number


import java.util.*;
class SecondLargest
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();

Arrays.sort(a);
System.out.print("The second largest
number: "+a[n-2]);
}
}
OR
public class SecondLargestNumber {
public static void main(String args[]){
int temp, size;
int array[] = {10, 20, 25, 63, 96, 57};
size = array.length;

for(int i = 0; i<size; i++ ){


for(int j = i+1; j<size; j++){

if(array[i]>array[j]){
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println("Third second
largest number is:: "+array[size-2]);
}
}

Java.util.* is stands for all the


packages in java
Scanner is a class in java. util
package used for obtaining the input
of the primitive types like int, double,
etc. and strings.
In java, packages are the container for
classes and whenever we want to use
the features of another classes that are
defined in another package,we
use import keyword.
Now, let's see
what java.util.Scanner means !!
In java we use "." to denote the hierarchy.
So the above statement will denote -​
java\util\Scanner in Windows
environment.
So, the full meaning is -​
import Scanner class which is in util
folder inside the java folder.​
In java -​
util :stands for utility and contains utility
classes.​
Scanner : is a predefined class for taking
inputs from user.

Scanner input = new


Scanner(System.in); you make a new
object of the Scanner class (so you make
a new "Scanner") and you store it in the
variable input. At the same time you are
calling the constructor of the class, with
the parameter System.in. That means it is
going to read from the standard input
stream of the program.
Now when you are
calling input.nextInt(); you execute the
method from the object you just created.
The nextInt() method scans the next
token of the input data as an “int”. As
the name of the class Scanner
elaborates, nextInt() method of this
class is used to scan or parse the input.

You might also like