SlideShare a Scribd company logo
JAVA
JAVA.ppsx java code java edv java development
JAVA.ppsx java code java edv java development
JAVA.ppsx java code java edv java development
JAVA.ppsx java code java edv java development
JAVA.ppsx java code java edv java development
JAVA.ppsx java code java edv java development
JAVA.ppsx java code java edv java development
JAVA.ppsx java code java edv java development
JAVA.ppsx java code java edv java development
JAVA.ppsx java code java edv java development
JAVA.ppsx java code java edv java development
JAVA.ppsx java code java edv java development
Tools You Will Need
need the following softwares −
•Linux 7.1 or Windows xp/7/8 operating system
•Java JDK 8
•Microsoft Notepad or any other text editor
Popular Java Editors
To write your Java programs, you will need a text editor. There are even more
sophisticated IDEs available in the market. 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/
https://www.guru99.com/install-java.html
OR
https://www.oracle.com/technetwork/java/javase/downloads/index.html
How to Download & Install Java JDK 8 in Windows
https://www.youtube.com/watch?v=jRZZUzqJ7S0
How to install Java on Windows OS - Video
How do I become a good Java programmer?
•Get your basics clear –
•Read documentation and open source frameworks source code –
•Practice Coding –
•Group discussions and read books –
•Subscribe to forums –
•Undertake projects –
•Dedicate yourself –
History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many
set-top box projects. The language, initially called ‘Oak’ after an oak tree that stood
outside Gosling's office, also went by the name ‘Green’ and ended up later being
renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write
Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software
under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-
source, aside from a small portion of code to which Sun did not hold the copyright.
Features of Java Programming Language
Java is platform independent
Java was built with the philosophy of "write once, run anywhere" (WORA). The Java code
(pure Java code and libraries) you write on one platform (operating system) will run on
other platforms with no modification.
To run Java, an abstract machine called Java Virtual Machine (JVM) is used. The JVM
executes the Java bytecode. Then, the CPU executes the JVM. Since all JVMs works exactly
the same, the same code works on other operating systems as well, making Java platform-
independent.
An object-oriented Language
There are different styles of programming. Object-oriented approach is one of the popular
programming styles. In object-oriented programming, a complex problem is divided into
smaller sets by creating objects. This makes your code reusable, has design benefits, and
makes code easier to maintain.
Many programming languages including Java, Python, and C++ has object-oriented
features. If you are serious about programming, you should definitely learn object-oriented
style of programming.
Java is fast
The earlier versions of Java were criticized for being slow. However, things are completely
different now. The new JVMs are significantly faster. And, the CPU that executes JVM are
also getting more and more powerful.
Now, Java is one of the fastest programming languages. Well optimized Java code is nearly
as fast as lower level languages like C/C++, and much faster than Python, PHP etc.
Java is secure
The Java platform provides various features for security of Java applications. Some of the
high-level features that Java handles are:
- provides secure platform for developing and running applications
- automatic memory management, reduces memory corruption and vulnerabilities
- provides secure communication by protecting the integrity and privacy of data
transmitted
Large Standard Library
One of the reasons why Java is widely used is because of the availability of huge
standard library. The Java environment has hundreds of classes and methods under
different packages to help software developers like us. For example,
java.lang - for advanced features of strings, arrays etc.
java.util - for data structures, regular expressions, date and time functions etc.
java.io - for file i/o, exception handling etc.
Java Terminologies You Need to Know Before You Start
Learning a new programming language can be challenging. You will hear a lot of new
terms which can be overwhelming for a newbie. So, here decided to explain a few terms
that you are likely to hear in the world of Java programming language.
Java - Java is a set of technologies (programming language and computing platform) for
creating and running software. However, Java is often used to refer Java programming
language for simplicity.
Java programming language - A powerful, general-purpose, platform-independent, object-
oriented programming language.
Java 8 - Java 8 is the latest major release for Java. Our Java tutorial will include all major
features of Java 8.
Java EE, Java ME and Java SE - Java EE, Java ME and Java SE stands for Java Platform
Enterprise Edition, Micro Edition, and standard edition respectively.
Java EE is targeted for applications which run on servers. Java ME is targeted for resource
limited devices like: embedded devices. And, Java SE is the basic Java environment used
for creating standard programs.
If you are a java programming newbie, we recommend you to start with J2SE.
JVM - JVM (Java Virtual Machine) is an abstract machine that enables your computer to
run a Java program.
JRE - JRE (Java Runtime Environment) contains JVM, supporting libraries, and other
components to run a Java program. However, it doesn't contain any compiler and
debugger.
JDK - JDK (Java Development Kit) contains JRE and tools such as compilers and debuggers
for developing Java applications.
Run Java on your OS
Run Java on Windows (XP, 7, 8 and 10)
To run Java Programming in Windows, you'll need to install two things: JAVA SE
Development Kit (JDK) and IDE to create your Java Projects.
Follow this step by step guide to get started.
Install Java
•Go to the Downloads page of Java Standard Edition Development Kit.
•Under Java SE Development Kit section, click Accept License agreement at the top of
the table. Then, click the download link for Windows (x64) if you have a 64-bit system,
or Windows (x86) if you have a 32-bit system.
•After download, open the setup file and follow the instructions. Click Next. Select all
features by selecting "This feature will be installed on local hard drive" and copy
the installation location (highlighted by yellow) in a Notepad. And, click next again.
•During the installation, you'll be prompted to install JRE. Click Next and you're done. Click
the Finish button to complete the installation
.
•Now, you need to edit the PATH variable. Go to Control Panel > System and Security >
System. Click on Advanced system settings on the left to get System Properties window.
•Click on Environment Variables. Then, on the lower System variables section,
find Path and click Edit on the following window. Click Ok to save the changes.
To check if Java was properly installed, open Command Prompt by typing cmd in
Windows search or using Run window (Windows Key + R), and type java -version to get
similar output as below. If you do, congratulations you've successfully installed Java. If
not, check the Oracle's Download Help.
https://www.youtube.com/watch?v=NZ38tlhtQgw
How to Install Eclipse for Java (Windows 10)
Java Version History
Many java versions have been released till now. The current stable release of Java is
Java SE 11.
•JDK Alpha and Beta (1995)
•JDK 1.0 (23rd Jan 1996)
•JDK 1.1 (19th Feb 1997)
•J2SE 1.2 (8th Dec 1998)
•J2SE 1.3 (8th May 2000)
•J2SE 1.4 (6th Feb 2002)
•J2SE 5.0 (30th Sep 2004)
•Java SE 6 (11th Dec 2006)
•Java SE 7 (28th July 2011)
•Java SE 8 (18th March 2014)
•Java SE 9 (21st Sep 2017)
•Java SE 10 (20th March 2018)
•Java SE 11
Application
According to Sun, 3 billion devices run Java. There are many devices where Java is
currently used. Some of them are as follows:
•Desktop Applications such as acrobat reader, media player, antivirus, etc.
•Web Applications such as irctc.co.in, javatpoint.com, etc.
•Enterprise Applications such as banking applications.
•Mobile
•Embedded System
•Smart Card
•Robotics
•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. AWT and Swing are
used in Java for creating standalone applications.
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, Hibernate, 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
enterprise application. It has advantages of the 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.
Java Platforms / Editions
There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as java.lang,
java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String,
Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing,
Reflection, Collection, etc.
2) Java EE (Java Enterprise Edition)
It is an enterprise platform which is mainly used to develop web and enterprise
applications. It is built on the top of the Java SE platform. It includes topics like Servlet,
JSP, Web Services, EJB, JPA, etc.
3) Java ME (Java Micro Edition)
It is a micro platform which is mainly used to develop mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a light-weight user interface API. FX
is normally related with sound or visual effects
Basic Syntax
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.
Example: public void myMethodName()
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).
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.
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
•Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
•Non-primitive data types: The non-primitive data types include Classes,
Interfaces, and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java language.
There are 8 types of primitive data types:
•boolean data type
•byte data type
•char data type
•short data type
•int data type
•long data type
•float data type
•double data type
JAVA.ppsx java code java edv java development
Data Type Default Value Default size
boolean false 1 bit
char 'u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 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.
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example: Boolean one = false
Byte Data Type
The byte data type is an example of primitive data type. It is an 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is
most required. It saves space because a byte is 4 times smaller than an integer. It can also
be used in place of "int" data type.
Example: byte a = 10, byte b = -20
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example: int a = 100000, int b = -200000
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive).
Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you
need a range of values more than those provided by int.
Example: long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating point numbers. The float data type should never be
used for precise values, such as currency. Its default value is 0.0F.
Example: float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range
is unlimited. The double data type is generally used for decimal values just like float. The
double data type also should never be used for precise values, such as currency. Its
default value is 0.0d.
Example: double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '
u0000' (or 0)(as java uses Unicode system not ASCII code system) to 'uffff' (or 65,535
inclusive).The char data type is used to store characters.
Example: char letterA = 'A'
•Unicode is a character encoding standard that has widespread acceptance. Microsoft
software uses Unicode at its core. Whether you realize it or not, you are using Unicode
already! Basically, “computers just deal with numbers. They store letters and other
characters by assigning a number for each one. Before Unicode was invented, there
were hundreds of different encoding systems for assigning these numbers. No single
encoding could contain enough characters.”
•The u0000 is the lowest range of Unicode system
•Unicode is an industry standard character set encoding developed and maintained by
The Unicode® Consortium. The Unicode character set has the capacity to support over
one million characters, and is being developed with an aim to have a single character set
that supports all characters from all scripts, as well as many symbols, that are in
common use around the world today or in the past. Currently, the Standard supports
over 96,000 characters representing a large number of scripts. The benefits of a single,
universal character set and the practical considerations for implementation that have
gone into the design of Unicode have made it a success, and it is well on the way to
becoming a dominant.
What is Unicode? and Why do I need to use Unicode?
Before Unicode, there were many language standards:
•ASCII (American Standard Code for Information Interchange)
for the United States.
•ISO 8859-1 for Western European Language.
•KOI-8 for Russian.
•GB18030 and BIG-5 for Chinese, and so on.
Why java uses Unicode System?
This caused two problems:
1. A particular code value corresponds to different letters in the
various language standards.
2. The encodings for languages with large character sets have
variable length. Some common characters are encoded as
single bytes, other require two or more byte.
Problem
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:u0000
highest value:uFFFF
Solution
FIRST JAVA PROGRAM
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
To compile: javac Simple.java
To execute: java Simple
save this file as Simple.java
Output: Hello Java
Parameters used in First Java Program
Let's see what is the meaning of class,
public, static, void, main, String[],
System.out.println().
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility. It means it is visible to
all.
static is a keyword. If we declare any method as static, it is known as the static method.
The core advantage of the static method is that there is no need to create an object to
invoke the static method. The main method is executed by the JVM, so it doesn't require
to create an object to invoke the main method. So it saves memory.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program.
String[] args is used for command line argument.
System.out.println() is used to print statement. Here, System is a class, out is the object
of PrintStream class, println() is the method of PrintStream class
Valid java main method signature
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
public static void main(String... args)
static public void main(String[] args)
public static final void main(String[] args)
final public static void main(String[] args)
final strictfp public static void main(String[] args)
Invalid java main method signature
public void main(String[] args)
static void main(String[] args)
public void static main(String[] args)
abstract public static void main(String[] args)
Can we have multiple classes in a java source file?
Yes, like the figure given below illustrates:
Java Variables
A variable is a container which holds the value while the java program is executed. A
variable is assigned with a datatype.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
Variable is name of reserved area allocated in memory. In other words, it is a name
of memory location. It is a combination of "vary + able" that means its value can be
changed.
Types of Variables
There are three types of variables in java:
•local variable
•instance variable
•static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the
class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
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.
It is called instance variable because its value is instance specific and is not
shared among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local.
You can create a single copy of static variable and share among all the instances
of the class. Memory allocation for static variable happens only once when the
class is loaded in the memory.
Example to understand the types of variables in java
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class
Java Variable Example: Add Two Numbers
class Simple
{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Java Variable Example: Narrowing (Typecasting)
class Simple
{
public static void main(String[] args){
float f=10.5f;
//int a=f; //Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}}
Get Integer Input From the User
There are several ways to get input from the user in Java. You will learn to get input
by using Scanner object in this article.
need to import Scanner class using:
import java.util.Scanner;
Then, we will create an object of Scanner class which will be used to get input from
the user.
Scanner input = new Scanner(System.in);
int number = input.nextInt();
EXAMPLE-
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("You entered " + number);
}
}
Here, input object of Scanner class is created. Then, the nextInt() method of the
Scanner class is used to get integer input from the user.
To get long, float, double and String input from the user, you can use nextLong(),
nextFloat(), nextDouble() and next() methods respectively.
Sum of two numbers using Scanner
import java.util.Scanner;
public class AddTwoNumbers2 {
public static void main(String[] args) {
int num1, num2, sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();
System.out.println("Enter Second Number: ");
num2 = sc.nextInt();
sc.close();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Java Program to get input from user(String)
using Scanner class to get the input. we are getting input String, integer and a float
number. For this we are using following methods:
public String nextLine(): For getting input String
import java.util.Scanner;
class GetInputData
{
public static void main(String args[])
{
int num;
float fnum;
String str;
Scanner in = new Scanner(System.in);
//Get input String
System.out.println("Enter a string: ");
str = in.nextLine();
System.out.println("Input String is: "+str);
•PRACTICE SESSION
•Java Program to Add two float, Double Numbers input by user
•Java Program to Multiply two numbers input by user.
•Java program to calculate area of Triangle.
•Java program to calculate area of Circle.
•Java program to create a calculator .
//Get input Integer
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);
}
}
Operators in java
Operator in java is a symbol that is used to perform
operations. For example: +, -, *, / etc.
There are many types of operators in java which are given
below:
•Unary Operator,
•Arithmetic Operator,
•Shift Operator,
•Relational Operator,
•Bitwise Operator,
•Logical Operator,
•Ternary Operator and
•Assignment Operator
Java Operator Precedence
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative * / %
additive + -
Shift shift << >> >>>
Relational comparison < > <= >=
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ? :
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=
>>>=
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:
•incrementing/decrementing a value by one
•negating an expression
•inverting the value of a boolean
Java Unary Operator Example: ++ and –
class OperatorExample
{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
Java Unary Operator Example 2: ++ and --
class OperatorExample
{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}}
Java Unary Operator Example: ~ and !
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}}
Java Arithmetic Operator Example
class OperatorExample
{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Java Arithmetic Operator Example: Expression
class OperatorExample
{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}
Program to read two integer and print product of them
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
/* This reads the input provided by user
* using keyboard
*/
Scanner scan = new Scanner(System.in);
System.out.print("Enter first number: ");
// This method reads the number provided using
//keyboard
int num1 = scan.nextInt();
System.out.print("Enter second number: ");
int num2 = scan.nextInt();
// Closing Scanner after the use
scan.close();
// Calculating product of two numbers
int product = num1*num2;
// Displaying the multiplication result
System.out.println("Output:
"+product);
}
}
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
Java Left Shift Operator Example
class OperatorExample
{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}
Java Right Shift Operator
The Java right shift operator >> is used to move left operands value to right by the
number of bits specified by the right operand.
Java Right Shift Operator Example
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check second condition if first condition is false. It
checks second condition only if first one is true.
The bitwise & operator always checks both conditions whether first condition is true or
false.
class OperatorExample
{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check second condition if first condition is true. It checks
second condition only if first one is false.
The bitwise | operator always checks both conditions whether first condition is true or
false.
class OperatorExample
{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}
Java Ternary Operator
Java Ternary operator is used as one liner replacement for if-then-else statement and
used a lot in java programming. it is the only conditional operator which takes three
operands.
Java Ternary Operator Example
class OperatorExample
{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
/Program to Find greatest of three numbers using Conditional Operator
import java.util.Scanner; //program uses Scanner class
public class ConditionalOperator
{
public static void main(String[] args)
{
int a,b,c,result;
//create Scanner object to obtain input from keyboard
Scanner input=new Scanner(System.in);
System.out.print("Enter the Three Number : "); //prompt for input
a=input.nextInt(); //Read First number
b=input.nextInt(); //Read Second number
c=input.nextInt(); //Read third number
result = (a>b)? ((a>c)?a:c) : ((b>c)?b:c);
System.out.println( result + " is Greatest");
}
}
Java Assignment Operator
Java assignment operator is one of the most common operator. It is used to assign the
value on its right to the operand on its left.
Java Assignment Operator Example
class OperatorExample
{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Java Assignment Operator Example: Adding short
class OperatorExample
{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}
Output:
Compile time error
Control Statements
Java If-else Statement
The Java if statement is used to test the condition. It checks boolean
condition: true or false. There are various types of if statement in java.
if statement
if-else statement
if-else-if ladder
nested if statement
Java if Statement
The Java if statement tests the condition. It executes
the if block if condition is true.
Syntax:
if(condition)
{
//code to be executed
}
//Java Program to demonstate the use of if statement.
public class IfExample
{
public static void main(String[] args)
{
//defining an 'age' variable
int age=20;
//checking the age
if(age>18)
{
System.out.print("Age is greater than 18");
}
}
}
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition
is true otherwise else block is executed.
Syntax:
if(condition)
{
//code if condition is true
}
Else
{
//code if condition is false
}
Java Program to demonstrate If statement
public class Sample{
public static void main(String args[])
{
int a=20, b=30;
if(b>a)
System.out.println("b is greater");
}
}
Java Program to demonstrate If –else statement
public class Sample {
public static void main(String args[]) {
int a = 80, b = 30;
if (b > a)
{
System.out.println("b is greater");
}
else
{
System.out.println("a is greater");
}
}
}
Java program is used to toss a coin using Java random class.
• Java Math.random() returns a random value between 0.0 and 1.0 each
time.
• If value is below 0.5 then it's Heads or otherwise Tails.
Import java.lang.Math;
public class JavaFlip
{
public static void main(String[] args) {
if (Math.random() < 0.5)
{
System.out.println("Heads");
}else{
System.out.println("Tails");
}
}
}
The basic format of else if statement is:
if(test_expression)
{
//execute your code
}
else if(test_expression n)
{
//execute your code
}
else
{
//execute your code
}
public class Sample {
public static void main(String args[]) {
int a = 30, b = 30;
if (b > a) {
System.out.println("b is greater");
}
else if(a > b){
System.out.println("a is greater");
}
else {
System.out.println("Both are equal");
}
}
}
Java program is used to demonstrates a comparison of two strings.
• Java equals() method is used to compare strings.
• Java equalsIgnoreCase() method can ignore the case.
• We cannot use == operator to compare two strings.
public class EqualCheck {
public static void main(String args[]){
String a = "AVATAR";
String b = "avatar";
if(a.equals(b)){
System.out.println("Both strings are equal.");
} else {
System.out.println("Both strings are not equal.");
}
if(a.equalsIgnoreCase(b)){
System.out.println("Both strings are equal.");
} else {
System.out.println("Both strings are not equal.");
}
} }
String a = "AVATAR";
String b = "avatar";
First String type variable a is storing the string value AVATAR, and the
second variable b is storing the string value avatar.
It is to be noted that both variables a and b will generate different ASCII
(American Standard Code for Information Interchange) values, and the
string comparison is checked based on the ASCII values among two or
more strings.
a.equals(b) is a pre-defined method of Java String Class which checks
whether two given and initialized strings are equal or not. If found equal,
the statement System.out.println ("Both strings are equal."); will get
printed else this statement System.out.println ("Both strings are not
equal."); gets printed.
Java switch statement is used when you have multiple
possibilities for the if statement.
Java switch statement
The basic format of the switch statement is:
switch(variable)
{
case 1:
//execute your code
break;
case n:
//execute your code
break;
default:
//execute your code
break;
}
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
PRACTICE SESSION
•Java Program to Check Even or Odd Number.
•Java program to find factorial of a given number using recursion.
•Java program to check prime number.
•Java program to find the greater number in three no’s input by user.
•Java program to find the smaller number in three no’s input by user.
•Java Program to demonstrate the use of If else-if ladder.
It is a program of grading system for fail, D grade, C grade, B grade, A grade and
A+.
•Java Program to demonstrate the use of Nested If Statement. Input User age
and weight if age is 18 and weight is greater than 50 than only he can donate
blood.
•Program to check whether the given number is positive or negative
•Read two integer or floating point numbers and display the multiplication
Java while and do...while Loop
Loop is used in programming to repeat a specific block of code.
How while loop works?
The test expression inside parenthesis is a boolean expression.
If the test expression is evaluated to true,
statements inside the while loop are executed.
then, the test expression is evaluated again.
This process goes on until the test expression is evaluated to false.
If the test expression is evaluated to false,
while loop is terminated.
Example : Java while Loop
// Program to find the sum of natural numbers from 1 to 100.
class AssignmentOperator {
public static void main(String[] args) {
int sum = 0, i = 100;
while (i != 0) {
sum += i; // sum = sum + i;
--i;
}
System.out.println("Sum = " + sum);
}
}
import java.util.Scanner;
class Convert{
public static void main(String[] args) {
int n, count = 0, a;
String x = "";
Scanner s = new Scanner(System.in);
System.out.print("Enter any decimal number:");
n = s.nextInt();
while(n > 0)
{
a = n % 2;
// if(a == 1) {
// count++;
//}
x = x + "" + a;
n = n / 2;
}
System.out.println("Binary number:"+x);
// System.out.println("No. of 1s:"+count);
}
}
Java while loop break continue program
import java.util.Scanner;
class BreakContinueWhileLoop {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Input an integer");
n = input.nextInt();
if (n != 0) {
System.out.println("You entered " + n);
continue;
}
else {
break;
}
}
}
}
Finding factorial of a number entered by user
import java.util.Scanner;
public class JavaExample {
public static void main(String[] args) {
//We will find the factorial of this number
int number;
System.out.println("Enter the number: ");
Scanner scanner = new Scanner(System.in);
number = scanner.nextInt();
scanner.close();
long fact = 1;
int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
class UserInputSum {
public static void main(String[] args) {
Double number, sum = 0.0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a number: ");
number = input.nextDouble();
if (number < 0.0) {
break;
}
sum += number;
}
System.out.println("Sum = " + sum);
}
}
calculates the sum of numbers entered by the user until user enters a negative
number.
Java do while loop
Java do while loop is used to execute a block of statements continuously until the given
condition is true. do while loop in java is similar to while loop except that the condition
is check after the statements are executed, so do while loop guarantees the loop
execution at least once.
EXAMPLE-
class JavaDoWhileLoop {
public static void main(String[] args) {
int i = 5;
do {
System.out.println(i);
i++;
} while (i <= 10);
}
}
EXAMPLE-
class DoWhileLoopExample
{
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
Calculates the sum of numbers entered by the user until user enters 0.
import java.util.Scanner;
class Sum {
public static void main(String[] args) {
Double number, sum = 0.0;
Scanner input = new Scanner(System.in);
do {
System.out.print("Enter a number: ");
number = input.nextDouble();
sum += number;
} while (number != 0.0);
System.out.println("Sum = " + sum);
}
}
public class DoWhileExample2
{
public static void main(String[] args)
{
do{
System.out.println("infinitive do while loop");
}while(true);
}
}
Java Infinitive do-while Loop
Java for Loop
The syntax of for Loop in Java is:
for (initialization; testExpression; update)
{
// codes inside for loop's body
}
Example 1: for Loop
// Program to print a sentence 10 times
class Loop {
public static void main(String[] args)
{
for (int i = 1; i <= 10; ++i)
{
System.out.println("Line " + i);
}
}
}
infinite for Loop
If the test expression is never false, for loop will run forever. This is called infinite for
loop. Let's take an example:
// Infinite for Loop
class Infinite {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; --i) {
System.out.println("Hello");
}
}
}
Here's an another example of infinite for loop.
for ( ; ; ) {
}
Program to print fibonacci series using for loop
public class JavaExample {
public static void main(String[] args) {
int count = 7, num1 = 0, num2 = 1;
System.out.print("Fibonacci Series of "+count+" numbers:");
for (int i = 1; i <= count; ++i)
{
System.out.print(num1+" ");
/* On each iteration, we are assigning second number
* to the first number and assigning the sum of last two
* numbers to the second number
*/
int sum = num1 + num2;
num1 = num2;
num2 = sum;
}
}
}
public class Pattern {
public static void main(String[] args) {
int rows = 5, k = 0;
for(int i = 1; i <= rows; ++i, k = 0) {
for(int space = 1; space <= rows - i; ++space) {
System.out.print(" ");
}
while(k != 2 * i - 1) {
System.out.print("* ");
++k;
}
System.out.println();
}
} }
Java for-each Loop (Enhanced for Loop)
In Java, there is another form of for loop (in addition to standard for loop)
to work with arrays and collection, the enhanced for loop.
• It starts with the keyword for like a normal for-loop.
• Instead of declaring and initializing a loop counter variable, declare a
variable that is the same type as the base type of the array, followed
by a colon, which is then followed by the array name.
• In the loop body, can use the loop variable created rather than
using an indexed array element.
• It’s commonly used to iterate over an array or a Collections class (eg,
ArrayList)
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;
}
The for-each loop introduced in Java5. It is mainly used to traverse array or
collection elements. The advantage of for-each loop is that it eliminates the
possibility of bugs and makes the code more readable.
Example-
class ForEachExample1
{
public static void main(String args[])
{
int arr[]={12,13,14,44};
for(int i:arr){
System.out.println(i);
}
}
}
example to iterate through elements of an array using standard for loop:
class ForLoop
{
public static void main(String[] args)
{
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
for (int i = 0; i < vowels.length; ++ i)
{
System.out.println(vowels[i]);
}
}
}
using for-each loop as follows:
class AssignmentOperator
{
public static void main(String[] args)
{
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
// foreach loop
for (char item: vowels)
{
System.out.println(item);
}
}
}
Note:-If we are working with arrays and collections, can use alternative syntax of for
loop (enhanced form of for loop) to iterate through items of arrays/collections.
Java - Numbers Class
Normally, when we work with Numbers, we use primitive data types such as byte, int,
long, double, etc.
Example
int i = 5000;
float gp = 13.65;
In development, we come across situations where we need to use objects
instead of primitive data types. In order to achieve this, Java provides wrapper
classes.
All the wrapper classes
(Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class
Number.
The object of the wrapper class contains or wraps its respective primitive data
type. Converting primitive data types into object is called boxing, and this is
taken care by the compiler. Therefore, while using a wrapper class you just need
to pass the value of the primitive data type to the constructor of the Wrapper
class.
And the Wrapper object will be converted back to a primitive data type, and this
process is called unboxing. The Number class is part of the java.lang package.
Example-
public class Test {
public static void main(String args[]) {
Integer x = 5; // boxes int to an Integer object
x = x + 10; // unboxes the Integer to a int
System.out.println(x);
}
}
When x is assigned an integer value, the compiler boxes the integer because x
is integer object. Later, x is unboxed so that they can be added as an integer.
Number Methods
Following is the list of the instance methods that all the subclasses
of the Number class implements −
Sr.No. Method & Description
1 xxxValue()Converts the value of this Number object to the xxx
data type and returns it.
2 compareTo()Compares this Number object to the argument.
3 equals()Determines whether this number object is equal to the
argument.
4 valueOf()Returns an Integer object holding the value of the
specified primitive.
5 toString()Returns a String object representing the value of a
specified int or Integer.
6 parseInt()This method is used to get the primitive data type of a
certain String.
7 abs()Returns the absolute value of the argument.
8 round()Returns the closest long or int, as indicated by the method's
return type to the argument.
9 min()Returns the smaller of the two arguments.
10 max()Returns the larger of the two arguments.
11 pow()Returns the value of the first argument raised to the power of
the second argument
12 sqrt()Returns the square root of the argument.
13 random()Returns a random number.
Java - xxxValue() Method
The method converts the value of the Number Object that invokes the
method to the primitive data type that is returned from the method.
• int intValue()
• long longValue()
• float floatValue()
• double doubleValue()
Return Value
This method returns the primitive data type that is given in the signature.
Example
public class value{
public static void main(String args[]) {
Integer x = 5;
// Returns byte primitive data type
System.out.println( x.byteValue() );
// Returns double primitive data type
System.out.println(x.doubleValue());
// Returns long primitive data type
System.out.println( x.longValue() );
}
}
Java - compareTo() Method
The method compares the Number object that invoked the method to the
argument. It is possible to compare Byte, Long, Integer, etc.
However, two different types cannot be compared, both the argument and the
Number object invoking the method should be of the same type.
Syntax
public int compareTo( NumberSubClass referenceName )
Return Value
• If the Integer is equal to the argument then 0 is returned.
• If the Integer is less than the argument then -1 is returned.
• If the Integer is greater than the argument then 1 is returned.
Example
public class Test
{
public static void main(String args[])
{
Integer x = 5;
System.out.println(x.compareTo(3));
System.out.println(x.compareTo(5));
System.out.println(x.compareTo(8));
}
}
Java - equals() Method
The method determines whether the Number object that invokes the method is equal to
the object that is passed as an argument.
Syntax
public boolean equals(Object o)
Return Value
The method returns True if the argument is not null and is an object of
the same type and with the same numeric value. There are some extra
requirements for Double and Float objects that are described in the Java
API documentation.
Example
public class Test
{
public static void main(String args[])
{
Integer x = 5;
Integer y = 10;
Integer z =5;
Short a = 5;
System.out.println(x.equals(y));
System.out.println(x.equals(z));
System.out.println(x.equals(a));
}
}
Java - valueOf() Method
The valueOf method returns the relevant Number Object holding the value of the
argument passed. The argument can be a primitive data type, String, etc.
This method is a static method. The method can take two arguments, where one is a
String and the other is a radix.
Syntax
Following are all the variants of this method −
static Integer valueOf(int i)
static Integer valueOf(String s)
static Integer valueOf(String s, int radix)
Return Value
valueOf(int i) − This returns an Integer object holding the value of the
specified primitive.
valueOf(String s) − This returns an Integer object holding the value of the
specified string representation.
valueOf(String s, int radix) − This returns an Integer object holding the integer
value of the specified string representation, parsed with the value of radix.
EXAMPLE-
public class Test
{
public static void main(String args[]) {
Integer x =Integer.valueOf(9);
Double c = Double.valueOf(5);
Float a = Float.valueOf("80");
Integer b = Integer.valueOf("444",16);
System.out.println(x);
System.out.println(c);
System.out.println(a);
System.out.println(b);
}
}
Java - parseInt() Method
This method is used to get the primitive data type of a certain String. parseXxx() is a
static method and can have one argument or two.
Syntax
Following are all the variants of this method −
static int parseInt(String s)
static int parseInt(String s, int radix)
Return Value
parseInt(String s) − This returns an integer (decimal only).
parseInt(int i) − This returns an integer, given a string representation of decimal,
binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as
input.
Example
public class Test {
public static void main(String args[]) {
int x =Integer.parseInt("9");
double c = Double.parseDouble("5");
int b = Integer.parseInt("444",16);
System.out.println(x);
System.out.println(c);
System.out.println(b);
}
}
Java - max() Method
This method gives the maximum of the two arguments. The argument can
be int, float, long, double.
Syntax
This method has the following variants −
• double max(double arg1, double arg2)
• float max(float arg1, float arg2)
• int max(int arg1, int arg2)
• long max(long arg1, long arg2)
Example
public class Test
{
public static void main(String args[])
{
System.out.println(Math.max(12.123, 12.456));
System.out.println(Math.max(23.12, 23.0));
}
}
Example-
public class Test {
public static void main(String args[]) {
System.out.println( Math.random() );
System.out.println( Math.random() );
}
}
Java - Character Class
Example
char ch = 'a';
// an array of chars
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };
Escape Sequences
A character preceded by a backslash () is an escape sequence and has a
special meaning to the compiler.
The newline character (n) has been used frequently in this tutorial in
System.out.println() statements to advance to the next line after the string is
printed.
Escape Sequence Description
t Inserts a tab in the text at this point.
b Inserts a backspace in the text at this point.
n Inserts a newline in the text at this point.
' Inserts a single quote character in the text at
this point.
" Inserts a double quote character in the text
at this point.
 Inserts a backslash character in the text at
this point.
Example:-
public class Test {
public static void main(String args[])
{
System.out.println("She said "Hello!" to me.");
}
}
This will produce the following result −
Output
She said "Hello!" to me.
Sr.No. Method & Description
1 isLetter()Determines whether the specified char value is a letter.
2 isDigit()Determines whether the specified char value is a digit.
3 isWhitespace()Determines whether the specified char value is white
space.
4 isUpperCase()Determines whether the specified char value is
uppercase.
5 isLowerCase()Determines whether the specified char value is
lowercase.
6 toUpperCase()Returns the uppercase form of the specified char
value.
7 toLowerCase()Returns the lowercase form of the specified char
value.
8 toString()Returns a String object representing the specified
character value that is, a one-character string.
Character Methods
Following is the list of the important instance methods that all the
subclasses of the Character class implement −
Java - isLetter() Method
The method determines whether the specified char value is a letter.
Syntax
boolean isLetter(char ch)
Example
public class Test
{
public static void main(String args[])
{
System.out.println(Character.isLetter('c'));
System.out.println(Character.isLetter('5'));
}
}
Java - isUpperCase() Method
This method determines whether the specified char value is uppercase.
Syntax
Boolean isUpperCase(char ch)
Example
public class Test {
public static void main(String args[]) {
System.out.println(Character.isUpperCase('c'));
System.out.println(Character.isUpperCase('C'));
System.out.println(Character.isUpperCase('n'));
System.out.println(Character.isUpperCase('t'));
}
}
Java - toLowerCase() Method
The method returns the lowercase form of the specified char value.
Syntax
char toLowerCase(char ch)
Example
public class Test
{
public static void main(String args[])
{
System.out.println(Character.toLowerCase('c'));
System.out.println(Character.toLowerCase('C'));
}
}
Java - toString() Method
This method returns a String object representing the specified character
value, that is, a one-character string.
Syntax
String toString(char ch)
Example
public class Test {
public static void main(String args[]) {
System.out.println(Character.toString('c'));
System.out.println(Character.toString('C'));
}
}
public class Example
{
public static void main(String args[])
{
//creating a string by java string literal
String str = "Beginnersbook";
char arrch[]={'h','e','l','l','o'};
//converting char array arrch[] to string str2
String str2 = new String(arrch);
//creating another java string str3 by using new keyword
String str3 = new String("Java String Example");
//Displaying all the three strings
System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}
}
Program to print pyramid using numbers
1
121
12321
1234321
123454321
public class Pattern
{
public static void main(String[] args)
{
// Create a new Scanner object
Scanner scanner = new Scanner(System.in);
// Get the number of rows from the user
System.out.println("Enter the number of rows to print
the pattern ");
int rows = scanner.nextInt();
System.out.println("** Printing the pattern... **");
for (int i = 1; i <= rows; i++)
{
for (int j = rows; j > i; j--)
{
System.out.print(" ");
}
for (int k = 1; k <= i; k++)
{
System.out.print(k);
}
for (int l = i - 1; l >= 1; l--)
{
System.out.print(l);
}
System.out.println();
}
}
}
import java.util.Scanner;
public class Pattern2
{
public static void main(String[] args)
{
// Create a new Scanner object
Scanner scanner = new Scanner(System.in);
// Get the number of rows from the user
System.out.println("Enter the number of rows to print the pattern
");
int rows = scanner.nextInt();
System.out.println("** Printing the pattern... **");
for (int i = rows; i >= 1; i--)
{
for (int j = 1; j < i; j++)
{
System.out.print(" ");
}
for (int k = i; k <= rows; k++)
{
System.out.print(k + " ");
}
System.out.println();
}
}
}
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
Java - Strings Class
A Java String contains an immutable sequence of Unicode characters. Unlike C/C+
+, where string is simply an array of char, A Java String is an object of the class
java.lang.
Java String is, however, special. Unlike an ordinary class:
String is associated with string literal in the form of double-quoted texts such as
"Hello, world!". We can assign a string literal directly into a String variable,
instead of calling the constructor to create a String instance.
The '+' operator is overloaded to concatenate two String operands. '+' does not
work on any other objects such as Point and Circle.
String is immutable. That is, its content cannot be modified once it is created. For
example, the method toUpperCase() constructs and returns a new String instead
of modifying the its existing content.
Creating Strings
The most direct way to create a string is to write −
String greeting = "Hello world!";
Whenever it encounters a string literal in code, the compiler creates a
String object with its value in this case, "Hello world!'.
As with any other object, we can create String objects by using the new
keyword and a constructor.
The String class has 11 constructors that allow us to provide the initial value
of the string using different sources, such as an array of characters.
Example
public class StringDemo
{
public static void main(String args[])
{
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
String Methods
1.int length(): Returns the number of characters in the String.
"GeeksforGeeks".length(); // returns 13
2.Char charAt(int i): Returns the character at index.
"GeeksforGeeks".charAt(3); // returns ‘k’
3.String substring (int i): Return the substring from the ith
index
character to end.
"GeeksforGeeks".substring(3); // returns “ksforGeeks”
4.String substring (int i, int j): Returns the substring from i to j-1
index.
"GeeksforGeeks".substring(2, 5); // returns “eks”
5.String concat( String str): Concatenates specified string to the
end of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”
6. int indexOf (String s): Returns the index within the string of the first
occurrence of the specified string.
String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6
7.int indexOf (String s, int i): Returns the index within the string of the
first occurrence of the specified string, starting at the specified index.
String s = ”Learn Share Learn”;
int output = s.indexOf(‘a’,3); // returns 8
8.Int lastindexOf( int ch): Returns the index within the string of the last
occurrence of the specified string.
String s = ”Learn Share Learn”;
int output = s.lastindexOf(‘a’); // returns 14
9.boolean equals( Object otherObj): Compares this string to the
specified object.
Boolean out = “Geeks”.equals(“Geeks”); // returns true
Boolean out = “Geeks”.equals(“geeks”); // returns false
10. int compareTo( String anotherString): Compares two string
lexicographically.
int out = s1.compareTo(s2); // where s1 ans s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out >0 // s1 comes after s2.
11. String toLowerCase(): Converts all the characters in the String to
lower case.
String word1 = “HeLLo”;
String word3 = word1.toLowerCase(); // returns “hello"
12. String toUpperCase(): Converts all the characters in the String to
upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”
13.String trim(): Returns the copy of the String, by removing
whitespaces at both ends. It does not affect whitespaces in the
middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”
14. String replace (char oldChar, char newChar): Returns new string
by replacing all occurrences of oldChar with newChar.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns
“geeksgorgeeks”

More Related Content

Similar to JAVA.ppsx java code java edv java development (20)

JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
SuganthiDPSGRKCW
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
Mohit Belwal
 
Java programming(unit 1)
Java programming(unit 1)Java programming(unit 1)
Java programming(unit 1)
Dr. SURBHI SAROHA
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01
Jay Palit
 
Java Basic.pdf
Java Basic.pdfJava Basic.pdf
Java Basic.pdf
TechSearchWeb
 
Java course in Chandigarh.pdf
Java course in Chandigarh.pdfJava course in Chandigarh.pdf
Java course in Chandigarh.pdf
ExcellenceTechnology9
 
What is-java
What is-javaWhat is-java
What is-java
Shahid Rasheed
 
J introtojava1-pdf
J introtojava1-pdfJ introtojava1-pdf
J introtojava1-pdf
Emmanuel Alimpolos
 
Java ms harsha
Java ms harshaJava ms harsha
Java ms harsha
Harsha Batra
 
Java ppt1
Java ppt1Java ppt1
Java ppt1
nikhilsh66131
 
Learn Java Part 1
Learn Java Part 1Learn Java Part 1
Learn Java Part 1
Gurpreet singh
 
Java programming Evolution-OverviewOfJava.pdf
Java programming Evolution-OverviewOfJava.pdfJava programming Evolution-OverviewOfJava.pdf
Java programming Evolution-OverviewOfJava.pdf
AbhishekSingh961152
 
JRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAJRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVA
Mehak Tawakley
 
1. Java Project Guidance for engineering
1. Java Project Guidance for engineering1. Java Project Guidance for engineering
1. Java Project Guidance for engineering
vyshukodumuri
 
Java Introduction | PDF
Java Introduction |  PDFJava Introduction |  PDF
Java Introduction | PDF
Geekster
 
Iintroduction to java , Java Coding , basics of java.pptx
Iintroduction to java , Java Coding , basics of java.pptxIintroduction to java , Java Coding , basics of java.pptx
Iintroduction to java , Java Coding , basics of java.pptx
MayankParashar31
 
java intro.pptx
java intro.pptxjava intro.pptx
java intro.pptx
MangaiyarkarasiDurai
 
What is java
What is javaWhat is java
What is java
javaicon
 
Ch2
Ch2Ch2
Ch2
Uğurcan Uzer
 
Unit 1 part 1 introduction to java
Unit 1 part 1 introduction to javaUnit 1 part 1 introduction to java
Unit 1 part 1 introduction to java
DrArpanaChaturvedi
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
SuganthiDPSGRKCW
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
Mohit Belwal
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01
Jay Palit
 
Java programming Evolution-OverviewOfJava.pdf
Java programming Evolution-OverviewOfJava.pdfJava programming Evolution-OverviewOfJava.pdf
Java programming Evolution-OverviewOfJava.pdf
AbhishekSingh961152
 
JRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAJRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVA
Mehak Tawakley
 
1. Java Project Guidance for engineering
1. Java Project Guidance for engineering1. Java Project Guidance for engineering
1. Java Project Guidance for engineering
vyshukodumuri
 
Java Introduction | PDF
Java Introduction |  PDFJava Introduction |  PDF
Java Introduction | PDF
Geekster
 
Iintroduction to java , Java Coding , basics of java.pptx
Iintroduction to java , Java Coding , basics of java.pptxIintroduction to java , Java Coding , basics of java.pptx
Iintroduction to java , Java Coding , basics of java.pptx
MayankParashar31
 
What is java
What is javaWhat is java
What is java
javaicon
 
Unit 1 part 1 introduction to java
Unit 1 part 1 introduction to javaUnit 1 part 1 introduction to java
Unit 1 part 1 introduction to java
DrArpanaChaturvedi
 

Recently uploaded (20)

Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Ad

JAVA.ppsx java code java edv java development

  • 14. Tools You Will Need need the following softwares − •Linux 7.1 or Windows xp/7/8 operating system •Java JDK 8 •Microsoft Notepad or any other text editor Popular Java Editors To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. 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/
  • 15. https://www.guru99.com/install-java.html OR https://www.oracle.com/technetwork/java/javase/downloads/index.html How to Download & Install Java JDK 8 in Windows https://www.youtube.com/watch?v=jRZZUzqJ7S0 How to install Java on Windows OS - Video
  • 16. How do I become a good Java programmer? •Get your basics clear – •Read documentation and open source frameworks source code – •Practice Coding – •Group discussions and read books – •Subscribe to forums – •Undertake projects – •Dedicate yourself –
  • 17. History of Java James Gosling initiated Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's office, also went by the name ‘Green’ and ended up later being renamed as Java, from a list of random words. Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms. On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL). On 8 May, 2007, Sun finished the process, making all of Java's core code free and open- source, aside from a small portion of code to which Sun did not hold the copyright.
  • 18. Features of Java Programming Language Java is platform independent Java was built with the philosophy of "write once, run anywhere" (WORA). The Java code (pure Java code and libraries) you write on one platform (operating system) will run on other platforms with no modification. To run Java, an abstract machine called Java Virtual Machine (JVM) is used. The JVM executes the Java bytecode. Then, the CPU executes the JVM. Since all JVMs works exactly the same, the same code works on other operating systems as well, making Java platform- independent. An object-oriented Language There are different styles of programming. Object-oriented approach is one of the popular programming styles. In object-oriented programming, a complex problem is divided into smaller sets by creating objects. This makes your code reusable, has design benefits, and makes code easier to maintain. Many programming languages including Java, Python, and C++ has object-oriented features. If you are serious about programming, you should definitely learn object-oriented style of programming.
  • 19. Java is fast The earlier versions of Java were criticized for being slow. However, things are completely different now. The new JVMs are significantly faster. And, the CPU that executes JVM are also getting more and more powerful. Now, Java is one of the fastest programming languages. Well optimized Java code is nearly as fast as lower level languages like C/C++, and much faster than Python, PHP etc. Java is secure The Java platform provides various features for security of Java applications. Some of the high-level features that Java handles are: - provides secure platform for developing and running applications - automatic memory management, reduces memory corruption and vulnerabilities - provides secure communication by protecting the integrity and privacy of data transmitted
  • 20. Large Standard Library One of the reasons why Java is widely used is because of the availability of huge standard library. The Java environment has hundreds of classes and methods under different packages to help software developers like us. For example, java.lang - for advanced features of strings, arrays etc. java.util - for data structures, regular expressions, date and time functions etc. java.io - for file i/o, exception handling etc.
  • 21. Java Terminologies You Need to Know Before You Start Learning a new programming language can be challenging. You will hear a lot of new terms which can be overwhelming for a newbie. So, here decided to explain a few terms that you are likely to hear in the world of Java programming language. Java - Java is a set of technologies (programming language and computing platform) for creating and running software. However, Java is often used to refer Java programming language for simplicity. Java programming language - A powerful, general-purpose, platform-independent, object- oriented programming language. Java 8 - Java 8 is the latest major release for Java. Our Java tutorial will include all major features of Java 8.
  • 22. Java EE, Java ME and Java SE - Java EE, Java ME and Java SE stands for Java Platform Enterprise Edition, Micro Edition, and standard edition respectively. Java EE is targeted for applications which run on servers. Java ME is targeted for resource limited devices like: embedded devices. And, Java SE is the basic Java environment used for creating standard programs. If you are a java programming newbie, we recommend you to start with J2SE. JVM - JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a Java program. JRE - JRE (Java Runtime Environment) contains JVM, supporting libraries, and other components to run a Java program. However, it doesn't contain any compiler and debugger. JDK - JDK (Java Development Kit) contains JRE and tools such as compilers and debuggers for developing Java applications.
  • 23. Run Java on your OS Run Java on Windows (XP, 7, 8 and 10) To run Java Programming in Windows, you'll need to install two things: JAVA SE Development Kit (JDK) and IDE to create your Java Projects. Follow this step by step guide to get started. Install Java •Go to the Downloads page of Java Standard Edition Development Kit. •Under Java SE Development Kit section, click Accept License agreement at the top of the table. Then, click the download link for Windows (x64) if you have a 64-bit system, or Windows (x86) if you have a 32-bit system.
  • 24. •After download, open the setup file and follow the instructions. Click Next. Select all features by selecting "This feature will be installed on local hard drive" and copy the installation location (highlighted by yellow) in a Notepad. And, click next again.
  • 25. •During the installation, you'll be prompted to install JRE. Click Next and you're done. Click the Finish button to complete the installation . •Now, you need to edit the PATH variable. Go to Control Panel > System and Security > System. Click on Advanced system settings on the left to get System Properties window.
  • 26. •Click on Environment Variables. Then, on the lower System variables section, find Path and click Edit on the following window. Click Ok to save the changes. To check if Java was properly installed, open Command Prompt by typing cmd in Windows search or using Run window (Windows Key + R), and type java -version to get similar output as below. If you do, congratulations you've successfully installed Java. If not, check the Oracle's Download Help.
  • 28. Java Version History Many java versions have been released till now. The current stable release of Java is Java SE 11. •JDK Alpha and Beta (1995) •JDK 1.0 (23rd Jan 1996) •JDK 1.1 (19th Feb 1997) •J2SE 1.2 (8th Dec 1998) •J2SE 1.3 (8th May 2000) •J2SE 1.4 (6th Feb 2002) •J2SE 5.0 (30th Sep 2004) •Java SE 6 (11th Dec 2006) •Java SE 7 (28th July 2011) •Java SE 8 (18th March 2014) •Java SE 9 (21st Sep 2017) •Java SE 10 (20th March 2018) •Java SE 11
  • 29. Application According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some of them are as follows: •Desktop Applications such as acrobat reader, media player, antivirus, etc. •Web Applications such as irctc.co.in, javatpoint.com, etc. •Enterprise Applications such as banking applications. •Mobile •Embedded System •Smart Card •Robotics •Games, etc.
  • 30. 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. AWT and Swing are used in Java for creating standalone applications. 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, Hibernate, 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 enterprise application. It has advantages of the 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.
  • 31. Java Platforms / Editions There are 4 platforms or editions of Java: 1) Java SE (Java Standard Edition) It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc. 2) Java EE (Java Enterprise Edition) It is an enterprise platform which is mainly used to develop web and enterprise applications. It is built on the top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc. 3) Java ME (Java Micro Edition) It is a micro platform which is mainly used to develop mobile applications. 4) JavaFX It is used to develop rich internet applications. It uses a light-weight user interface API. FX is normally related with sound or visual effects
  • 32. Basic Syntax 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. Example: public void myMethodName() 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). 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.
  • 33. Data Types in Java Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java: •Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double. •Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays. Java Primitive Data Types In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java language. There are 8 types of primitive data types: •boolean data type •byte data type •char data type •short data type •int data type •long data type •float data type •double data type
  • 35. Data Type Default Value Default size boolean false 1 bit char 'u0000' 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0L 8 byte float 0.0f 4 byte double 0.0d 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. The Boolean data type specifies one bit of information, but its "size" can't be defined precisely. Example: Boolean one = false
  • 36. Byte Data Type The byte data type is an example of primitive data type. It is an 8-bit signed two's complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default value is 0. The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type. Example: byte a = 10, byte b = -20 Int Data Type The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0. The int data type is generally used as a default data type for integral values unless if there is no problem about memory. Example: int a = 100000, int b = -200000
  • 37. Long Data Type The long data type is a 64-bit two's complement integer. Its value-range lies between - 9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a range of values more than those provided by int. Example: long a = 100000L, long b = -200000L Float Data Type The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is unlimited. It is recommended to use a float (instead of double) if you need to save memory in large arrays of floating point numbers. The float data type should never be used for precise values, such as currency. Its default value is 0.0F. Example: float f1 = 234.5f
  • 38. Double Data Type The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type is generally used for decimal values just like float. The double data type also should never be used for precise values, such as currency. Its default value is 0.0d. Example: double d1 = 12.3 Char Data Type The char data type is a single 16-bit Unicode character. Its value-range lies between ' u0000' (or 0)(as java uses Unicode system not ASCII code system) to 'uffff' (or 65,535 inclusive).The char data type is used to store characters. Example: char letterA = 'A'
  • 39. •Unicode is a character encoding standard that has widespread acceptance. Microsoft software uses Unicode at its core. Whether you realize it or not, you are using Unicode already! Basically, “computers just deal with numbers. They store letters and other characters by assigning a number for each one. Before Unicode was invented, there were hundreds of different encoding systems for assigning these numbers. No single encoding could contain enough characters.” •The u0000 is the lowest range of Unicode system •Unicode is an industry standard character set encoding developed and maintained by The Unicode® Consortium. The Unicode character set has the capacity to support over one million characters, and is being developed with an aim to have a single character set that supports all characters from all scripts, as well as many symbols, that are in common use around the world today or in the past. Currently, the Standard supports over 96,000 characters representing a large number of scripts. The benefits of a single, universal character set and the practical considerations for implementation that have gone into the design of Unicode have made it a success, and it is well on the way to becoming a dominant. What is Unicode? and Why do I need to use Unicode?
  • 40. Before Unicode, there were many language standards: •ASCII (American Standard Code for Information Interchange) for the United States. •ISO 8859-1 for Western European Language. •KOI-8 for Russian. •GB18030 and BIG-5 for Chinese, and so on. Why java uses Unicode System? This caused two problems: 1. A particular code value corresponds to different letters in the various language standards. 2. The encodings for languages with large character sets have variable length. Some common characters are encoded as single bytes, other require two or more byte. Problem To solve these problems, a new language standard was developed i.e. Unicode System. In unicode, character holds 2 byte, so java also uses 2 byte for characters. lowest value:u0000 highest value:uFFFF Solution
  • 41. FIRST JAVA PROGRAM class Simple{ public static void main(String args[]){ System.out.println("Hello Java"); } } To compile: javac Simple.java To execute: java Simple save this file as Simple.java Output: Hello Java
  • 42. Parameters used in First Java Program Let's see what is the meaning of class, public, static, void, main, String[], System.out.println(). class keyword is used to declare a class in java. public keyword is an access modifier which represents visibility. It means it is visible to all. static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static method is that there is no need to create an object to invoke the static method. The main method is executed by the JVM, so it doesn't require to create an object to invoke the main method. So it saves memory. void is the return type of the method. It means it doesn't return any value. main represents the starting point of the program. String[] args is used for command line argument. System.out.println() is used to print statement. Here, System is a class, out is the object of PrintStream class, println() is the method of PrintStream class
  • 43. Valid java main method signature public static void main(String[] args) public static void main(String []args) public static void main(String args[]) public static void main(String... args) static public void main(String[] args) public static final void main(String[] args) final public static void main(String[] args) final strictfp public static void main(String[] args) Invalid java main method signature public void main(String[] args) static void main(String[] args) public void static main(String[] args) abstract public static void main(String[] args)
  • 44. Can we have multiple classes in a java source file? Yes, like the figure given below illustrates:
  • 45. Java Variables A variable is a container which holds the value while the java program is executed. A variable is assigned with a datatype. Variable is a name of memory location. There are three types of variables in java: local, instance and static. Variable is name of reserved area allocated in memory. In other words, it is a name of memory location. It is a combination of "vary + able" that means its value can be changed.
  • 46. Types of Variables There are three types of variables in java: •local variable •instance variable •static variable
  • 47. 1) Local Variable A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists. A local variable cannot be defined with "static" keyword. 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. It is called instance variable because its value is instance specific and is not shared among instances. 3) Static variable A variable which is declared as static is called static variable. It cannot be local. You can create a single copy of static variable and share among all the instances of the class. Memory allocation for static variable happens only once when the class is loaded in the memory.
  • 48. Example to understand the types of variables in java class A { int data=50;//instance variable static int m=100;//static variable void method() { int n=90;//local variable } }//end of class
  • 49. Java Variable Example: Add Two Numbers class Simple { public static void main(String[] args) { int a=10; int b=10; int c=a+b; System.out.println(c); } } Java Variable Example: Narrowing (Typecasting) class Simple { public static void main(String[] args){ float f=10.5f; //int a=f; //Compile time error int a=(int)f; System.out.println(f); System.out.println(a); }}
  • 50. Get Integer Input From the User There are several ways to get input from the user in Java. You will learn to get input by using Scanner object in this article. need to import Scanner class using: import java.util.Scanner; Then, we will create an object of Scanner class which will be used to get input from the user. Scanner input = new Scanner(System.in); int number = input.nextInt();
  • 51. EXAMPLE- import java.util.Scanner; class Input { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); int number = input.nextInt(); System.out.println("You entered " + number); } } Here, input object of Scanner class is created. Then, the nextInt() method of the Scanner class is used to get integer input from the user. To get long, float, double and String input from the user, you can use nextLong(), nextFloat(), nextDouble() and next() methods respectively.
  • 52. Sum of two numbers using Scanner import java.util.Scanner; public class AddTwoNumbers2 { public static void main(String[] args) { int num1, num2, sum; Scanner sc = new Scanner(System.in); System.out.println("Enter First Number: "); num1 = sc.nextInt(); System.out.println("Enter Second Number: "); num2 = sc.nextInt(); sc.close(); sum = num1 + num2; System.out.println("Sum of these numbers: "+sum); } }
  • 53. Java Program to get input from user(String) using Scanner class to get the input. we are getting input String, integer and a float number. For this we are using following methods: public String nextLine(): For getting input String import java.util.Scanner; class GetInputData { public static void main(String args[]) { int num; float fnum; String str; Scanner in = new Scanner(System.in); //Get input String System.out.println("Enter a string: "); str = in.nextLine(); System.out.println("Input String is: "+str);
  • 54. •PRACTICE SESSION •Java Program to Add two float, Double Numbers input by user •Java Program to Multiply two numbers input by user. •Java program to calculate area of Triangle. •Java program to calculate area of Circle. •Java program to create a calculator . //Get input Integer 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); } }
  • 55. Operators in java Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc. There are many types of operators in java which are given below: •Unary Operator, •Arithmetic Operator, •Shift Operator, •Relational Operator, •Bitwise Operator, •Logical Operator, •Ternary Operator and •Assignment Operator
  • 56. Java Operator Precedence Operator Type Category Precedence Unary postfix expr++ expr-- prefix ++expr --expr +expr -expr ~ ! Arithmetic multiplicative * / % additive + - Shift shift << >> >>> Relational comparison < > <= >= equality == != Bitwise bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | Logical logical AND && logical OR || Ternary ternary ? : Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
  • 57. Java Unary Operator The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.: •incrementing/decrementing a value by one •negating an expression •inverting the value of a boolean Java Unary Operator Example: ++ and – class OperatorExample { public static void main(String args[]) { int x=10; System.out.println(x++);//10 (11) System.out.println(++x);//12 System.out.println(x--);//12 (11) System.out.println(--x);//10 } }
  • 58. Java Unary Operator Example 2: ++ and -- class OperatorExample { public static void main(String args[]){ int a=10; int b=10; System.out.println(a++ + ++a);//10+12=22 System.out.println(b++ + b++);//10+11=21 }} Java Unary Operator Example: ~ and ! class OperatorExample{ public static void main(String args[]){ int a=10; int b=-10; boolean c=true; boolean d=false; System.out.println(~a);//-11 (minus of total positive value which starts from 0) System.out.println(~b);//9 (positive of total minus, positive starts from 0) System.out.println(!c);//false (opposite of boolean value) System.out.println(!d);//true }}
  • 59. Java Arithmetic Operator Example class OperatorExample { public static void main(String args[]){ int a=10; int b=5; System.out.println(a+b);//15 System.out.println(a-b);//5 System.out.println(a*b);//50 System.out.println(a/b);//2 System.out.println(a%b);//0 }} Java Arithmetic Operator Example: Expression class OperatorExample { public static void main(String args[]){ System.out.println(10*10/5+3-1*4/2); }}
  • 60. Program to read two integer and print product of them import java.util.Scanner; public class Demo { public static void main(String[] args) { /* This reads the input provided by user * using keyboard */ Scanner scan = new Scanner(System.in); System.out.print("Enter first number: "); // This method reads the number provided using //keyboard int num1 = scan.nextInt(); System.out.print("Enter second number: "); int num2 = scan.nextInt(); // Closing Scanner after the use scan.close(); // Calculating product of two numbers int product = num1*num2; // Displaying the multiplication result System.out.println("Output: "+product); } }
  • 61. Java Left Shift Operator The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times. Java Left Shift Operator Example class OperatorExample { public static void main(String args[]){ System.out.println(10<<2);//10*2^2=10*4=40 System.out.println(10<<3);//10*2^3=10*8=80 System.out.println(20<<2);//20*2^2=20*4=80 System.out.println(15<<4);//15*2^4=15*16=240 }}
  • 62. Java Right Shift Operator The Java right shift operator >> is used to move left operands value to right by the number of bits specified by the right operand. Java Right Shift Operator Example class OperatorExample { public static void main(String args[]) { System.out.println(10>>2);//10/2^2=10/4=2 System.out.println(20>>2);//20/2^2=20/4=5 System.out.println(20>>3);//20/2^3=20/8=2 }}
  • 63. Java AND Operator Example: Logical && and Bitwise & The logical && operator doesn't check second condition if first condition is false. It checks second condition only if first one is true. The bitwise & operator always checks both conditions whether first condition is true or false. class OperatorExample { public static void main(String args[]){ int a=10; int b=5; int c=20; System.out.println(a<b&&a<c);//false && true = false System.out.println(a<b&a<c);//false & true = false }}
  • 64. Java OR Operator Example: Logical || and Bitwise | The logical || operator doesn't check second condition if first condition is true. It checks second condition only if first one is false. The bitwise | operator always checks both conditions whether first condition is true or false. class OperatorExample { public static void main(String args[]){ int a=10; int b=5; int c=20; System.out.println(a>b||a<c);//true || true = true System.out.println(a>b|a<c);//true | true = true //|| vs | System.out.println(a>b||a++<c);//true || true = true System.out.println(a);//10 because second condition is not checked System.out.println(a>b|a++<c);//true | true = true System.out.println(a);//11 because second condition is checked }}
  • 65. Java Ternary Operator Java Ternary operator is used as one liner replacement for if-then-else statement and used a lot in java programming. it is the only conditional operator which takes three operands. Java Ternary Operator Example class OperatorExample { public static void main(String args[]){ int a=2; int b=5; int min=(a<b)?a:b; System.out.println(min); }}
  • 66. /Program to Find greatest of three numbers using Conditional Operator import java.util.Scanner; //program uses Scanner class public class ConditionalOperator { public static void main(String[] args) { int a,b,c,result; //create Scanner object to obtain input from keyboard Scanner input=new Scanner(System.in); System.out.print("Enter the Three Number : "); //prompt for input a=input.nextInt(); //Read First number b=input.nextInt(); //Read Second number c=input.nextInt(); //Read third number result = (a>b)? ((a>c)?a:c) : ((b>c)?b:c); System.out.println( result + " is Greatest"); } }
  • 67. Java Assignment Operator Java assignment operator is one of the most common operator. It is used to assign the value on its right to the operand on its left. Java Assignment Operator Example class OperatorExample { public static void main(String args[]){ int a=10; int b=20; a+=4;//a=a+4 (a=10+4) b-=4;//b=b-4 (b=20-4) System.out.println(a); System.out.println(b); }}
  • 68. Java Assignment Operator Example: Adding short class OperatorExample { public static void main(String args[]){ short a=10; short b=10; //a+=b;//a=a+b internally so fine a=a+b;//Compile time error because 10+10=20 now int System.out.println(a); }} Output: Compile time error
  • 69. Control Statements Java If-else Statement The Java if statement is used to test the condition. It checks boolean condition: true or false. There are various types of if statement in java. if statement if-else statement if-else-if ladder nested if statement Java if Statement The Java if statement tests the condition. It executes the if block if condition is true. Syntax: if(condition) { //code to be executed }
  • 70. //Java Program to demonstate the use of if statement. public class IfExample { public static void main(String[] args) { //defining an 'age' variable int age=20; //checking the age if(age>18) { System.out.print("Age is greater than 18"); } } }
  • 71. Java if-else Statement The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed. Syntax: if(condition) { //code if condition is true } Else { //code if condition is false }
  • 72. Java Program to demonstrate If statement public class Sample{ public static void main(String args[]) { int a=20, b=30; if(b>a) System.out.println("b is greater"); } }
  • 73. Java Program to demonstrate If –else statement public class Sample { public static void main(String args[]) { int a = 80, b = 30; if (b > a) { System.out.println("b is greater"); } else { System.out.println("a is greater"); } } }
  • 74. Java program is used to toss a coin using Java random class. • Java Math.random() returns a random value between 0.0 and 1.0 each time. • If value is below 0.5 then it's Heads or otherwise Tails. Import java.lang.Math; public class JavaFlip { public static void main(String[] args) { if (Math.random() < 0.5) { System.out.println("Heads"); }else{ System.out.println("Tails"); } } }
  • 75. The basic format of else if statement is: if(test_expression) { //execute your code } else if(test_expression n) { //execute your code } else { //execute your code }
  • 76. public class Sample { public static void main(String args[]) { int a = 30, b = 30; if (b > a) { System.out.println("b is greater"); } else if(a > b){ System.out.println("a is greater"); } else { System.out.println("Both are equal"); } } }
  • 77. Java program is used to demonstrates a comparison of two strings. • Java equals() method is used to compare strings. • Java equalsIgnoreCase() method can ignore the case. • We cannot use == operator to compare two strings. public class EqualCheck { public static void main(String args[]){ String a = "AVATAR"; String b = "avatar"; if(a.equals(b)){ System.out.println("Both strings are equal."); } else { System.out.println("Both strings are not equal."); } if(a.equalsIgnoreCase(b)){ System.out.println("Both strings are equal."); } else { System.out.println("Both strings are not equal."); } } }
  • 78. String a = "AVATAR"; String b = "avatar"; First String type variable a is storing the string value AVATAR, and the second variable b is storing the string value avatar. It is to be noted that both variables a and b will generate different ASCII (American Standard Code for Information Interchange) values, and the string comparison is checked based on the ASCII values among two or more strings. a.equals(b) is a pre-defined method of Java String Class which checks whether two given and initialized strings are equal or not. If found equal, the statement System.out.println ("Both strings are equal."); will get printed else this statement System.out.println ("Both strings are not equal."); gets printed.
  • 79. Java switch statement is used when you have multiple possibilities for the if statement. Java switch statement The basic format of the switch statement is: switch(variable) { case 1: //execute your code break; case n: //execute your code break; default: //execute your code break; }
  • 80. public class SwitchDemo { public static void main(String[] args) { int month = 8; String monthString; switch (month) { case 1: monthString = "January"; break; case 2: monthString = "February"; break; case 3: monthString = "March"; break; case 4: monthString = "April"; break; case 5: monthString = "May"; break; case 6: monthString = "June"; break;
  • 81. case 7: monthString = "July"; break; case 8: monthString = "August"; break; case 9: monthString = "September"; break; case 10: monthString = "October"; break; case 11: monthString = "November"; break; case 12: monthString = "December"; break; default: monthString = "Invalid month"; break; } System.out.println(monthString); } }
  • 82. PRACTICE SESSION •Java Program to Check Even or Odd Number. •Java program to find factorial of a given number using recursion. •Java program to check prime number. •Java program to find the greater number in three no’s input by user. •Java program to find the smaller number in three no’s input by user. •Java Program to demonstrate the use of If else-if ladder. It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+. •Java Program to demonstrate the use of Nested If Statement. Input User age and weight if age is 18 and weight is greater than 50 than only he can donate blood. •Program to check whether the given number is positive or negative •Read two integer or floating point numbers and display the multiplication
  • 83. Java while and do...while Loop Loop is used in programming to repeat a specific block of code. How while loop works? The test expression inside parenthesis is a boolean expression. If the test expression is evaluated to true, statements inside the while loop are executed. then, the test expression is evaluated again. This process goes on until the test expression is evaluated to false. If the test expression is evaluated to false, while loop is terminated.
  • 84. Example : Java while Loop // Program to find the sum of natural numbers from 1 to 100. class AssignmentOperator { public static void main(String[] args) { int sum = 0, i = 100; while (i != 0) { sum += i; // sum = sum + i; --i; } System.out.println("Sum = " + sum); } }
  • 85. import java.util.Scanner; class Convert{ public static void main(String[] args) { int n, count = 0, a; String x = ""; Scanner s = new Scanner(System.in); System.out.print("Enter any decimal number:"); n = s.nextInt(); while(n > 0) { a = n % 2; // if(a == 1) { // count++; //} x = x + "" + a; n = n / 2; } System.out.println("Binary number:"+x); // System.out.println("No. of 1s:"+count); } }
  • 86. Java while loop break continue program import java.util.Scanner; class BreakContinueWhileLoop { public static void main(String[] args) { int n; Scanner input = new Scanner(System.in); while (true) { System.out.println("Input an integer"); n = input.nextInt(); if (n != 0) { System.out.println("You entered " + n); continue; } else { break; } } } }
  • 87. Finding factorial of a number entered by user import java.util.Scanner; public class JavaExample { public static void main(String[] args) { //We will find the factorial of this number int number; System.out.println("Enter the number: "); Scanner scanner = new Scanner(System.in); number = scanner.nextInt(); scanner.close(); long fact = 1; int i = 1; while(i<=number) { fact = fact * i; i++; } System.out.println("Factorial of "+number+" is: "+fact); } }
  • 88. class UserInputSum { public static void main(String[] args) { Double number, sum = 0.0; Scanner input = new Scanner(System.in); while (true) { System.out.print("Enter a number: "); number = input.nextDouble(); if (number < 0.0) { break; } sum += number; } System.out.println("Sum = " + sum); } } calculates the sum of numbers entered by the user until user enters a negative number.
  • 89. Java do while loop Java do while loop is used to execute a block of statements continuously until the given condition is true. do while loop in java is similar to while loop except that the condition is check after the statements are executed, so do while loop guarantees the loop execution at least once.
  • 90. EXAMPLE- class JavaDoWhileLoop { public static void main(String[] args) { int i = 5; do { System.out.println(i); i++; } while (i <= 10); } } EXAMPLE- class DoWhileLoopExample { public static void main(String args[]){ int i=10; do{ System.out.println(i); i--; }while(i>1); } }
  • 91. Calculates the sum of numbers entered by the user until user enters 0. import java.util.Scanner; class Sum { public static void main(String[] args) { Double number, sum = 0.0; Scanner input = new Scanner(System.in); do { System.out.print("Enter a number: "); number = input.nextDouble(); sum += number; } while (number != 0.0); System.out.println("Sum = " + sum); } }
  • 92. public class DoWhileExample2 { public static void main(String[] args) { do{ System.out.println("infinitive do while loop"); }while(true); } } Java Infinitive do-while Loop
  • 93. Java for Loop The syntax of for Loop in Java is: for (initialization; testExpression; update) { // codes inside for loop's body }
  • 94. Example 1: for Loop // Program to print a sentence 10 times class Loop { public static void main(String[] args) { for (int i = 1; i <= 10; ++i) { System.out.println("Line " + i); } } }
  • 95. infinite for Loop If the test expression is never false, for loop will run forever. This is called infinite for loop. Let's take an example: // Infinite for Loop class Infinite { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 10; --i) { System.out.println("Hello"); } } } Here's an another example of infinite for loop. for ( ; ; ) { }
  • 96. Program to print fibonacci series using for loop public class JavaExample { public static void main(String[] args) { int count = 7, num1 = 0, num2 = 1; System.out.print("Fibonacci Series of "+count+" numbers:"); for (int i = 1; i <= count; ++i) { System.out.print(num1+" "); /* On each iteration, we are assigning second number * to the first number and assigning the sum of last two * numbers to the second number */ int sum = num1 + num2; num1 = num2; num2 = sum; } } }
  • 97. public class Pattern { public static void main(String[] args) { int rows = 5, k = 0; for(int i = 1; i <= rows; ++i, k = 0) { for(int space = 1; space <= rows - i; ++space) { System.out.print(" "); } while(k != 2 * i - 1) { System.out.print("* "); ++k; } System.out.println(); } } }
  • 98. Java for-each Loop (Enhanced for Loop) In Java, there is another form of for loop (in addition to standard for loop) to work with arrays and collection, the enhanced for loop. • It starts with the keyword for like a normal for-loop. • Instead of declaring and initializing a loop counter variable, declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name. • In the loop body, can use the loop variable created rather than using an indexed array element. • It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
  • 99. 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; } The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.
  • 100. Example- class ForEachExample1 { public static void main(String args[]) { int arr[]={12,13,14,44}; for(int i:arr){ System.out.println(i); } } }
  • 101. example to iterate through elements of an array using standard for loop: class ForLoop { public static void main(String[] args) { char[] vowels = {'a', 'e', 'i', 'o', 'u'}; for (int i = 0; i < vowels.length; ++ i) { System.out.println(vowels[i]); } } }
  • 102. using for-each loop as follows: class AssignmentOperator { public static void main(String[] args) { char[] vowels = {'a', 'e', 'i', 'o', 'u'}; // foreach loop for (char item: vowels) { System.out.println(item); } } } Note:-If we are working with arrays and collections, can use alternative syntax of for loop (enhanced form of for loop) to iterate through items of arrays/collections.
  • 103. Java - Numbers Class Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc. Example int i = 5000; float gp = 13.65; In development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper classes. All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.
  • 104. The object of the wrapper class contains or wraps its respective primitive data type. Converting primitive data types into object is called boxing, and this is taken care by the compiler. Therefore, while using a wrapper class you just need to pass the value of the primitive data type to the constructor of the Wrapper class. And the Wrapper object will be converted back to a primitive data type, and this process is called unboxing. The Number class is part of the java.lang package.
  • 105. Example- public class Test { public static void main(String args[]) { Integer x = 5; // boxes int to an Integer object x = x + 10; // unboxes the Integer to a int System.out.println(x); } } When x is assigned an integer value, the compiler boxes the integer because x is integer object. Later, x is unboxed so that they can be added as an integer.
  • 106. Number Methods Following is the list of the instance methods that all the subclasses of the Number class implements − Sr.No. Method & Description 1 xxxValue()Converts the value of this Number object to the xxx data type and returns it. 2 compareTo()Compares this Number object to the argument. 3 equals()Determines whether this number object is equal to the argument. 4 valueOf()Returns an Integer object holding the value of the specified primitive. 5 toString()Returns a String object representing the value of a specified int or Integer. 6 parseInt()This method is used to get the primitive data type of a certain String. 7 abs()Returns the absolute value of the argument.
  • 107. 8 round()Returns the closest long or int, as indicated by the method's return type to the argument. 9 min()Returns the smaller of the two arguments. 10 max()Returns the larger of the two arguments. 11 pow()Returns the value of the first argument raised to the power of the second argument 12 sqrt()Returns the square root of the argument. 13 random()Returns a random number.
  • 108. Java - xxxValue() Method The method converts the value of the Number Object that invokes the method to the primitive data type that is returned from the method. • int intValue() • long longValue() • float floatValue() • double doubleValue() Return Value This method returns the primitive data type that is given in the signature.
  • 109. Example public class value{ public static void main(String args[]) { Integer x = 5; // Returns byte primitive data type System.out.println( x.byteValue() ); // Returns double primitive data type System.out.println(x.doubleValue()); // Returns long primitive data type System.out.println( x.longValue() ); } }
  • 110. Java - compareTo() Method The method compares the Number object that invoked the method to the argument. It is possible to compare Byte, Long, Integer, etc. However, two different types cannot be compared, both the argument and the Number object invoking the method should be of the same type. Syntax public int compareTo( NumberSubClass referenceName ) Return Value • If the Integer is equal to the argument then 0 is returned. • If the Integer is less than the argument then -1 is returned. • If the Integer is greater than the argument then 1 is returned.
  • 111. Example public class Test { public static void main(String args[]) { Integer x = 5; System.out.println(x.compareTo(3)); System.out.println(x.compareTo(5)); System.out.println(x.compareTo(8)); } }
  • 112. Java - equals() Method The method determines whether the Number object that invokes the method is equal to the object that is passed as an argument. Syntax public boolean equals(Object o) Return Value The method returns True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation.
  • 113. Example public class Test { public static void main(String args[]) { Integer x = 5; Integer y = 10; Integer z =5; Short a = 5; System.out.println(x.equals(y)); System.out.println(x.equals(z)); System.out.println(x.equals(a)); } }
  • 114. Java - valueOf() Method The valueOf method returns the relevant Number Object holding the value of the argument passed. The argument can be a primitive data type, String, etc. This method is a static method. The method can take two arguments, where one is a String and the other is a radix. Syntax Following are all the variants of this method − static Integer valueOf(int i) static Integer valueOf(String s) static Integer valueOf(String s, int radix)
  • 115. Return Value valueOf(int i) − This returns an Integer object holding the value of the specified primitive. valueOf(String s) − This returns an Integer object holding the value of the specified string representation. valueOf(String s, int radix) − This returns an Integer object holding the integer value of the specified string representation, parsed with the value of radix.
  • 116. EXAMPLE- public class Test { public static void main(String args[]) { Integer x =Integer.valueOf(9); Double c = Double.valueOf(5); Float a = Float.valueOf("80"); Integer b = Integer.valueOf("444",16); System.out.println(x); System.out.println(c); System.out.println(a); System.out.println(b); } }
  • 117. Java - parseInt() Method This method is used to get the primitive data type of a certain String. parseXxx() is a static method and can have one argument or two. Syntax Following are all the variants of this method − static int parseInt(String s) static int parseInt(String s, int radix) Return Value parseInt(String s) − This returns an integer (decimal only). parseInt(int i) − This returns an integer, given a string representation of decimal, binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input.
  • 118. Example public class Test { public static void main(String args[]) { int x =Integer.parseInt("9"); double c = Double.parseDouble("5"); int b = Integer.parseInt("444",16); System.out.println(x); System.out.println(c); System.out.println(b); } }
  • 119. Java - max() Method This method gives the maximum of the two arguments. The argument can be int, float, long, double. Syntax This method has the following variants − • double max(double arg1, double arg2) • float max(float arg1, float arg2) • int max(int arg1, int arg2) • long max(long arg1, long arg2)
  • 120. Example public class Test { public static void main(String args[]) { System.out.println(Math.max(12.123, 12.456)); System.out.println(Math.max(23.12, 23.0)); } } Example- public class Test { public static void main(String args[]) { System.out.println( Math.random() ); System.out.println( Math.random() ); } }
  • 121. Java - Character Class Example char ch = 'a'; // an array of chars char[] charArray ={ 'a', 'b', 'c', 'd', 'e' }; Escape Sequences A character preceded by a backslash () is an escape sequence and has a special meaning to the compiler. The newline character (n) has been used frequently in this tutorial in System.out.println() statements to advance to the next line after the string is printed.
  • 122. Escape Sequence Description t Inserts a tab in the text at this point. b Inserts a backspace in the text at this point. n Inserts a newline in the text at this point. ' Inserts a single quote character in the text at this point. " Inserts a double quote character in the text at this point. Inserts a backslash character in the text at this point.
  • 123. Example:- public class Test { public static void main(String args[]) { System.out.println("She said "Hello!" to me."); } } This will produce the following result − Output She said "Hello!" to me.
  • 124. Sr.No. Method & Description 1 isLetter()Determines whether the specified char value is a letter. 2 isDigit()Determines whether the specified char value is a digit. 3 isWhitespace()Determines whether the specified char value is white space. 4 isUpperCase()Determines whether the specified char value is uppercase. 5 isLowerCase()Determines whether the specified char value is lowercase. 6 toUpperCase()Returns the uppercase form of the specified char value. 7 toLowerCase()Returns the lowercase form of the specified char value. 8 toString()Returns a String object representing the specified character value that is, a one-character string. Character Methods Following is the list of the important instance methods that all the subclasses of the Character class implement −
  • 125. Java - isLetter() Method The method determines whether the specified char value is a letter. Syntax boolean isLetter(char ch) Example public class Test { public static void main(String args[]) { System.out.println(Character.isLetter('c')); System.out.println(Character.isLetter('5')); } }
  • 126. Java - isUpperCase() Method This method determines whether the specified char value is uppercase. Syntax Boolean isUpperCase(char ch) Example public class Test { public static void main(String args[]) { System.out.println(Character.isUpperCase('c')); System.out.println(Character.isUpperCase('C')); System.out.println(Character.isUpperCase('n')); System.out.println(Character.isUpperCase('t')); } }
  • 127. Java - toLowerCase() Method The method returns the lowercase form of the specified char value. Syntax char toLowerCase(char ch) Example public class Test { public static void main(String args[]) { System.out.println(Character.toLowerCase('c')); System.out.println(Character.toLowerCase('C')); } }
  • 128. Java - toString() Method This method returns a String object representing the specified character value, that is, a one-character string. Syntax String toString(char ch) Example public class Test { public static void main(String args[]) { System.out.println(Character.toString('c')); System.out.println(Character.toString('C')); } }
  • 129. public class Example { public static void main(String args[]) { //creating a string by java string literal String str = "Beginnersbook"; char arrch[]={'h','e','l','l','o'}; //converting char array arrch[] to string str2 String str2 = new String(arrch); //creating another java string str3 by using new keyword String str3 = new String("Java String Example"); //Displaying all the three strings System.out.println(str); System.out.println(str2); System.out.println(str3); } }
  • 130. Program to print pyramid using numbers 1 121 12321 1234321 123454321 public class Pattern { public static void main(String[] args) { // Create a new Scanner object Scanner scanner = new Scanner(System.in); // Get the number of rows from the user System.out.println("Enter the number of rows to print the pattern "); int rows = scanner.nextInt(); System.out.println("** Printing the pattern... **");
  • 131. for (int i = 1; i <= rows; i++) { for (int j = rows; j > i; j--) { System.out.print(" "); } for (int k = 1; k <= i; k++) { System.out.print(k); } for (int l = i - 1; l >= 1; l--) { System.out.print(l); } System.out.println(); } } }
  • 132. import java.util.Scanner; public class Pattern2 { public static void main(String[] args) { // Create a new Scanner object Scanner scanner = new Scanner(System.in); // Get the number of rows from the user System.out.println("Enter the number of rows to print the pattern "); int rows = scanner.nextInt(); System.out.println("** Printing the pattern... **");
  • 133. for (int i = rows; i >= 1; i--) { for (int j = 1; j < i; j++) { System.out.print(" "); } for (int k = i; k <= rows; k++) { System.out.print(k + " "); } System.out.println(); } } } 5 4 5 3 4 5 2 3 4 5 1 2 3 4 5
  • 134. Java - Strings Class A Java String contains an immutable sequence of Unicode characters. Unlike C/C+ +, where string is simply an array of char, A Java String is an object of the class java.lang. Java String is, however, special. Unlike an ordinary class: String is associated with string literal in the form of double-quoted texts such as "Hello, world!". We can assign a string literal directly into a String variable, instead of calling the constructor to create a String instance. The '+' operator is overloaded to concatenate two String operands. '+' does not work on any other objects such as Point and Circle. String is immutable. That is, its content cannot be modified once it is created. For example, the method toUpperCase() constructs and returns a new String instead of modifying the its existing content.
  • 135. Creating Strings The most direct way to create a string is to write − String greeting = "Hello world!"; Whenever it encounters a string literal in code, the compiler creates a String object with its value in this case, "Hello world!'. As with any other object, we can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow us to provide the initial value of the string using different sources, such as an array of characters.
  • 136. Example public class StringDemo { public static void main(String args[]) { char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' }; String helloString = new String(helloArray); System.out.println( helloString ); } }
  • 137. String Methods 1.int length(): Returns the number of characters in the String. "GeeksforGeeks".length(); // returns 13 2.Char charAt(int i): Returns the character at index. "GeeksforGeeks".charAt(3); // returns ‘k’ 3.String substring (int i): Return the substring from the ith index character to end. "GeeksforGeeks".substring(3); // returns “ksforGeeks” 4.String substring (int i, int j): Returns the substring from i to j-1 index. "GeeksforGeeks".substring(2, 5); // returns “eks” 5.String concat( String str): Concatenates specified string to the end of this string. String s1 = ”Geeks”; String s2 = ”forGeeks”; String output = s1.concat(s2); // returns “GeeksforGeeks”
  • 138. 6. int indexOf (String s): Returns the index within the string of the first occurrence of the specified string. String s = ”Learn Share Learn”; int output = s.indexOf(“Share”); // returns 6 7.int indexOf (String s, int i): Returns the index within the string of the first occurrence of the specified string, starting at the specified index. String s = ”Learn Share Learn”; int output = s.indexOf(‘a’,3); // returns 8 8.Int lastindexOf( int ch): Returns the index within the string of the last occurrence of the specified string. String s = ”Learn Share Learn”; int output = s.lastindexOf(‘a’); // returns 14 9.boolean equals( Object otherObj): Compares this string to the specified object. Boolean out = “Geeks”.equals(“Geeks”); // returns true Boolean out = “Geeks”.equals(“geeks”); // returns false
  • 139. 10. int compareTo( String anotherString): Compares two string lexicographically. int out = s1.compareTo(s2); // where s1 ans s2 are // strings to be compared This returns difference s1-s2. If : out < 0 // s1 comes before s2 out = 0 // s1 and s2 are equal. out >0 // s1 comes after s2. 11. String toLowerCase(): Converts all the characters in the String to lower case. String word1 = “HeLLo”; String word3 = word1.toLowerCase(); // returns “hello"
  • 140. 12. String toUpperCase(): Converts all the characters in the String to upper case. String word1 = “HeLLo”; String word2 = word1.toUpperCase(); // returns “HELLO” 13.String trim(): Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle. String word1 = “ Learn Share Learn “; String word2 = word1.trim(); // returns “Learn Share Learn” 14. String replace (char oldChar, char newChar): Returns new string by replacing all occurrences of oldChar with newChar. String s1 = “feeksforfeeks“; String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks”