0% found this document useful (0 votes)
48 views

Java Program Documents

More company required java programmers

Uploaded by

perweeng31
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Java Program Documents

More company required java programmers

Uploaded by

perweeng31
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

Introduction to Java

.
JAVA
• Java programming language was released by James Gosling in the year
of 1995, so he is called as the father of JAVA.
• He invented JAVA at Sun Micro systems INC, USA.
• Later the copyrights are given to Oracle Corporation, now this Free and
Open Source (OpenJDK) software is running in around 3 Billion devices.
• Java is used to build various software applications, such as
• Mobile Applications,
• Web Applications,
• Games,
• stand alone desktop applications and more.
What is Software?
• Collection of Programs meant for performing some operations or
obtaining some objectives.
• In Real time scenario, based on operations we have, software's are
classified into 3 types.
1. System Software
2. Application Software
3. Internet Software
System Software:
• The Stand Alone applications run in the context of single machine and
whose results can be accessed in the same machine but not in the other
machines. All the System Software's comes under Stand Alone
application. In Real time, three projects comes under System Software
development.
• They are:
a) Development of Device Drivers
b) Development of Utility Programs: i.e. Antivirus software.
c) Development of Real time Operating System:
Examples of Operating System are Windows, UNIX, LINUX, Mac, etc.
2. Application Software:
• Application Software comes under the Stand Alone applications but it is
used to develop projects for small scale organizations.
• They can run only in particular organization.
• Examples of Application Software are: Supermarkets, Shopping Malls,
Health Care services etc.
3. Internet Software:
• Internet software is used to develop distributed applications. These applications
runs in the context of Browser/www and whose results can be accessed across the
universe.
Examples of Internet Software are:
1) Development of Websites.
2) Development of ATM applications.
3) Development of credit/debit applications.
4) Development of net banking applications.
5) Development of all e-commerce applications.
• Now, Let's see what is JAVA?
"JAVA is an internet software used for developing distributed applications and used
by other technology programmers for developing their applications.“
Java is case-sensitive
Why Use Java?
• Java works on different platforms (Windows, Mac, Linux, etc.)
• It is one of the most popular programming language in the
world
• It has a large demand in the current job market
• It is easy to learn and simple to use
• It is open-source and free
• It is secure, fast and powerful
• It has a huge community support (tens of millions of
developers)
• Java is an object oriented language which gives a clear
structure to programs and allows code to be reused, lowering
development costs
Java Install
To install Java on Windows:
1.Go to "System Properties" (Can be found on Control Panel > System and Security > System
> Advanced System Settings)
2.Click on the "Environment variables" button under the "Advanced" tab
3.Then, select the "Path" variable in System variables and click on the "Edit" button
4.Click on the "New" button and add the path where Java is installed, followed by \bin. By
default, Java is installed in C:\Program Files\Java\jdk-11.0.1 (If nothing else was specified
when you installed it). In that case, You will have to add a new path with: C:\Program
Files\Java\jdk-11.0.1\bin
Then, click "OK", and save the settings
OR
1. Install jdkc driveprogramsjavabincopy its path*(1)
2. Searchedit the system environment variablesAdvanceenvironment variablesSelect on PATH under
system variableEditNewpaste Java path*(1)ok
3. environment variablesSelect on NewJava_HomePaste the java path without binok

4.At last, open Command Prompt (cmd.exe) and type java -version to see if Java is running
on your machine
Now write a program in notepad and save it with same class
name in Java folder
class Hello{
public static void main(String args[]){
System.out.println(“Hello Welcome to ITI Chaibasa");
}
}
Now, click the java folder address tab & type cmdnow type the below details

• 1. C:\Users\PC1\Desktop\JAVA>javac hello.java enter

• C:\Users\PC1\Desktop\JAVA>java hello enter

• hello Output
Example explained
// this is hello program
class Hello{
public static void main(String args[]){
System.out.println(“Hello Welcome to ITI Chaibasa");
}
}
• We use // for single comments, and /*……….*/ for multi line comment.

• Every line of code that runs in Java must be inside a class followed by a class name.
• public: lt declares that the file access has no restriction.
• static: It is a keyword which instruct compiler, so that main should run before any thing else in the program.
• void: It indicates that main() will not return anything.
• String args[]: It declares a string array.
• The name of the java file must match the class name & with ".java" as a extension name.

• main() is a method/function.

• println: for print text or output.


• When we are working with text, it must be wrapped inside double quotations marks.
Ex.
Keyword
Println method is also used to print numbers.
public class Main {
public static void main(String[] args) {
System.out.println(3);
System.out.println(3*5);
System.out.println(3+7);
}
}
Java Variables
• Variables are containers for storing data values.
• Types of variables:
• string: stores text, such as "Hello". String values are surrounded by double
quotes
• int: stores integers (whole numbers), without decimals, such as 123 or -123
• float: stores floating point numbers, with decimals, such as 19.99 or -19.99
• char: stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
• boolean: stores values with two states: true or false

Syntax:
Type variablename=value;
Ex.
int myNum=20; //single variable declaration
int x=3,y=4,z=4; //multiple variable declaration
Ex.
public class Main {
public static void main(String[] args) {
String name = "John";
System.out.println(name);
}
}
To combine both text and a variable, use the + character:

public class Main {


public static void main(String[] args) {
String name = "John";
System.out.println("Hello " + name);
}
}
The general rules for naming variables are:

•Names can contain letters, digits, underscores, and dollar signs


•Names must begin with a letter
•Names should start with a lowercase letter and it cannot contain
whitespace
•Names can also begin with $ and _ (but we will not use it in this tutorial)
•Names are case sensitive ("myVar" and "myvar" are different variables)
•Reserved words (like Java keywords, such as int or boolean) cannot be
used as names
Java Reserved words
Java Data Types
Java Data Types
Data types are divided into two groups:
1.Primitive data types:
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to
2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7
decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal
digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter or ASCII values
Non-Primitive Data Types
• Non-primitive data types are called reference types because
they refer to objects.
• Examples of non-primitive types
are Strings, Arrays, Classes, etc.
Difference
• Primitive types are predefined (already defined) in Java. Non-
primitive types are created by the programmer
• A primitive type has always a value, while non-primitive types
can be null.
• A primitive type starts with a lowercase letter, while non-
primitive types starts with an uppercase letter.
JAVA OPERATORS
• Arithmetic Operator
• Comparison Operator
• Logical/Relational Operator
• Assignment Operator
• Bitwise operator
.
Comparison/Relational Operator
Logical Operator
.
Bitwise operator
Java Strings
• Strings are used for storing text.
• A String variable contains a collection of characters
surrounded by double quotes.
public class Main {
public static void main(String[] args) {
String greeting = "Hello";
System.out.println(greeting);
}
}
String Method
• length(): to get length of a string.
• toUpperCase(), toLowerCase(), indexof() etc.
public class Main {
public static void main(String[] args) {
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
System.out.println(txt.length());
}
}
Java Math
• Math.max(x,y): can be used to find the highest value of x and y.
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(5, 10));
}
}
• Math.min(x,y)
• Math.sqrt(x)
Java Booleans
public class Main {
public static void main(String[] args) {
int myAge = 25;
int votingAge = 18;
System.out.println(myAge >= votingAge); // returns true
}
}
Java Methods
• A method is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also
known as functions.
• Why use methods?
To reuse code
• A method must be declared within a class. It is defined with
the name of the method, followed by parentheses (). Java
provides some pre-defined methods, such as System.out.println()
• you can also create your own methods to perform certain
actions.
Call a Method
• To call a method in Java, write the method's name followed by
two parentheses () and a semicolon;
• Ex.
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
}
}
Java Method Parameters
• Information can be passed to methods as parameter. Parameters act as
variables inside the method.
• When a parameter is passed to the method, it is called
an argument(In below ex. below fname is parameter and Amar &
Anuj is arguments)
• Ex.
public class Main {
static void myMethod(String fname) {
System.out.println(fname + " Kumar");
}

public static void main(String[] args) {


myMethod(“Amar");
myMethod("Anuj");
}
}
Java Method Overloading(plusMethod() is used)
public class Main {
static int plusMethod(int x, int y) {
return x + y;
}

static double plusMethod(double x, double y) {


return x + y;
}

public static void main(String[] args) {


int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
}
Decision Making in Java
• If
• If…..else
• Nested if….else
if statement
If(expression)
{
Statement if expression is true
}

Ex.
public class Main {
public static void main(String[] args) {
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}
}
}
If….else statement
If(expression)
{
Statement if expression is true
}
else
{
Statement if expression is false
}
Ex.
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
If…else with checkAge() call method
public class Main {
static void checkAge(int age) {

if (age < 18) {


System.out.println("Access denied - You are not old enough!");

} else {
System.out.println("Access granted - You are old enough!");
}

public static void main(String[] args) {


checkAge(20);
}
}
Nested If….else statement
If(expression 1)
{
Statement if expression is true
}
else if(expression 2)
{
Statement if expression is true
}
else if(expression 3)
{
Statement if expression is true
}
else
{
Statement if no expression is true
}
Ex.
public class Main {
public static void main(String[] args) {
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
Short Hand If...Else

public class Main {


public static void main(String[] args) {
int time = 20;
String result;
result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);
}
}
Switch Case
switch(expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
case condition 3: statement(s)
break;
case condition n: statement(s)
break;
default: statement(s)
}
Ex.
public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Null");
}
}
}
Loops in Java
• While loop
• do…..while loop
• For loop
While loop
while(expression) {
Statement if expression is true
}
Ex.
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}
do… while loop
do{
Statement to be executed.
}while(expression);
Ex.
Ex.
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
}
}
for loop
For(initialization;test condition;iterationstatement)
{
Statement to be executed if test condition is true.
}
Ex.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
.
Loop control
1)break
2)continue
1. break Ex.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
}
}
2. continue
Ex.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
}
}
ARRAY
An array is a collection of multiple values in a single
variable.
To declare an array, define the variable type with square
brackets: String[] cars;
Ex.
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
}
}
Accessing Array Elements
• You access an array element by referring to the index
number:
• const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
• Note: Array indexes start with 0. [0] is the first element. [1] is the second
element.
i.e.car[0]=saab
Change an Array Element
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
}
}
Array Length

public class Main {


public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
}
}
Loop Through an Array
(Using for loop and car.length)

public class Main {


public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
}
}
Multidimensional Arrays
• A multidimensional array is an array of arrays.
• Multidimensional arrays are useful when you want to store
data as a tabular form, like a table with rows and columns.
• int[][] myNum={{1,2,3,4}, {5,6,7}};
• Here,
• myNum[0]: 1st array i.e. {1,2,3,4} &
• myNum[1]: 2nd array i.e. {5,6,7}
• Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
Access Elements
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]);
}
}
Loop Through a Multi-Dimensional Array
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
}
}
}
}
Java OOP
• OOP stands for Object-Oriented Programming.
• Procedural programming is about writing procedures or
methods that perform operations on the data,
• while object-oriented programming is about creating objects
that contain both data and methods.
• Object-oriented programming has several advantages over
procedural programming:
• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP helps to keep the Java code DRY "Don't Repeat Yourself",
and makes the code easier to maintain, modify and debug
Java - What are Classes and Objects?
• A class is a template for objects, and an object is an instance
of a class.
Ex.
Class objects
Fruit Apple
Banana
Mango
• Everything in Java is associated with classes and objects,
along with its attributes and methods. For example: in real
life, a car is an object. The car has attributes, such as weight
and color, and methods, such as drive and brake.
Ex.
public class Main {
int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x); //here x is an attribute
}
}
Modify Attributes
public class Main {
int x = 10;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 25; // x is now 25
System.out.println(myObj.x);
}
}
Use of final(value cannot change) keyword

public class Main {


final int x = 10;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 25; // will generate an error
System.out.println(myObj.x);
}
}
• Static vs. Public
Static method, which means that it can be accessed without creating an
object of the class, unlike public which can only be accessed by objects:
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method

Main myObj = new Main(); // Create an object of MyClass


myObj.myPublicMethod(); // Call the public method
}
}
Java Constructors
• A constructor in Java is a special method that is used to initialize objects.
• The constructor is called when an object of a class is created.
Ex.
// Create a Main class
public class Main {
int x;
// Create a class constructor for the Main class
public Main() {
x = 5;
}
public static void main(String[] args) {
Main myObj = new Main(); //Creating object of the class i.e. constructor with same class name.
System.out.println(myObj.x);
}
}
Java Modifiers
It is used to set the access level for classes, attributes, methods
and constructors.
We divide modifiers into two groups:
• Access Modifiers - controls the access level i.e. public used
in class. For attributes, methods and constructors, you
can use the one of the following: public(the code is accessible
for all classes),private(The code is only accessible within the
declared class), etc.
• Non-Access Modifiers - do not control access level, but
provides other functionality. For classes, you can use final.
For attributes and methods, you can use final, static etc.
Java Encapsulation
• Encapsulation, is to make sure that "sensitive" data is
hidden from users. To achieve this, you must:
• declare class variables/attributes as private.
• provide public get and set methods to access and update the
value of a private variable.
• private variables can only be accessed within the same class
• However, it is possible to access them if we provide
public get(returns the variable value) method and set(sets
the value) methods.
Ex.
Public class person{
Private String name;
Public String getName(){
Return name;
}
Public void setName(String newname){
This.name=newname;
}
}
Java Packages & API
• A package in Java is a folder in a file directory. We use packages
to avoid name conflicts, and to write a better maintainable code.
Packages are divided into two categories:
• Built-in Packages (packages from the Java API)
• User-defined Packages (create your own packages)

• Built-in Packages:The Java API is a library of prewritten classes,


that are free to use, included in the Java Development
Environment.
• you can either import a single class (along with its methods and
attributes), or a whole package that contain all the classes.
• To use a class or a package from the library, you need to use the
import keyword.
Import a Class
import java.util.Scanner; // import the Scanner class
class Main {
public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);


String userName;
// Enter username and press Enter

System.out.println("Enter username");
userName = myObj.nextLine();
System.out.println("Username is: " + userName);

}
Output:
Enter username:
ex. i.e. let xyz
Username is: xyz
Explanation:

Scanner class is used to get user input.

Scanner is a class of java.util package.


To use of Scanner class we create an object of the class and use any
of the available methods found in the scanner class.In above
ex. We use nextLine() method which is used to read a complete
line.
Import a Package
• To import a whole package, end the sentence with an asterisk
sign(*).
• The following example will import ALL the classes in the
java.util package.
Import java.util.*;
Java Inheritance (Subclass and Superclass)
• In Java, it is possible to inherit attributes and methods from
one class to another.
• It is useful for code reusability: reuse attributes and methods
of an existing class when you create a new class.
• We group the "inheritance concept" into two categories:
• subclass (child) - the class that inherits from another class
• superclass (parent) - the class being inherited from
• To inherit from a class, use the extends keyword.
• In the example below, the car(subclass) inherits the attributes
and methods from the vehicle(superclass) class.
Ex.
class Vehicle {
protected String brand = "Ford"; //vehicle attribute
public void honk() { //vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; //car attribute
public static void main(String[] args) {
Car myCar = new Car(); //create a mycar object

myCar.honk(); //call the honk method from my car object


System.out.println(myFastCar.brand + " " + myFastCar.modelName);
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
}
}
Java Polymorphism
• Polymorphism means "many forms", and it occurs when we
have many classes that are related to each other by
inheritance.
• It is useful for code reusability: reuse attributes and methods
of an existing class when you create a new class.
• Inheritance lets us inherit attributes and methods from
another class while Polymorphism uses those methods to
perform different tasks. This allows us to perform a single
action in different ways.
Ex.
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
}

Cont…..
Cont..

class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
The animal makes a sound
The dog says: bow wow
Java Abstraction

• Data abstraction is the process of hiding certain details


and showing only essential information to the user.
• keyword is a non-access modifier, used for classes and
methods:
• Abstract class: is a restricted class that cannot be used to
create objects (to access it, it must be inherited from
another class).

Abstract method: can only be used in an abstract class,
and it does not have a body. The body is provided by the
subclass (inherited from).
Ex.
abstract class Animal {

public abstract void animalSound();

public void sleep() {

System.out.println("Zzz");

From the example above, it is not possible to create an object of


the Animal class:
Animal myObj = new Animal(); // will generate an error
Java User Input (Scanner)
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Display Current Date
import java.time.LocalDate; // import the LocalDate class
public class Main {
public static void main(String[] args) {
LocalDate myObj = LocalDate.now(); // Create a date object
System.out.println(myObj); // Display the current date
}
}
Formatting Date and Time
import java.time.LocalDateTime; // Import the LocalDateTime class
import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class

public class Main {


public static void main(String[] args) {
LocalDateTime myDateObj = LocalDateTime.now();
System.out.println("Before formatting: " + myDateObj);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy
HH:mm:ss");

String formattedDate = myDateObj.format(myFormatObj);


System.out.println("After formatting: " + formattedDate);
}
}
SOME EXAMPLES OF JAVA
PROGRAM
.
Add Two Numbers
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 6;
int sum = x + y;
System.out.println(sum); // Print the sum of x + y
}
}
Add Two Numbers with User Input
import java.util.Scanner; // Import the Scanner class

public class MyClass {

public static void main(String[] args) {

int x, y, sum;

Scanner myObj = new Scanner(System.in); // Create a Scanner object

System.out.println("Type a number:");

x = myObj.nextInt(); // Read user input

System.out.println("Type another number:");

y = myObj.nextInt(); // Read user input

sum = x + y;

System.out.println("Sum is: " + sum); // Output user input

}
OUTPUT:

Type a number:
10

Type another number:


10

Sum is: 20
Reverse a String
public class Main {
public static void main(String[] args) {
String originalStr = "Hello";
String reversedStr = "";
System.out.println("Original string: " + originalStr);

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


reversedStr = originalStr.charAt(i) + reversedStr;
}

System.out.println("Reversed string: "+ reversedStr);


}
}
Calculate the Sum of an Array
public class Main {
public static void main(String[] args) {
int[] myArray = {1, 5, 10, 25};
int sum = 0;
int i;

// Loop through array elements and get the sum


for (i = 0; i < myArray.length; i++) {
sum += myArray[i];
}
System.out.println("The sum is: " + sum);
}
}
Area of Rectangle
• public class Main {
• public static void main(String[] args) {
• int length = 5;
• int width = 2;
• int area = length * width;
• System.out.println("Area of rectangle: " + area);
• }
•}
Check Whether a Number is Even or Odd
• public class Main {
• public static void main(String[] args) {
• int number = 5;
• if (number % 2 == 0) {
• System.out.println(number + " is even.");
• } else {
• System.out.println(number + " is odd.");
• }
• }
•}
Java String Methods
Method Description Return
Type
charAt() Returns the character at the specified index char
(position)
concat() Appends a string to the end of another string String

endsWith() Checks whether a string ends with the specified boolean


character(s)
equals() Compares two strings. Returns true if the strings Boolean
are equal, and false if not
getChars() Copies characters from a string to an array of void
chars
Java String Methods
Method Description Return Type

indexOf() Returns the position of the first found occurrence of int


specified characters in a string
isEmpty() Checks whether a string is empty or not boolean
length() Returns the length of a specified string int
toCharArray() Converts this string to a new character array char[]
toLowerCase() Converts a string to lower case letters String
toString() Returns the value of a String object String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends of a string String

valueOf() Returns the string representation of the specified value String


Java Math Methods
Method Description Return Type

abs(x) Returns the absolute value of x double|float|int|l


ong
x
exp(x) Returns the value of E double

max(x, y) Returns the number with the highest value double|float|int|l


ong
min(x, y) Returns the number with the lowest value double|float|int|l
ong
pow(x, y) Returns the value of x to the power of y double

cbrt(x) Returns the cube root of x double

ceil(x) Returns the value of x rounded up to its nearest integer double

sqrt(x) Returns the square root of x double

cos(x) Returns the cosine of x (x is in radians) double


Ex.
• public class Main {
• public static void main(String[] args) {
• String txt = "Hello World";
• System.out.println(txt.toUpperCase());
• System.out.println(txt.toLowerCase());
• }
•}
• public class Main {
• public static void main(String[] args) {
• System.out.println(Math.max(5, 10));
• }
•}
Ex.
• public class Main {
• public static void main(String[] args) {
• int x = 10;
• System.out.println(x == 10); // returns true, because the value of x
is equal to 10
• }
•}
Java code to check if the given string is palindrome or not:
• import java.io.*;
• class Programming9
• {
• public static void main (String args[]) throws IOException //IO Exception will thrown if an I/O errors occur
• {
• BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); //accept String from keyboard
• System.out.println ("enter the String:");
• String str = br.readLine (); // read from BufferReader class
• String temp = str; // converting the string into StringBuffer

• StringBuffer sb = new StringBuffer (str);


• sb.reverse (); //reverse String into StringBuffer
• str = sb.toString (); //convert StringBuffer into a String

• if (temp.equalsIgnoreCase (str)) //compare original string available in temp with this reversed String
• System.out.println (temp + " is palindrome");
• else
• System.out.println (temp + " is not palindrome");
Java code to find ASCII value of a character:
• import java.util.Scanner;
• class Programming9
• {
• public static void main(String[] args)
• {
• //scanner is a class for creating an object
• Scanner sc=new Scanner(System.in);

• //input from user


• System.out.print("Enter a Character: ");

• //typecasting from character datatype to integer datatype


• char c=sc.next().charAt(0);
• int i = c;

• //print the ASCII value of the character


• System.out.println("ASCII value of "+c+" is "+i);
• }
• }
Java program prints the square series 0, 1, 4 , 9, 16, 25, etc.
import java.io.*;
public class SquareSeries
{ public static void main(String args[]) throws IOException
{ int n;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no.of elements in series: ");
n = Integer.parseInt(br.readLine());
if(n>0)
{ System.out.println("Series:");
for(int i=0; i<n; i++)
{
System.out.println((int)(Math.pow(i,2)));
}
}
else
System.out.println("You Entered the Wrong no.");
}
}
Java Program To Print Numbers As Pyramid
public class Pyramid
{
public static void main(String[] args)
{
int i=0,j=0,n=6,k=0;
for(i=0; i<n; i++)
{
k=1;
for(j=0; j<(n+i); j++)
{
if(j<n-i-1)
System.out.print(" ");
else
{
System.out.print(""+k);
if(j<(n-1))
k++;
else
k--;
}
}
System.out.println(" ");
}
}
}
Output:

1
121
12321
1234321
123454321
12345654321
Java Program to Calculate BMI (Body Mass Index) Value
• import java.io.*;
• import java.lang.*;
• class BmiCalc {
• public static void main(String args[]) throws IOException {
• float h, w, bmi;
• try {
• BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
• System.out.println("enter the weight(in kgs):");
• w = Float.parseFloat(br.readLine());
• System.out.println("enter the height(in meters):");
• h = Float.parseFloat(br.readLine());
• bmi = w / (h * h);
• System.out.println("your BMI(body mass index) value is" + bmi);
• System.out.println("if your BMI is '<18' you are under weight");
• System.out.println("if your BMI is in between '18 and 24 ' you are normal weight");
• System.out.println("if your BMI is '>25' you are under weight");
• System.out.println("if your BMI is '>30' you are suffering from obesity");
• } catch (NumberFormatException a)
• {
• System.out.println(a);
• }
• }
• }
Java Program to Find Sum of Individual Digits of a Given Number
• import java.io.BufferedReader;
• import java.io.IOException;
• import java.io.InputStreamReader;

• class SumOfDigits {
• public static void main(String args[]) throws IOException {
• BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
• System.out.println("Enter the value to do the sum :");
• int n = Integer.parseInt(br.readLine());
• int sum = 0, k;
• while (n != 0) {
• k = n % 10;
• sum = sum + k;
• n = n / 10;
• }
• System.out.print("\nSum of individual digits : " + sum);
• }
• }
Java Program for Printing Natural Numbers up to Given Number
• import java.io.*;
• import java.lang.*;
• class Num
• {
• public static void main(String args[])throws IOException
• {
• BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
• System.out.println("Enter the number:");
• int n=Integer.parseInt(br.readLine());
• System.out.println("Numbers are");
• for(int i=1; i<=n; i++)
• System.out.println(i);
• }
• }
Java Program For Concatenation of Two Strings
• import java.io.*;
• import java.lang.*;
• class Concatenation
• {
• public static void main(String args[])throws IOException
• {
• BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
• String s1,s2;
• System.out.println("Enter First String: ");
• s1=br.readLine();
• System.out.println("Enter Second String: ");
• s2=br.readLine();
• System.out.println("Concatination of s1 and s2 :"+s1.concat(s2));
• }
• }
Java Program to Find Factorial of a Given Number using For Loop
• import java.io.*;
• import java.lang.*;
• class Factorial
• {
• public static void main(String args[]) throws IOException
• {
• BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
• System.out.println("Enter Number: ");
• int num=Integer.parseInt(br.readLine());
• int fact=1;
• for(int i=1; i<=num; i++)
• {
• fact=fact*i;
• }
• System.out.println("Factorial of a Given Number is : "+fact);
• }
• }
Java Program to Reverse a Number
• import java.io.*;
• import java.lang.*;
• class Reverse
• {
• public static void main(String args[]) throws IOException
• {
• BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
• System.out.println("Enter Number: ");
• int num=Integer.parseInt(br.readLine());

• int remainder, result=0;


• while(num>0)
• {
• remainder = num%10;
• result = result * 10 + remainder;
• num = num/10;
• }
• System.out.println("Reverse number is : "+result);
• }
• }
Java Program for Division of Two Numbers
• import java.io.*;
• import java.lang.*;
• class Div
• {
• public static void main(String args[])throws IOException
• {
• int n1=0,n2;
• BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
• System.out.println("Enter first number: ");
• n1=Integer.parseInt(br.readLine());
• System.out.println("Enter second number: ");
• n2=Integer.parseInt(br.readLine());
• n1/=n2;
• System.out.println("Division of two numbers is: "+n1);
• }
• }
Java Program to Find Given Number Is Even or Odd
• import java.io.*;
• import java.lang.*;
• class EvenOdd
• {
• public static void main(String args[])throws IOException
• {
• int n=0;
• BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
• System.out.println("Enter number: ");
• n=Integer.parseInt(br.readLine());
• n=n%2;
• if(n==0)
• System.out.println("The given number is even ");
• else
• System.out.println("The given number is odd ");
• }
• }

You might also like