Basic Java con_cd
Software set up :
Links and steps to
download and install required softwares to start core java programming.
Note : Please
download java and sts ide as per your operating system and processor type
Step 1 : Link to
download Java 8 :
Step 2 : Link to
download STS IDE:
https://spring.io/tools
or
https://drive.google.com/drive/folders/1xh05Otem1kEfQ61oluE4PPf36jHzyNA_?usp=sharing
Step 3: Add Java
into STS IDE:
We
have to make sure that the Java run time of our STS IDE points to a JDK instead
of a JRE. Here are the steps:
Go
to Window-> Preferences -> java -> Installed JREs -> Click on add
-> standard vm -> next
As
shown in below,
->click
directory -> select jdk-> click finish -> click apply and close, as
shown below.
Types of
Java Software
Java (sun, oracle)
- (Basic ) core java (sdk) (j2se)
To develop standalone applications
-applications which run on only one machine at a time are called standalone
applications
Ex: ms word, notepad, wordpad, paint etc
-j2ee (java 2 enterprize edition) advanced java
-we can develop web applications which runs multiple machines at a time (client
server architecture), spring framework, springboot, hibernate, jpa, web
services.
Ex : gmail, facebook, whatsapp
-j2me (java 2 micro edition)
We can Develop mobile
applications
What is Java?
Java is a object oriented programming language
to write programs,
Program means set of instructions (line).
Ex:
Java :
Mahesh vaibhav
Windows os Linux
os
firstPro.java
firstPro.class firstPro.class
C
firstPro.c
firstPro.obj firstPro.obj
Features of java ?
-open source
-platform independent
-oops
To develop standalone, web applications,
mobile applications, gaming, animation, real time applications.
What is software?
-Set of programs
What is program?
-set of instructions
What is java compiler ?
-Program which coverts source code into byte
code and generates .class file is called compiler.
firstProgram.java ---
firstProgram.class (byte code)
-- firstProgram.obj (output)
What is java interpreter ?
-Program which runs byte code or .class file
and show final output is called java interpreter
What is JIT ?
-Just in time compiler which compile program
very fast.
What is JVM ?
- Stands for Java virtual machine and it Is a
bunch of programs which executes byte code or class file.
What is JDK ?
- Java development kit which supports to write
java programs and develop java applications
What is JRE ?
- Stands for Java Runtime Environment which
runs programs and applications written in java.
What is keyword ?
- Vocabulary set of java
- word having predefined meaning in java
- ex : main, void, char, int, short, byte,
long, float, double, for, while, do, if, else, switch, break, continue, goto,
register etc.
What is variables ?
Name given to memory location to store value.
Rules : It should not start with symbol(except
underscore) or number.
It should not be keyword.
Ex : int empNo = 20;
What is Constant ?
- constants are values which does not change
during program execution.
Ex : final float pi = 3.14;
What is datatype ?
- Is a keyword which defines type of data.
Ex : int , char, float
int ( whole numbers ) : 1,2,3…..n
float ( decimal point numbers ) :
1.5,2.6,3.8…..n
char (characters): a, b, ^
boolean status = false;
int a = 50;
|
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 |
What is package
- package is like
folder which is used to keep similar types of files at one place
-used to avoid accidental deletion
-should be start with small letter
-syntax : package basic;
What is class
- class is a keyword which is used to declare
class and class is an entity which contains variables, methods, blocks,
constructors which can be reused many times using object.
Ex : class Student
What is Object
-Object is an instance of Class, used to
access properties of class. In below stu1 is an object of Student class.
Ex : Student stu1
First java program to print your name
// write a program
to print your name
public class
FirstJavaProgram {
public static void
main(String[] args) {
System.out.println("My
name is Mahesh");
}
}
Structure of Java program
Package declaration
Include library files
Declare class
Open curly brace
public static void main
Open curly brace {
Variable declaration
i/o statements
operational statements
close curly brace of main
close curly brace of class
}
Members of Class
-Variables
-constructors
-instance blocks
-static blocks
-methods
Variables
A name given to memory location to store
value.
-Instance variable
-declared
without static keyword
Ex
: int marks = 50;
-stored
in heap type of memory
-multiple
copy storage
Static variable
-declared
with static keyword
-ex
: static int marks = 50;
-
centralized memory area
-single
copy storage
-Local variable
-variable declared outside class but within
block is called local variable
-Scope of local variable is within block only
where it is declared
ex:
void m1(){
int c=20;
}
Constructors :
Defination:
Constructor is a special method which has same name as class name.
-Constructor
will be invoked automatically whenever you
create the object.
-Constructor
will be used to initialize instance
variables of the class with the different set of values.
-When
you are not writing any constructor inside the class, then jvm automatically
inserts default constructor, otherwise not
inserted.
-Constructor
has not return type, even void also not, if
return type is given then jvm consider it as normal method.
-We
can’t call the constructor explicitly.
-Constructors
can be overloaded.
Example
Program: 1
// 1. Write a
program to understand use of constructor
public class
ConsPro1{
//default constructor
ConsPro1(){
System.out.println("\n\n\n\nThis
is default constructor");
}
public static void
main(String args[]){
ConsPro1 c = new
ConsPro1();
}
}
Block
2 types of blocks
-instance
-static block
-difference between instance and static block
-Static block executed only at first object
creation of class but instance block is executed every time we create object of
same class.
-static block executed before instance block
-static block executes more faster than
instance block
public class
BlockPro {
//instance block
{
System.out.println("This
is instance block...");
}
//static block
static{
System.out.println("This
is static block...");
}
public static void
main(String[] args) {
BlockPro b1 = new
BlockPro();
BlockPro b2 = new
BlockPro();
}
}
Output :
This is static block...
This is instance block...
This is instance block...
Methods:
-Defination: Method
is a routine which is written to perform
some operation.
-Syntax: [Access modifier] [return_type] Method
name(parameters)
-2
Types
1.Instance
methods
2.Static
methods
-Difference between instance and static methods
|
Instance Methods |
Static Methods |
|
1. Method defined without static keyword, is called instance method. |
1. Method defined with static keyword,
is called static method. |
|
2. Must be called
by reference variable, i.e object. |
2. Can be called by
-With class name
-With reference variable which contains null.
- With reference variable which contains object. |
-Ex: public int Sqrt(int n){
Statements;
return r;
}
package
methodDemo;
public class
MPractice {
int a=50,b=60,ans;
private int Addition(){ //method defination
ans=a+b;
//System.out.println(ans);
return ans;
}
public static void
main(String[] args) {
MPractice m=new MPractice();
int
ans=m.Addition(); //method call
System.out.println("ans="+ans);
}
}
Operators in Java
|
• Arithmetic Operator |
|
• Relational Operator |
|
• Logical Operator |
|
• Unary Operator |
|
• Ternary Operator |
|
• Assignment Operator |
Java Arithmetic
Operators
Java arithmetic operators are used to perform addition,
subtraction, multiplication, and division. They act as basic mathematical
operations.
Example
program :
public 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
}
}
Output:
1555020
Relational Operators in Java
Java
has 6 relational operators.
== is the
equality operator. This returns true if both the operands are referring to the
same object, otherwise false.
!= is for
non-equality operator. It returns true if both the operands are referring to
the different objects, otherwise false.
< is
less than operator.
> is
greater than operator.
<= is
less than or equal to operator.
>= is
greater than or equal to operator.
Program to demonstrate use of relational
operators
package com.consyosoft.java;
public class
RelationalOperators {
public static void main(String[]
args) {
int a = 10;
int b = 20;
System.out.println(a ==
b);
System.out.println(a !=
b);
System.out.println(a
> b);
System.out.println(a
< b);
System.out.println(a
>= b);
System.out.println(a
<= b);
}
}
Logical operators
‘Logical AND’ Operator(&&):
'Logical OR' Operator(||)
'Logical NOT' Operator(!)
Logical &&
table
0 && 0 = 0
0 && 1 = 0
1 && 0 = 0
1 && 1 = 1
Logical || table
0 && 0 = 0
0 && 1 = 1
1 && 0 = 1
1 && 1 = 1
Logical !
Table
!0 = 1
!1 = 0
Program to understand logical operators
}
}
Java Unary Operator
The Java unary operators require only one
operand. Unary operators are used to perform various operations i.e.
int a=10;
post increment : a++
pre increment : ++a
post decrement : a--
pre decrement : --a
Program to demonstrate ++ and -- operators
public 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
}}
Output:
10121210
Ternary Operator
Java ternary operator is the only conditional operator
that takes three operands. It’s a one-liner replacement for if-then-else statement
and used a lot in Java programming. We can use the ternary operator in place of
if-else conditions or even switch conditions using nested ternary operators.
// Java program to
find largest among two
// numbers using
ternary operator
import java.io.*;
class Ternary {
public static void main(String[]
args)
{
// variable declaration
int n1 = 5, n2 = 10,
max;
System.out.println("First
num: " + n1);
System.out.println("Second
num: " + n2);
// Largest among n1 and
n2
max = (n1 > n2) ? n1
: n2;
// Print the largest
number
System.out.println("Maximum
is = " + max);
}
}
Assignment operator
=
First java program to print your
name
//
write a program to print your name
public class
FirstJavaProgram {
public static
void main(String[] args) {
System.out.println("My
name is Mahesh");
}
}
Program to Add two numbers
public class AddTwoNumbers {
public static void main(String[] args) {
int num1 = 5, num2 = 15, sum;
sum = num1 + num2;
System.out.println("Sum of these
numbers: "+sum);
}
}
calculate compound interest
Compound interest is calculated using the following formula:
P (1 + R/n) (nt) - P
Here P is principal
amount.
R is the annual interest rate.
t is the time the money is
invested or borrowed for.
n is the number of times that
interest is compounded per unit t, for example if interest is compounded
monthly and t is in years then the value of n would be 12. If interest is
compounded quarterly and t is in years then the value of n would be 4.
Before writing the java
program let’s take an example to calculate the compound interest.
Let’s say an amount of
$2,000 is deposited into a bank account as a fixed deposit at an annual
interest rate of 8%, compounded monthly, the compound interest after 5 years
would be:
P = 2000.
R = 8/100 = 0.08 (decimal).
n = 12.
t = 5.
Let’s put these values in the formula.
Compound Interest = 2000 (1 +
0.08 / 12) (12 * 5) – 2000 = $979.69
So, the compound interest after 5 years is $979.69.
Java program to calculate compound interest
In this java program we are calculating the compound interest, we are
taking the same example that we have
seen above for the calculation.
public class JavaExample {
public void calculate(int p, int t, double r, int n) {
double amount = p * Math.pow(1 + (r / n), n * t);
double cinterest = amount - p;
System.out.println("Compound Interest after " + t + " years: "+cinterest);
System.out.println("Amount after " + t + " years: "+amount);
}
public static void main(String args[]) {
JavaExample obj = new JavaExample();
obj.calculate(2000, 5, .08, 12);
}
}
Output:
Compound Interest after 5 years: 979.6914166032102
Amount after 5 years: 2979.69141660321
Java program to calculate power of number
public class JavaExample {
public static void main(String[] args) {
//Here number is the base and p is the exponent
int number = 2, p = 5;
long result = 1;
//Copying the exponent value to the loop counter
int i = p;
for (;i != 0; --i)
{
result *= number;
}
//Displaying the output
System.out.println(number+"^"+p+" = "+result);
}
}
Java program to swap two variables
public class Consyosoft
{
public static void main(String[]
args)
{
int x = 100, y = 200;
System.out.println("Before
Swap");
System.out.println("x
= " + x);
System.out.println("y
= " + y);
int temp = x;
x = y;
y = temp;
System.out.println("After
swap");
System.out.println("x
= " + x);
System.out.println("y
= " + y);
}
}
Java program to Calculate area of rectangle
public class rectangle{
public static void main(String args[])
{
int width=5;
int height=10;
int area=width*height;
System.out.println("Area of rectangle="+area);
}
}
// Java program to calculate the area and perimeter of the circle.
class CalStuff{
double areaOfCircle(double pi, int r){
// calculating the area
of the circle
area = pi * radius *
radius;
return area;
}
double
circumference(double pi, int r)
{
double
cir = 2*PI*r;
return
cir;
}
}
}
public class ConsyoSoft
{
public static void main(String[] args)
{
int radius;
double pi = 3.142, area,
circum;
radius = 5;
CalStuff c = new
CalStuff();
area = c.areaOfCircle(pi,
radius);
circum = c.circumference(pi, radius);
// printing the area of
the circle
System.out.println("Area
of circle is :" + area);
System.out.println("Circumference of circle is :" + circum);
}
}
package basic;
public class
AsciiPract {
public static void
main(String[] args) {
char c = 'k';
// %d displays the
integer value of a character
// %c displays the
actual character
System.out.println("The
ASCII value of k is " + c);
}
}
Java program to print ascii value of character
// C program to print
// ASCII Value of Character
#include <stdio.h>
int main()
{
char c = 'k';
// %d displays the integer value
of a character
// %c displays the actual
character
printf("The ASCII value of %c
is %d", c, c);
return 0;
}
Java program to print default values of primitive datatype variables
class Test {
int k;
double d;
float f;
boolean istrue;
String p;
public void printValue() {
System.out.println("int
default value = "+ k);
System.out.println("double
default value = "+ d);
System.out.println("float
default value = "+ f);
System.out.println("boolean
default value = "+ istrue);
System.out.println("String
default value = "+ p);
}
}
public
class HelloWorld {
public static void main(String argv[]) {
Test test = new Test();
test.printValue();
}
}
Java program to swap two variables without using the third
variable
// using temporary variable
import java.io.*;
class ConsyoSoft {
public static void
main(String a[])
{
int x =
10;
int y = 5;
x = x + y;
y = x - y;
x = x - y;
System.out.println("After
swaping:"
+
" x = " + x + ", y = " + y);
}
}
//Java program to print Fibonacci series till n
class FibonacciExample1{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}
1.if statement
if is keyword used to write condition.
Syntax :
if(condition){
stmts;
}
//write a program to check a number and print if it is positive
class IfStatement {
public
static void main(String[] args) {
int number
= 10;
// checks
if number is greater than 0
if (number
> 0) {
System.out.println("The number is positive.");
}
System.out.println("Statement outside if block");
}
}
2.if else
if else are
keywords used to write condition
syntax :
if(condition){
stmt 1;
}
else{
stmt 2;
}
Flowchart :
//write a program to check a number and print wheather it is
positive or negative
class Main {
public
static void main(String[] args) {
int number
= -10;
// checks
if number is greater than 0
if (number
> 0) {
System.out.println("The number is positive.");
}
// execute
this block
// if
number is not greater than 0
else {
System.out.println("The number is not positive.");
}
System.out.println("Statement outside if...else block");
}
}
3. else if ladder
To write more than one condition and only one
condition should be executed then we use else if ladder.
Syntax :
if(condition){
}
else if(condition){
}
else if(condition){
}
.
.
else{
}
// write a program to
declare a variable with value and print wheather it is
positive/negative/zero
class Main {
public
static void main(String[] args) {
int number
= 0;
// checks
if number is greater than 0
if (number
> 0) {
System.out.println("The number is positive.");
}
// checks
if number is less than 0
else if
(number < 0) {
System.out.println("The number is negative.");
}
// if both
condition is false
else {
System.out.println("The number is 0.");
}
}
}
4. Switch :
syntax :
switch(condition){
case
1:
stmts;
break;
case 2:
stmts;
break;
case 3:
stmts;
break;
.
.
.
case
n:
stmts;
break;
default:
stmts;
}
/* write a program to take a number from
user, and perform operation as per his choice for arithmetic operations */
package
conditionalStmt;
import
java.util.Scanner;
public class
SwitchPractical {
public static void
main(String[] args) {
int choice, num1=10,
num2=5;
Scanner s = new
Scanner(System.in);
System.out.println("Please
enter your choice");
System.out.println("1.
Addition");
System.out.println("2.
Substraction");
System.out.println("3.
Multiplication");
System.out.println("4.
Division");
System.out.println("Please
enter choice.");
choice = s.nextInt(); //3
switch(choice){
case 1:
System.out.println(num1+num2);
break;
case 2:
System.out.println(num1-num2);
break;
case 3:
System.out.println(num1*num2);
break;
case 4:
System.out.println(num1/num2);
break;
default:
System.out.println("please
enter correct choice");
break;
}
}
}
Looping Statements :
To execute some set of code repeatedly we use loops.
while loop :
While is entry controlled loop used to execute some
set of code repeatedly.
syntax :
while(condition){
}
Program : write a program to print numbers
from 1 to 100.
package loopPract;
public class WhileDemo {
public
static void main(String[] args) {
int
i=1;
while(i<=10)
{
System.out.println(i);
i++; //11
}
}
}
do while loop :
do while loop is exit control loop.
syntax :
do{
}while(condition);
// program to print
numbers from 1 to 10
package
loopStmts;
public class
DoWhilePractical {
public static void
main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
for loop
for loop is used to execute set of statements
repeatedly
syntax :
for(initialization;condition;increment/decrement){
}
//Program 3 : Write a
program to print 1 to 100 using for loop
package
basicPrograms;
public class
ForDemo {
public static void
main(String[] args) {
for(int i=1;i<=10;i++)
{ //1,2,3,4.....9,10,11
System.out.println(i); //1,2,3...9,10
}
}
}
/*
sequence
step 1 : initialization
step 2 : condition (if condition is true then next steps will be
executed)
step 3 : body
step 4 : increment/decrement
step 5 : repeat step 2 to 4 till loop
condition is true
*/
//write a program to print below pattern using
nested loop
/*
*
**
***
****
*****
*/
package loopPract;
public class PatternDemo {
public
static void main(String[] args) {
//for
lines
for(int
i=1;i<=5;i++) { //6
//print
for(int
j=1;j<=i;j++) { //
System.out.print(j);
}
System.out.println();
}
}}
for each loop :
·
It’s
commonly used to iterate over an array or a Collections class (eg, ArrayList)
//for…each loop with array :
package
basicPrograms;
public class
ForEachDemo {
public static void
main(String[] args) {
int eids[]=
{10,20,30,40};
for(int e
: eids) {
System.out.println(e);
}
}
}
//for…each
loop with arraylist :
package
basicPrograms;
import
java.util.ArrayList;
public class
ForEachDemo {
public static void
main(String[] args) {
ArrayList eids= new
ArrayList();
eids.add(20);
eids.add(30);
eids.add(40);
eids.add(50);
for(int e
: eids) {
System.out.println(e);
}
}
}
class PrimePract {
// Function to print all the
// prime numbers till N
static void prime_N(int N)
{
// Declaring the
variables
int x, y, flg;
// Printing display
message
System.out.println(
"All
the Prime numbers within 1 and " + N
+ "
are:");
// Using for loop for
traversing all
// the numbers from 1 to
N
for (x = 1; x <= N;
x++) {
// Omit 0
and 1 as they are
// neither
prime nor composite
if (x == 1
|| x == 0)
continue;
// Using
flag variable to check
// if x is
prime or not
flg = 1;
for (y = 2;
y <= x / 2; ++y) {
if
(x % y == 0) {
flg
= 0;
break;
}
}
// If flag
is 1 then x is prime but
// if flag
is 0 then x is not prime
if (flg ==
1)
System.out.print(x
+ " ");
}
}
// The Driver code
public static void main(String[] args)
{
int N = 45;
prime_N(N);
}
}
//Java program to find factorial of given number
package basic;
class FactoPracto{
// Method to find factorial of the
given number
static int factorial(int
n)
{
int res = 1, i;
for (i = 2; i
<= n; i++)
res *= i;
return res;
}
// Driver method
public static void
main(String[] args)
{
int num = 5;
System.out.println(
"Factorial
of " + num
+ " is
" + factorial(5));
}
}
Program to Check if a number is palindrome or not
package basic;
class PalindromePract
{
/* Iterative function to reverse
digits of num*/
static int
reverseDigits(int num) //
{
int rev_num = 0;
while (num >
0) {
rev_num =
rev_num * 10 + num % 10;
//
num = num /
10; //
}
return rev_num;
}
/* Function to check if n is Palindrome*/
static int
isPalindrome(int n)
{
//
get the reverse of n
int rev_n = reverseDigits(n);
// Check if rev_n and n
are same or not.
if (rev_n == n)
return
1;
else
return
0;
}
/*Driver program to test
reversDigits*/
public static void
main(String []args)
{
int n = 245;
System.out.println("Is"
+ n + "a Palindrome number? -> " +
(isPalindrome(n)
== 1 ? "true" : "false"));
n = 151;
System.out.println("Is"
+ n + "a Palindrome number? -> " +
(isPalindrome(n) == 1 ? "true" : "false"));
}
}
//java Program to Check wheather number is Armstrong or not
package basic;
public class
ArmstrongPract {
public static void
main(String[] args) {
int num =
159,processedNum;
processedNum = checkArmstrong(num);
if(processedNum
== num)
System.out.println("number
is armstrong");
else
System.out.println("number
is not armstrong");
}
private static int
checkArmstrong(int num) {
int digit, sum=0;
while(num>0) {
digit =
num%10; //1
sum = sum +
(digit*digit*digit); //153
num=num/10; //1
}
return sum;
}
}
//java Program to Check wheather number is Armstrong or not
package basic;
public class
ArmstrongPract {
public static void
main(String[] args) {
int num =
159,processedNum;
processedNum = checkArmstrong(num);
if(processedNum
== num)
System.out.println("number
is armstrong");
else
System.out.println("number
is not armstrong");
}
private static int
checkArmstrong(int num) {
int digit, sum=0;
while(num>0) {
digit =
num%10; //1
sum = sum +
(digit*digit*digit); //153
num=num/10; //1
}
return sum;
}
}
Arrays in Java :
An array
is a group of like-typed variables that are referred to by a common name.
The variables in the
array are ordered.
Types : 1 D and 2D
-index order
-index starts with 0
int eid[];
One-Dimensional
Arrays :
//Write a
program to declare and initialize 1 dimentional array
//Write a program to declare and initialize 1 dimentional
array
/*
array[0] = 11
array[1] = 12
array[2]
= 13
array[3]
= 14
*/
package basic;
class OneDArray {
public
static void main( String args[] ) {
int[]
salary = {11000,12000,13000,14000,15000,11000,12000,13000,14000,15000,11000,12000};
int len =
salary.length;
//Printing
the elements of array
for
(int i =0; i<len ;i++)
{
if(i==6)
salary[i]
= salary[i] + 5000;
System.out.println(salary[i]);
}
}
}
Two-Dimensional
Arrays :
//Write a program to declare and initialize 2 dimentional array
class TwoDPract {
public static void main(String[]
args)
{
int[][] arr = new
int[10][20];
arr[0][0] = 1;
System.out.println("arr[0][0]
= " + arr[0][0]);
}
}
// Java program to calculate average of array
elements
class
ArrayForAverage{
// Function that return average of
an array.
static double average(int a[], int
n)
{
// Find sum of array
element
int sum = 0;
for (int i = 0; i <
n; i++)
sum += a[i];
return (double)sum / n;
}
//driver code
public static void main (String[]
args)
{
int arr[] = {10, 2, 3,
4, 5, 6, 7, 8, 9};
int n = arr.length;
System.out.println(average(arr,
n));
}
}
//Java program to reverse an array
public class ReverseArray {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = arr.length-1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}
//java
program to sort an array in ascending order
public class SortAsc {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;
//Displaying elements of original array
System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
//Sort the array in ascending order
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
//Java program to Convert Character Array to String
package basic;
//Main
class
class CharArrayToString{
// Method 1
// To convert a character
// array to a string using the
constructor
public static String
toString(char[] a)
{
// Creating object of
String class
String string = new
String(a);
return string;
}
// Main driver method
public static void
main(String args[])
{
// Character array
char s[] = { 'c',
'o', 'n', 's', 'y', 'o', 's',
'o', 'f', 't', ' ', 'o', 'k' };
// Printing converted
string from character array
System.out.println(toString(s));
}
}
//java program to perform addition of matrix
package basic;
public class
MatrixAddition{
public static void
main(String args[]){
//creating two
matrices
int a[][]={{1,3,4},{2,4,3},{3,4,5}};
int b[][]={{1,3,4},{2,4,3},{1,2,4}};
//creating another
matrix to store the sum of two matrices
int c[][]=new
int[3][3]; //3 rows and 3
columns
//adding and printing
addition of 2 matrices
for(int i=0;i<3;i++){
for(int
j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j]; //use - for subtraction
System.out.print(c[i][j]+"
");
}
System.out.println();//new
line
}
}
}
//java program to sort names of array, alphabetically
package basic;
class
SortNamesAlphabetically {
public static void
main(String[] args)
{
// storing input in
variable
int n = 4;
// create string array
called names
String names[] = { "Rahul",
"Ajay", "Gourav", "Riya" };
String temp;
for (int i
= 0; i < n; i++) {
for (int
j = i + 1; j < n; j++) {
//
to compare one string with other strings
if
(names[i].compareTo(names[j]) > 0) {
//
swapping
temp
= names[i];
names[i]
= names[j];
names[j]
= temp;
}
}
}
// print output array
System.out.println("The
names in alphabetical order are: ");
for (int i
= 0; i < n; i++) {
System.out.println(names[i]);
}
}
}
//java program to print first largest and second largest number
among elements of array
package basic;
public class
LargestInArray{
public static int
getSecondLargest(int[] a, int total){
int temp;
for (int i
= 0; i < total; i++) //3
{
for (int
j = i + 1; j < total; j++) //4
{
if
(a[i] > a[j]) //6>
{
temp
= a[i]; //5
a[i]
= a[j]; //3
a[j]
= temp; //5
}
}
}
for (int i
= 0; i < total; i++) //3
{
System.out.println("array
after swap : "+a[i]);
}
System.out.println("first
largest"+ a[total-1]); //a[5]
return a[total-2]; //a[4]
}
public static void
main(String args[]){
int a[]={1,2,5,6,3,2};
System.out.println("Second
Largest: "+getSecondLargest(a,6));
}
}
//Java Program to merge two arrays, store them in another array and
print
package basic;
import
java.util.Arrays;
public class
MergeTwoArrays {
public static void
main(String[] args)
{
// first array
int[] a = { 10,
20, 30, 40 };
// second array
int[] b = { 50,
60, 70, 80 };
// determines length of
firstArray
int a1 = a.length;
// determines length of
secondArray
int b1 = b.length;
// resultant array size
int c1 = a1 + b1;
// create the resultant
array
int[] c = new
int[c1];
// using the pre-defined
function arraycopy
System.arraycopy(a,
0, c, 0, a1);
System.arraycopy(b,
0, c, a1, b1);
// prints the resultant
array
System.out.println(Arrays.toString(c));
}
}
//java program to Find square root of a number without sqrt
method
package basic;
public class
Sqrt {
public static void main(String args[]){
int n = 16; // 12
double i, precision = 0.00001;
for(i = 1; i*i<=n; ++i) //
;
for(--i; i*i < n; i += precision)
;
System.out.println("Square root of given number
"+i); //144
}
}
//program to implement string class methods
/*
String
is an inbuilt class
it
contains methods to perform operations on string
*/
package
basic;
public
class String_Ex {
public static void main(String[]
args) {
String s1 =
"Mahesh"; //
String s2 = new
String("Hundekari");
char
s3[]={'a','b','c','d'};
String s4=new
String(s3);
String s5=new
String("Mahesh Hundekari");
String s6=new
String("Hundekari");
String s7=new
String("Mahesh");
String
s10="mahesh";
String s11=" mahesh ";
char s12[]=new char[15];
String s13="This,
is my name, Mahesh";
String s14[];
s14=s13.split(",");
/*s14[0] = This
s14[1] = is my name
s14[2] = Mahesh
*/
System.out.println("Split
delimeter:");
for(int
i=0;i<s14.length;i++)
System.out.println(s14[i]);
System.out.println("Content
of String s1:"+s1);
System.out.println("Content
of String s2:"+s2);
System.out.println("Content
of String s4:"+s4);
System.out.println("\nConcat
of String s5 and s6:"+s5.concat(s6));
System.out.println("Length
of String s5:"+s5.length());
System.out.println("CharAt
3rd position:"+s5.charAt(2));
if(s5.equals(s6))
System.out.println("case1:
s5 and s6 are Same");
else
System.out.println("case1:
s5 and s6 are not Same");
if(s5.equals(s7))
System.out.println("case
2: s5 and s7 are Same");
else
System.out.println("case
2: s5 and s7 are not Same");
System.out.println("Equals
Ignore case:"+s5.equalsIgnoreCase(s10));
System.out.println("Starts
With:"+s5.startsWith("M"));
System.out.println("Ends
With:"+s5.endsWith("esh"));
System.out.println("Index
Of:"+s5.indexOf("s"));
System.out.println("contents
of s5 = "+s5); // Mahesh ---- mahesh
System.out.println("Last
Index Of:"+s5.lastIndexOf("h"));
System.out.println("Replace
with:"+s5.replace("h","x"));
System.out.println("SubString:"+s5.substring(2));
System.out.println("SubString
from:"+s5.substring(2,6));
System.out.println("ToLowerCase:"+s5.toLowerCase());
System.out.println("ToUpperCase:"+s5.toUpperCase());
System.out.println("content
of s5 "+s5); // Mahesh g Hundekari
System.out.println("Trim:"+s5.trim());
StringBuffer sb = new
StringBuffer("india ");
//System.out.println("contents of sb =
"+sb); sb.insert(5, 'a');
System.out.println(sb);
System.out.println("getChars:");
s5.getChars(1, 5, s12,5);
System.out.println(s12);
}
}
/*
* String finalString = s5.replace('h', 'r');
* System.out.println("string s5 content
after setting another character ..."
* +finalString);
*/
//Program to access object of one class into another class
package basic;
public class
Employee {
void show() {
Salary s = new
Salary();
s.salaryDetails();
}
public static void
main(String[] args) {
Employee e = new
Employee();
e.show();
}
}
package basic;
public class
Salary {
void salaryDetails(){
System.out.println("1,20,000");
}
}
// Java program to print numbers from 1 to 5 using recursion
package
basic;
public class
Recursion {
static int count=0;
static void
p(){
count++;
if(count<=5){
System.out.println("hello
"+count);
p();
}
}
public static void
main(String[] args) {
p();
}
}


Comments
Post a Comment