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

java programs

The document contains various Java programming examples demonstrating concepts such as finding a missing digit in an array, calculating the sum of digits, checking if a number is even or odd, and handling exceptions. It also covers string manipulation, thread creation, and the immutability of strings. Additionally, it explains the differences between call by value and call by reference, along with code snippets illustrating these concepts.

Uploaded by

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

java programs

The document contains various Java programming examples demonstrating concepts such as finding a missing digit in an array, calculating the sum of digits, checking if a number is even or odd, and handling exceptions. It also covers string manipulation, thread creation, and the immutability of strings. Additionally, it explains the differences between call by value and call by reference, along with code snippets illustrating these concepts.

Uploaded by

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

1.

Optimized array program to get a missing only 1 digit in 1st 10 digits that are non-ordered and non-
duplicte

public class Main

public static void main(String[] args) {

System.out.println("Hello World");

int sum=0;

int[] arr={8,9,5,1,2,6,7,3,4,10};

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

sum=sum+arr[i];

}*/

for(int I : arr){

sum=sum+I;

if(sum==55)

System.out.println("no element is missed");

else

System.out.println(55-sum"+ is missing");

Note : n(n+1)/2 where n is no.of digits in the array

2.Optimized code for getting sum og Digits upto single digit

public class Main


{

public static void main(String[] args) {

System.out.println("Hello World");

int num=12345;;

int sum=(num%9==0?9:num%9);

System.out.println(sum );

3.Find a given number is even or odd without using loops and conditipnal statements??

Int num=10;

String[] result={“even”,”odd”};

System.out.println(result[num%2]);

_________________________________________________________________

package com.learn;

public class App {


public static void main(String[] args) {
System.out.println(m1());
}

public static String m1() {


try {
System.out.println("A");
return "B";
} catch (Exception e) {
return "c";
}
finally {
System.out.println("D");
}
}}
O/P : A D B
package com.learn;

public class App {


public static void main(String[] args) {
m1(null);
}

public static void m1(Object o) {


System.out.println("object");
}

public static void m1(String s) {


System.out.println("string");
}

}
OP:String
If we pass any other argumnet like
Integer i=10;
m1(i); then OP is Object

 System.out.print(m1(null));
--> The method print(boolean) in the type PrintStream is not applicable
for the arguments (void)

int x=1;
if((boolean)x==true)
-->>Cannot cast from int to boolean
package com.learn;
public class App {
public static void main(String[] args) {
App p=new App();
p.m1(10, 10);// The method m1(int, float) is ambiguous for the type
App
}
public void m1(int a, float b)
{
System.out.println("int - float");
}
public void m1(float a, int b ) {
System.out.println("float - int ");
}
}
CE: The method m1(int, float) is ambiguous for the type App

package com.learn;

public class App {


public static void main(String[] args) {
for(int i=1;i<=12;i=i+2)
{
if (i==8) {
System.out.println(i);break;
}
}}}
OP: N/A
package com.learn;
public class App {
public static void main(String[] args) {
String s=new String("shekar").intern();
String s2=new String("shekar").intern();
System.out.println(s==s2);
}

}
OP: true
The intern() method in Java is used to place a String object into the pool of
strings, which acts as a kind of internal cache. When intern() is called on a
String object, Java checks if the string already exists in the pool. If it does,
the method returns a reference to the string from the pool. If the string
doesn't exist in the pool, it's added to the pool and then its reference is
returned

package com.learn;

public class App {


public static void main(String[] args) {
String s=null;
System.out.println(s==null);
}

OP: true

package com.learn;
public class App {
public static void main(String[] args) {
String s1="java";
String s2="java";
s1=s1+"rules";
System.out.println(s1==s2));
}}
OP :false

System.out.println(s1.equals(“javarules”));
op:true

package com.learn;

public class myapp {


static boolean myBoolean;
public static void main(String[] args) {

System.out.println("shekar");
System.out.println(myBoolean);
}

}
OP: shekar
False

package com.learn;
public class myapp {
public static void main(String[] args) {
boolean myBoolean;
System.out.println("ajgjha");
System.out.println(myBoolean);
}
}
CE: The local variable myBoolean may not have
been initialized

package com.learn;

public class myapp {


public static void main(String[] args) {
try {
return;
} finally {
System.out.println("finally");
}
}

}
Op: finally

public class myapp {


public static void main(String[] args) {
int x=3;
int y=4;
switch (x+3) {
case 6: y=0;
System.out.println(y);

case 7: y=1;
System.out.println(y);

default:y=y+1;
System.out.println(y); }
}

}
OP : 0 1 2

public class Main


{
public static void main(String[] args) {
System.out.println("Hello World");
String s=null;
System.out.println(s);
System.out.println(s.toString());
}
}

OP:
Hello World
null
Exception in thread "main"
java.lang.NullPointerException
at Main.main(Main.java:15)
parent p = new child ();????

class parent
{
void m1 ()
{
System.out.println ("IN parent-M1()");
}
void m3 ()
{
System.out.println ("IN parent-M3()");
}

class child extends parent


{
void m1 ()
{

System.out.println ("IN child-M1()");


}
void m2 ()
{
System.out.println ("CHild - m2()");
}}

public class Main


{
public static void main (String[]args)
{
/*parent a = new parent (); //cant call
child methods using parent object
a.m1 ();
a.m3 ();
// a.m2 (); */

child c = new child ();


c.m1 ();
parent p = new child ();
p.m1 ();
p.m3();

package test;

public class app {


public static void main(String[] args) {
try {
System.out.println("hello");
System.out.println(10 / 0);
System.out.println("done");
}

catch (Exception e) {
System.out.println("exception
occured");
e.printStackTrace();
//
System.out.println(e.getMessage());
//
System.out.println(e.getStackTrace());
}
}
}

Custom Exception:
package test;

import java.util.Scanner;

public class app {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter
amount>100");
try {
int amount = sc.nextInt();
if (amount < 100) {
throw new myExceeption("enter
amount > 100");
} else
System.out.println(amount);
} catch (Exception e) {
System.out.println("exception
occured");
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

class myExceeption extends Exception {


myExceeption(String msg) {
super(msg);
}
}

Program for thread creation using extending a


Thread class and implementing a Runnable
interface….
(NOTE : Output for a multi threaded program is
unpredictable )
package test;

import java.util.Iterator;
import java.util.Scanner;

public class app {


public static void main(String[] args) {
myTread t1=new myTread();
t1.start();
threadWithRunnable twr=new
threadWithRunnable();
Thread t2=new Thread(twr);
t2.start();
for (int i = 1; i <= 10; i++) {
System.out.println("main " + i);
}

}
}

class myTread extends Thread {


@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("child " + i);
}
}
}
class threadWithRunnable implements
Runnable{

@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Runnable
thread" + i);
}
}}
}
Program to demonstrate JOIn()
package test;

public class app {


public static void main(String[] args)
throws InterruptedException {
JD3 jd3 = new JD3();
JD2 jd2 = new JD2();
jd2.jd3=jd3;
jd2.start();

jd3.start();
jd2.join();
System.out.println("S3-Parsing data
from files and save to DB");
}
}

class JD2 extends Thread {


JD3 jd3;
// JD3 jd3 = new JD3();

@Override
public void run() {
try {
jd3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("S2-connectong to
AWS - s3 ");
}
}

class JD3 extends Thread {


@Override
public void run() {
System.out.println("S1-Fetch
credentials from Filestore");
}
}

Without using Synchronized keyword sum of N -


numbers

package test;

public class app {


public static void main(String[] args)
throws InterruptedException {
myThread t = new myThread();
t.start();
Thread.sleep(1);
System.out.println(t.sum);
}
}

class myThread extends Thread {


int sum;

@Override
public void run() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch
block
e.printStackTrace();
}
for (int i = 1; i <= 100; i++) {
sum = sum + i;

}
}
}

t.join() is not efficient because:


In below we only need sum value but here we are
waiting for hello to print for 10 times and then
we are having our sum value. So it is not
efficient;

package test;

public class app {


public static void main(String[] args)
throws InterruptedException {
myThread t = new myThread();
t.start();
t.join();
System.out.println(t.sum);
}
}
class myThread extends Thread {
int sum;

@Override
public void run() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch
block
e.printStackTrace();
}
for (int i = 1; i <= 100; i++) {
sum = sum + i;

}
for (int i = 1; i <= 10; i++) {
System.out.println("hello "+i);
}
}
}

Pprogram for using wait() notify()


notifyAll();
public class app {
public static void main(String[] args)
throws InterruptedException {
myThread t = new myThread();
t.start();
synchronized (t) {
t.wait();
System.out.println(t.sum);

}}}
class myThread extends Thread {
int sum;
@Override
public void run() {
synchronized (this) {
for (int i = 1; i <= 100; i++) {
sum = sum + i;
}
this.notify();
}
for (int i = 1; i <= 10; i++) {
System.out.println("hello " + i);
}}}

public class app {


public static void main(String[] args)
throws InterruptedException {
String name = "shekar";
String fname = "shekar";

String owner = "shekar";


owner = "shekar-eddandi";
System.out.println(name + " " +
fname + " " + owner);

//
*******************************************
*****************//

char[] c = { 's', 'h', 'e', 'k',


'a', 'r' };
String s = new String(c);
System.out.println("converted to
string from char : " + s);
System.out.println("converting to
lower case : " + s.toLowerCase());
System.out.println("converting to
upper case : " + s.toUpperCase());
System.out.println("checking
contains : " + s.contains("kaar"));

System.out.println("converted to
char from string : " + s.toCharArray());

char[] aa = s.toCharArray();
System.out.println(aa);
System.out.println(aa[3]);
//
*******************************************
**************//
owner.toUpperCase(); // toUppercase
will return a string. it doesn't modify the
existing string
System.out.println(owner); // this
is because Immutability
String newOwner =
owner.toUpperCase();
System.out.println(newOwner);

System.out.println(newOwner.equals(owner));

System.out.println(newOwner.equalsIgnoreCas
e(owner));

//
*******************************************
*********//

String str = "raja";


System.out.println(str.indexOf('a'));
System.out.println(str.charAt(0));

//
*******************************************
***************************//
String n = "Rajashekar";
System.out.println(n.substring(1));
System.out.println(n.substring(0,
4));
/****************************//
String n="shekar is a good boy";
System.out.println("splitting.....");
String[] newN=n.split(" ");
for(String sss:newN)
System.out.println(sss);
}
}

Showing strings are immutable..


package test;

public class app {


public static void main(String[] args)
throws InterruptedException {
String str1 = "Hello"; // Create a
string "Hello"
System.out.println("Original
String: " + str1);
// Attempting to change the string
String str2 =str1.concat(" World");
// Concatenating " World" to str1
System.out.println("Modified
String: " + str2);}
}

Same program
public class app {
public static void main(String[] args)
{
String s1=new String("shekar");
s1.concat("Raja");
String str = s1.concat("eddandi");
System.out.println(s1);
System.out.println(str);
StringBuilder s2=new
StringBuilder("sheki");
s2.append("Raj");
System.out.println(s2);
}
}

Reverse a string
public class app {
public static void main(String[] args) {
String s = "213";
System.out.println("given String
is : " + s);
char[] c = s.toCharArray();
int j=0;
char[] str = new char[s.length()];
for (int i = s.length() - 1; i >= 0;
i--) {
str[j] = c[i];
j++;
}
// for (char ch : str) {
// System.out.print(ch);
// }
// String a=new String(str);
System.out.println(new String(str));
String name="shekar";
for (int jj = name.length()-1; jj
>=0; jj--) {
System.out.print(name.charAt(jj));
}
}

Optimized code for reverse string


package test;

public class app {


public static void main(String[] args) {

String s="rajashekar";
char[] c=s.toCharArray();
int start=0,end=c.length-1;
while(start<=end) {
char temp=c[start];
c[start]=c[end];
c[end]=temp;
start++;
end--;
}
System.out.println(new String(c));
}

Optimized code for reverse String:


public class App {
public static void main(String[] args) {
String s = "rajashekar";

int length = s.length();


String reversed = "";

for (int i = length - 1; i >= 0; i--) {


reversed += s.charAt(i);
}
System.out.println(reversed);
}
}

Call by value and call by reference :


public class app {
public static void main(String[] args) {
int a=10;
primitivesCallByValue(10);
ObjectcallByReferance();
System.out.println("the value of
primitive has not changed : "+a);
}

private static void


primitivesCallByValue(int i) {
System.out.println("Original value :
"+i);
i=20;
System.out.println("changed value :
"+i);
}

private static void


ObjectcallByReferance() {
app p = new app(5, "shekar");
System.out.println("initail values
of object : "+p.id+" - "+p.name);
p.id=3;
p.name="sagar";
System.out.println("changed values
of object : "+p.id+" - "+p.name);
}
private int id;
private String name;

app(int id, String name) {


this.id = id;
this.name = name;
}
}

1. Call by Value:
 In call by value, a copy of the actual parameter's value is passed to the
method.
 The method works with this copy, and any changes made to the
parameter within the method don't affect the original value outside the
method.
 Primitive data types (like int, float, char, etc.) use call by value.
public class CallByValueExample {
public static void main(String[] args) {
int num = 10;
System.out.println("Before calling method: " + num);
modifyValue(num);
System.out.println("After calling method: " + num);
}

public static void modifyValue(int number) {


number = 20; // Changes are made to the copy of 'num'
System.out.println("Inside method: " + number);
}
}

2. Call by Reference (or Call by Object Reference):


• In call by reference, the reference (memory
address) to the object is passed to the method, not a
copy of the object itself.
• If the method modifies the object's state
(attributes, fields, etc.), these changes will be
reflected in the original object outside the method.
• Java uses call by value for passing references (not
call by reference).

EX:
public class CallByReferenceExample {
public static void main(String[] args) {
MyClass obj = new MyClass();
System.out.println("Before calling method: " +
obj.value);
modifyObject(obj);
System.out.println("After calling method: " +
obj.value);
}

public static void modifyObject(MyClass object) {


object.value = 30; // Changes are made to the
original object
System.out.println("Inside method: " +
object.value);
}
}

class MyClass {
int value = 10;
}

You might also like