answersLogoWhite

0

📱

Java Programming

The Java programming language was released in 1995 as a core component of the Java platform of Sun Microsystems. It is a general-purpose, class-based, object-oriented language that is widely used in application software and web applications.

5,203 Questions

Can you change the size of an array dynamically in Java?

No, you can't change the size of an array dynamically. If you are needing to change the size of an array dynamically use an ArrayList, LinkedList, ConcurrrentHashMap, or another class that meets your needs.

Return type of malloc?

void * (If you used your help/manual system, you would get an answer much sooner.)

Why does a java compiler use C language?

The original Java compiler was probably written in C/C++ because an efficient language like C is ideal for writing compilers in.

What is thread class in java?

The ability of a program to concurrently execute multiple regions of code provides capabilities that are difficult or impossible to achieve with strictly sequential languages. Sequential object-oriented languages send messages (make method calls) and then block or wait for the operation to complete.

Programmers are already familiar with concurrent processes, possibly without

recognizing them. For example, operating systems usually have many processes

running to handle printing, updating the display, receiving mail from the network, and so on. In contrast, most programming languages do not promote the use of concurrent operations within one application. At best, programmers have access to a few library calls to launch and control multiple operations.

Java provides language-level and library support for threads--independent

sequences of execution within the same program that share the same code and data address space. Each thread has its own stack to make method calls and store local variables.

Most applications that use threads are a form of simulation or have a graphical

user interface, but threads in general have the following advantages over sequential programming:

Threads support concurrent operations.

For example, Server applications can handle multiple clients by launching a thread to deal with each client.

Long computations or high-latency disk and network operations can be handled in the background without disturbing foreground computations or screen updates.

Threads often result in simpler programs.

In sequential programming, updating multiple displays normally requires a big

while-loop that performs small parts of each display update. Unfortunately,

this loop basically simulates an operating system scheduler. In Java, each view

can be assigned a thread to provide continuous updates.

Programs that need to respond to user-initiated events can set up service

routines to handle the events without having to insert code in the main routine

to look for these events.

Threads provide a high degree of control.

Imagine launching a complex computation that occasionally takes longer than

is satisfactory. A "watchdog" thread can be activated that will "kill" the

computation if it becomes costly, perhaps in favor of an alternate,

approximate solution. Note that sequential programs must muddy the

computation with termination code, whereas, a Java program can use thread

control to non-intrusively supervise any operation.

Threaded applications exploit parallelism.

A computer with multiple CPUs can literally execute multiple threads on

different functional units without having to simulating multi-tasking ("time

sharing").

On some computers, one CPU handles the display while another handles

computations or database accesses, thus, providing extremely fast user

interface response times.

What is a unit inheritance?

Unit Inheritance or Single Inheritance refers to the situation where one class inherits/extends the features of another class

ex: public class A extends B {

.....

}

The above is an example of unit inheritance.

What are the errors in this code?

the code is:

function pppf($var1)

{

// Get PPPF Code Infomation

$sql = "SELECT * FROM pppf_code";

$pppf_query = mysql_query($sql);

while($pppf = mysql_fetch_assoc($pppf_query))

{

$y = mysql_num_rows($pppf_query);

if ($x<=$y)

{

$pppf_i = $pppf['input_text'];

$pppf_o = $pppf['output_text'];

$pppf_input = array($pppf_input.", '$pppf_i'");

$pppf_output = array($pppf_output.", '$pppf_o'");

}

}

echo $pppf_input['0']." | ".$pppf_output['0']."<br>";

$pppf_out = str_replace($pppf_input, $pppf_output, $var1);

echo $pppf_out;

}

What is the difference between a for loop and a while loop in java?

ComparisonThe conditions for both the 'while' and 'for' loop are exactly the same, but in each flow structure the conditions are placed in different locations. A 'for' loop places the full condition within the 'for' loop whereas the 'while' loop places the counter variable outside of the loop.

The 'for' loop is used when the length of the loop is known whereas the 'while' loop is usually used when the length of the loop is unknown.

'for' loop exampleWithin the parentheses the complete condition is contained. The condition has 3 parts delimited by a colon ';'. The first part sets the counter 'int i' to 0, the second part tells the loop to stop when the counter is 5. The third part tells java to increment the counter by 1 value each time the loop iterates.

for ( int i = 0; i < 5; i++)


'while' loop exampleWith the 'while' loop the counter is initialized outside of the 'while' loop. Inside the parentheses of the loop the condition is set to stop looping when the counter reaches a value of 5. Inside of the 'while' loop block the counter is set to increment by 1 value each time the loop iterates.

int i = 0;

while ( i < 5 ) {

i++

}

How do you Implement a Stack using an ArrayList in java?

Just add the elements to the end of the ArrayList, and take them out from the end of the ArrayList. Use the .add() method to add an element to the end; use the .size() method to find out how many elements it has (so you can access the last element), and use the .remove() method to eliminate this last element.

Difference between Dynamic binding and message passing in oop?

Message to method binding

A question of whether a message should bind to

  • a method in the class to which the reference variable pointing to the receiver was declared to be an instance of (static binding), or
  • a method in the class to which the receiver is an instance of at run-time (dynamic binding).
Dynamic binding
  • in the context of OOP typically refers to the binding of methods to messages
  • methods varying dynamically entails much of the power of the OO approach
  • main source of power in an OO language
  • search for method (code body) to bind to a message starts from the class to which the receiver currently (i.e., at run-time) is an instance of, and and proceeds up the class inheritance hierarchy from there (static binding initiates the search from the class to which the reference variable pointing to the receiver was declared to be an instance of)
  • if no method found anywhere, a run-time error (method not found) is reported and this is typically the only error in a Smalltalk program ever detected and reported
  • example: Mammal m; Cow c; if (user input) m = new Cow; // if static binding used, run method in class Mammal bound to run message here // if dynamic binding used, run method in class Cow bound to run message here m.run else c = new Cow; c.run
Why dynamic binding?
  • `to allow software systems to be more easily extended during both development and maintenance' [COPL] p. 461
  • allows dynamic polymorphism, consider sorting (written in a general way)
  • obviates need for abstract classes (e.g., Fruit class, peel method)
  • while other forms of dynamism in languages tend to be compromise efficiency in the run-time system, dynamic binding involves little overhead
Dynamic vs. static binding
  • advantages of each?
  • disadvantages of each?
Message to method binding in languages
  • Smalltalk
    • dynamic by default
    • by sending a message to super we can initiate the search (for the method to bind to the message) in the parent class of the class to which the sender belongs (i.e., like sending a message to self with a different entry point for the search (not quite static binding))
  • Java and Eiffel
    • dynamic by default
    • in Java, preface method with final qualifier to prevent any subclass from overriding it
    • in Eiffel, preface method with frozen qualifier to prevent any subclass from overriding it
  • C++
    • static by default (why?)
    • preface method with virtual qualifier for dynamic binding; the search for the method to bind to the message starts in the class which defines the method prefaced with the virtual qualifier and proceeds down the inheritance hierarchy from there to the class to which the receiver object belongs
  • Objective-C, Modula-3, Python, and Ruby use dynamic binding for all methods
  • Simula, C# and Ada 95 use static binding by default and support dynamic binding as an option
Dynamic binding ambiguity

Do not confuse dynamic binding of messages to methods with dynamic allocation and deallocations of objects.

  • Smalltalk: manual dynamic allocation, automatic deallocation
  • Java: manual dynamic allocation, automatic deallocation
  • C++: manual dynamic allocation, manual deallocation

What is Implicit garbage collection in java?

It returns memory to the memory pool by destroying objects that no longer have a reference to them.

Memory management is a crucial element in many types of applications. Consider a program that reads in large amounts of data, say from somewhere else on a network, and then writes that data into a database on a hard drive. A typical design would be to read the data into some sort of collection in memory, perform some operations on the data, and then write the data into the database. After the data is written into the database, the collection that stored the data temporarily must be emptied of old data or deleted and recreated before processing the next batch. This operation might be performed thousands of times, and in languages like C or C++ that do not offer automatic garbage collection, a small flaw in the logic that manually empties or deletes the collection data structures can allow small amounts of memory to be improperly reclaimed or lost forever. These small losses are called memory leaks, and over many thousands of iterations they can make enough memory inaccessible that programs will eventually crash. Creating code that performs manual memory management cleanly and thoroughly is a complex task.

Java's garbage collector provides an automatic solution to memory management. In most cases it frees you from having to add any memory management logic to your application. The downside to automatic garbage collection is that you can't completely control when it runs and when it doesn't.

Overview of Java's Garbage Collector

Garbage collection is the phrase used to describe automatic memory management in Java. Whenever a software program executes (in any programming language for that matter), it uses memory in several different ways. We're not going to get into Computer Science 101 here, but it's typical for memory to be used to create a stack, a heap, in Java's case constant pools, and method areas. The heap is that part of memory where Java objects live, and it's the one and only part of memory that is in any way involved in the garbage collection process.

So, all of garbage collection revolves around making sure that the heap has as much free space as possible. For the purpose of the exam, what this boils down to is deleting any objects that are no longer reachable by the Java program running. When the garbage collector runs, its purpose is to find and delete objects that cannot be reached. If you think of a Java program as being in a constant cycle of creating the objects it needs (which occupy space on the heap), and then discarding them when they're no longer needed, creating new objects, discarding them, and so on, the missing piece of the puzzle is the garbage collector. When it runs, it looks for those discarded objects and deletes them from memory so that the cycle of using memory and releasing it can continue.

What is the difference between local variable and global variable in Embedded C?

It's simple. A global variable has a scope through out out the C program. It can be accessed anywhere from any function or etc. A local variable on the other hand, is local to it's container only and can not be accessed outside of it's container. For example a function has variable sum then sum is only accessible within the function and not anywhere else.

Why do we overload a constructor?

We overload constructors to give options on how to initialize an object.

Public Person()

{

name=""

age=""

gender=""

}

...if you override

Public Person(String name, int age, String gender)

{

this.name=name

this.age=age

this.gender=gender

}

Now upon coding time, if you need to initialize it with parameters you have two choices:

  1. When an object will be initialized and you don't have to pass values to the parameter, use the constructor without parameters,
  2. and if you need to pass parameters, then use the one with parameters.

Now if you ask me what's the use?

well, since you are creating a class, you are encapsulating. you want as much to limit the use of your internal properties.

e.g.

private name

private birthyear

public Person(String name, Int age)

{

this.name=name

this.birthyear= yearNow-age

}

public Person(String name, Int birthdate)

{

this.name=name

this.birthdate=birthdate

}

You make sure that everytime a Person() is initialized, birthday property has a value either from age or birthdate.

I know the example is absurd but there are lots of complex example for this, I do overloading of constructors most of the time. from creating connection objects, to creating business process objects, since they differ in their needs.

Problem that often occur is code duplication. It's up to you to make a way to minimize/avoid duplication of code. usually I do this

public Person(String name, Int age)

{

Person(name, yearNow-age)

}

public Person(String name, Int birthyear)

{

this.name=name

this.birthyear=birthyear

Person();

}

Hope this gives an idea.

Which programming language should you use?

Depends on what you are trying to program! Games, web applications, mobile phone apps may use different languages. I'm not sure which ones use which as of 11-2009 but you need to determine that first!

What is system defined default constructor in java?

System defined constructor or Default constructor is the constructor that the JVM would place in every java class irrespective of whether we code it manually or not. This is to ensure that we do not have compile time issues or instantiation issues even if we miss declaring/coding the constructor specifically. Ex: public class Test { public String getName() { return "Rocky"l } Public static void main(String[] args){ Test obj = new Test(); String name = obj.getName(); } } Here we were able to instantiate the class Test even though we did not declare a no argument constructor. This is the default constructor that gets called when we try to instantiate it.

Is Java is platform dependent or independent?

Java is not machine dependent. High-level Java source code is compiled against the JVM which produces Java byte code, the lower-level native language of the JVM. At runtime, the JVM interprets the byte code to produce the required machine-dependent code. Every platform that supports Java has its own JVM, thus the same byte code can execute upon any supported platform. The translation from byte code to machine-dependent code is handled solely by the platform JVM.

What is the difference between single threaded and multithreaded in java?

A single threaded application is one that has only one thread of execution running at any given point of time. Whereas a multi-threaded application can have multiple threads of executing running simultaneously.

Generally in enterprise applications, we need to fetch and load a lot of data before the system starts or initializes. In such cases, we typically spawn multiple threads and let the load operations run in parallel to save time. Lets say you need to fetch 10 different sets of data each of which will run for approximately 1 minute, if you run them all in sequence one by one, your system will load only after 10 minutes. But, if you spawn 10 threads, the system might load in around 2 minutes which is much faster than the single threaded time.

Data abstraction and encapsulation in java?

Abstraction

Abstraction is simplifying complex reality by modelling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem.

For example, Lassie the Dog may be treated as a Dog much of the time, a Collie when necessary to access Collie-specific attributes or behaviors, and as an Animal (perhaps the parent class of Dog) when counting Timmy's pets.

Abstraction is also achieved through Composition. For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more components. To build the Car class, one does not need to know how the different components work internally, but only how to interface with them, i.e., send messages to them, receive messages from them, and perhaps make the different objects composing the class interact with each other.

Encapsulation

Encapsulation conceals the functional details of a class from objects that send messages to it.

For example, the Dog class has a bark() method. The code for the bark() method defines exactly how a bark happens (e.g., by inhale() and then exhale(), at a particular pitch and volume). Timmy, Lassie's friend, however, does not need to know exactly how she barks. Encapsulation is achieved by specifying which classes may use the members of an object. The result is that each object exposes to any class a certain interface - those members accessible to that class. The reason for encapsulation is to prevent clients of an interface from depending on those parts of the implementation that are likely to change in future, thereby allowing those changes to be made more easily, that is, without changes to clients. For example, an interface can ensure that puppies can only be added to an object of the class Dog by code in that class. Members are often specified as public, protected or private, determining whether they are available to all classes, sub-classes or only the defining class. Some languages go further: Java uses the default access modifier to restrict access also to classes in the same package, C# and VB.NET reserve some members to classes in the same assembly using keywords internal (C#) or Friend (VB.NET), and Eiffel and C++ allow one to specify which classes may access any member.

Is the default access specifier same as protected?

A private member of a class can only be accessed by methods of that class.

A protected member of a class can only be accessed by methods of that class and by methods of a derived class of that class.

What is Linear and non linear list in data structure?

Linear : Traversal is linear .. ex: array,linked lists,stacks,queues NoN-linear: Traversal is not linear.. ex:trees,graphs imagine the situation of searching of particular element..in above scenarious..then u will understand easily.. Linear : Traversal is linear .. ex: array,linked lists,stacks,queues NoN-linear: Traversal is not linear.. ex:trees,graphs imagine the situation of searching of particular element..in above scenarious..then u will understand easily.. Linear : Traversal is linear .. ex: array,linked lists,stacks,queues NoN-linear: Traversal is not linear.. ex:trees,graphs imagine the situation of searching of particular element..in above scenarious..then u will understand easily..

How does you set the path of java progrramig?

In Windows:

  • Copy the lib path of the java jdk from where it is installed.
  • Open command promt.
  • Type the following command.

set CLASSPATH=

Example:

C:\>set classpath=C:\Java\jdk1.6.0_03\lib

What do you get when you compile a java program?

The java interpreter or JVM (Java Virtual Machine) is not able to execute the java source code for a program. The java source code first needs to be compiled into bytecode that can be processed by JVM.

Producing bytecode make the program platform independent as each platform has its own JVM. It is also possible to directly write bytecode, bypassing the need to compile, but that would be tedious job and also not good for security purpose as the compiler checks for various errors in a program.

What keyword is used to declare a named constant?

Constant in Java refers to a fixed value that doesn’t change during the execution of a program. The value of constants appears right in a program. It is also known as Literals. We use the constants to create values that assign to variables. Constants can make our program easy to read and understood by others.

Java does not directly support the constant. To define a variable as a constant, We use the “Static” and “Final” Keywords before declaring a variable.

Hope this helps. Thank you

How do you reverse the order of the elements in the array?

Start by pointing to each end of the array. Work your way towards the middle of the array, swapping elements as you go. When the pointers meet or pass each other, the array is completely reversed.

Why is java often termed as a platform?

The word "platform" in this context refers to the environment - the combination of hardware and software - on which a program runs. For example, some programs are designed to work specifically on Intel processors, and on the Microsoft Windows operating system. In the case of Java, programs written in Java are designed to work on a special program called the Java Virtual Machine (JVM) - this would be the platform. Since JVM programs have been created for many operating systems and processors, programs written in the Java language can run on many operating systems as well. You might say that it is "multiplatform", but you might also say that the "platform" is the JVM.

Note that in this case "platform" does NOT refer to the Java programming language, but specifically to the JVM.

Documentation of Hostel management system?

There are a lot of commercial packages that do this; use Google to locate the vendors.