[Go to site: main page, start]

0% found this document useful (0 votes)
15 views28 pages

Java Code Output and Analysis

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)
15 views28 pages

Java Code Output and Analysis

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

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) {

[Link]("Hello World");

int sum=0;

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

/*for(int i=0;i<[Link];i++)

sum=sum+arr[i];

}*/

for(int I : arr){

sum=sum+I;

if(sum==55)

[Link]("no element is missed");

else

[Link](55-sum"+ is missing");

Note : n(n+1)/2 where n is [Link] digits in the array

[Link] code for getting sum og Digits upto single digit

public class Main


{

public static void main(String[] args) {

[Link]("Hello World");

int num=12345;;

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

[Link](sum );

[Link] a given number is even or odd without using loops and conditipnal statements??

Int num=10;

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

[Link](result[num%2]);

_________________________________________________________________

package [Link];

public class App {


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

public static String m1() {


try {
[Link]("A");
return "B";
} catch (Exception e) {
return "c";
}
finally {
[Link]("D");
}
}}
O/P : A D B
package [Link];

public class App {


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

public static void m1(Object o) {


[Link]("object");
}

public static void m1(String s) {


[Link]("string");
}

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

 [Link](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 [Link];
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)
{
[Link]("int - float");
}
public void m1(float a, int b ) {
[Link]("float - int ");
}
}
CE: The method m1(int, float) is ambiguous for the type App

package [Link];

public class App {


public static void main(String[] args) {
for(int i=1;i<=12;i=i+2)
{
if (i==8) {
[Link](i);break;
}
}}}
OP: N/A
package [Link];
public class App {
public static void main(String[] args) {
String s=new String("shekar").intern();
String s2=new String("shekar").intern();
[Link](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 [Link];

public class App {


public static void main(String[] args) {
String s=null;
[Link](s==null);
}

OP: true

package [Link];
public class App {
public static void main(String[] args) {
String s1="java";
String s2="java";
s1=s1+"rules";
[Link](s1==s2));
}}
OP :false

[Link]([Link](“javarules”));
op:true

package [Link];

public class myapp {


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

[Link]("shekar");
[Link](myBoolean);
}

}
OP: shekar
False

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

package [Link];

public class myapp {


public static void main(String[] args) {
try {
return;
} finally {
[Link]("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;
[Link](y);

case 7: y=1;
[Link](y);

default:y=y+1;
[Link](y); }
}

}
OP : 0 1 2

public class Main


{
public static void main(String[] args) {
[Link]("Hello World");
String s=null;
[Link](s);
[Link]([Link]());
}
}

OP:
Hello World
null
Exception in thread "main"
[Link]
at [Link]([Link])
parent p = new child ();????

class parent
{
void m1 ()
{
[Link] ("IN parent-M1()");
}
void m3 ()
{
[Link] ("IN parent-M3()");
}

class child extends parent


{
void m1 ()
{

[Link] ("IN child-M1()");


}
void m2 ()
{
[Link] ("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 {
[Link]("hello");
[Link](10 / 0);
[Link]("done");
}

catch (Exception e) {
[Link]("exception
occured");
[Link]();
//
[Link]([Link]());
//
[Link]([Link]());
}
}
}

Custom Exception:
package test;

import [Link];

public class app {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("enter
amount>100");
try {
int amount = [Link]();
if (amount < 100) {
throw new myExceeption("enter
amount > 100");
} else
[Link](amount);
} catch (Exception e) {
[Link]("exception
occured");
[Link]([Link]());
[Link]();
}
}
}

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 [Link];
import [Link];

public class app {


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

}
}

class myTread extends Thread {


@Override
public void run() {
for (int i = 1; i <= 10; i++) {
[Link]("child " + i);
}
}
}
class threadWithRunnable implements
Runnable{

@Override
public void run() {
for (int i = 1; i <= 10; i++) {
[Link]("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;
[Link]();

[Link]();
[Link]();
[Link]("S3-Parsing data
from files and save to DB");
}
}

class JD2 extends Thread {


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

@Override
public void run() {
try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
[Link]("S2-connectong to
AWS - s3 ");
}
}

class JD3 extends Thread {


@Override
public void run() {
[Link]("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();
[Link]();
[Link](1);
[Link]([Link]);
}
}

class myThread extends Thread {


int sum;

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

}
}
}

[Link]() 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();
[Link]();
[Link]();
[Link]([Link]);
}
}
class myThread extends Thread {
int sum;

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

}
for (int i = 1; i <= 10; i++) {
[Link]("hello "+i);
}
}
}

Pprogram for using wait() notify()


notifyAll();
public class app {
public static void main(String[] args)
throws InterruptedException {
myThread t = new myThread();
[Link]();
synchronized (t) {
[Link]();
[Link]([Link]);

}}}
class myThread extends Thread {
int sum;
@Override
public void run() {
synchronized (this) {
for (int i = 1; i <= 100; i++) {
sum = sum + i;
}
[Link]();
}
for (int i = 1; i <= 10; i++) {
[Link]("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";
[Link](name + " " +
fname + " " + owner);

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

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


'a', 'r' };
String s = new String(c);
[Link]("converted to
string from char : " + s);
[Link]("converting to
lower case : " + [Link]());
[Link]("converting to
upper case : " + [Link]());
[Link]("checking
contains : " + [Link]("kaar"));

[Link]("converted to
char from string : " + [Link]());

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

[Link]([Link](owner));

[Link]([Link]
e(owner));

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

String str = "raja";


[Link]([Link]('a'));
[Link]([Link](0));

//
*******************************************
***************************//
String n = "Rajashekar";
[Link]([Link](1));
[Link]([Link](0,
4));
/****************************//
String n="shekar is a good boy";
[Link]("splitting.....");
String[] newN=[Link](" ");
for(String sss:newN)
[Link](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"
[Link]("Original
String: " + str1);
// Attempting to change the string
String str2 =[Link](" World");
// Concatenating " World" to str1
[Link]("Modified
String: " + str2);}
}

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

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

Optimized code for reverse string


package test;

public class app {


public static void main(String[] args) {

String s="rajashekar";
char[] c=[Link]();
int start=0,end=[Link]-1;
while(start<=end) {
char temp=c[start];
c[start]=c[end];
c[end]=temp;
start++;
end--;
}
[Link](new String(c));
}

Optimized code for reverse String:


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

int length = [Link]();


String reversed = "";

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


reversed += [Link](i);
}
[Link](reversed);
}
}

Call by value and call by reference :


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

private static void


primitivesCallByValue(int i) {
[Link]("Original value :
"+i);
i=20;
[Link]("changed value :
"+i);
}

private static void


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

app(int id, String name) {


[Link] = id;
[Link] = 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;
[Link]("Before calling method: " + num);
modifyValue(num);
[Link]("After calling method: " + num);
}

public static void modifyValue(int number) {


number = 20; // Changes are made to the copy of 'num'
[Link]("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();
[Link]("Before calling method: " +
[Link]);
modifyObject(obj);
[Link]("After calling method: " +
[Link]);
}

public static void modifyObject(MyClass object) {


[Link] = 30; // Changes are made to the
original object
[Link]("Inside method: " +
[Link]);
}
}

class MyClass {
int value = 10;
}

Common questions

Powered by AI

Throwing a custom exception in Java can enhance error handling by providing more meaningful context about the error, allowing developers to identify and address the specific problem more easily. Custom exceptions extend the Exception class and can include additional fields and methods to convey detailed information about the nature of the error, potentially allowing for more precise logging, tracking, and debugging . This approach also aids in differentiating between different types of errors, leading to more robust and maintainable code.

In Java, using the intern() method on strings optimizes memory by storing unique strings in the runtime String pool. This means interning allows for object comparison using reference equality rather than content equality. For instance, if two strings were created using the new keyword and intern() was applied, they could be compared with the '==' and return true because they point to the same memory location within the pool .

Synchronization is crucial in a multithreaded Java program to prevent thread interference and ensure accurate calculation of a sum. When multiple threads access and modify shared data concurrently, such as a sum variable, synchronization is needed to ensure that operations on the variable are atomic and orderly. Without synchronization, thread scheduling could lead to race conditions, where the output's correctness is dependent on the sequence of thread execution, resulting in inconsistent or incorrect sum calculations . Proper synchronization ensures only one thread modifies the shared data at a time, maintaining data integrity and program correctness.

Interning in Java stores a single copy of each distinct literal string in a pool, a special memory region. When the intern() method is used on a string, Java checks this pool; if the string is already present, it returns a reference to it. This mechanism allows for string comparison using the == operator instead of equals(), as interned strings refer to the same object in memory .

In Java, the try-catch-finally block is crucial for exception handling. The try block encloses code that might throw an exception, providing a mechanism for the program to continue functioning even when errors occur. The catch block handles specific exceptions thrown by the try block, allowing for the execution of appropriate error-handling code. Finally, the finally block executes regardless of whether an exception was thrown or caught, usually used for resource cleanup, like closing files or releasing resources . This structure ensures the program is robust and handles errors gracefully, reducing potential system crashes or data loss.

Mixing numeric and boolean data types in Java can lead to compilation errors because these types are inherently incompatible. Java's strong type system doesn't allow direct casting between numerics and booleans, which have distinct logical and arithmetic roles. An example error arises when trying to cast an integer to a boolean, resulting in 'Cannot cast from int to boolean' . This restriction enforces type safety, preventing the use of unintended logical or arithmetic operations that may lead to unpredictable results.

The join() method in Java is used to wait for the completion of a thread. By calling join() on a thread, the current thread suspends its execution until the target thread completes. This is useful when threads are performing coordinated tasks and one thread must finish before others can proceed. While join() helps manage thread dependencies and sequencing, it should be used judiciously to avoid deadlocks and ensure that resources are effectively utilized without unnecessary waiting . Thus, join() is a powerful but complex tool in thread management that requires careful application.

In Java, the call-by-value mechanism involves passing a copy of the actual parameter. For primitives, this means that changes within a method don’t affect the original variable outside the method; only the local copy is changed. Conversely, when objects are involved, a copy of the reference is passed. This means any changes to the object's fields affect the original object, as both the original and the copy refer to the same object in memory . Thus, while Java is technically call-by-value, in case of objects, it works similarly to call-by-reference in other languages, causing significant confusion and potential errors if misunderstood.

In Java, the wait() and notify() methods are part of the Object class and are essential for thread communication when dealing with concurrency. A thread that calls wait() on an object enters a waiting state and releases the object's lock, allowing other threads to execute. When a thread calls notify(), it wakes up one of the waiting threads, enabling it to acquire the object's lock and proceed with execution. This mechanism is crucial for scenarios requiring synchronization and coordination among multiple threads to ensure data consistency and avoid race conditions .

Java's string immutability means that once a string object is created, its content cannot be changed. This characteristic has several implications for software design: it enhances security and efficiency by making strings inherently thread-safe and facilitating safe sharing and caching. It also simplifies code maintenance by preventing unintended string modifications. However, immutability can lead to increased overhead when concatenating strings, as a new object is created each time, necessitating structures like StringBuilder for efficient string manipulations . Overall, immutability is a beneficial design choice in terms of reliability and performance trade-offs.

You might also like