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

What are the rules for naming variables in java?

Some basic conventions are:
1. you cannot have keywords as names
2. All identifiers have to start with an alphabet
3. Except '_' and '$' no other special character is allowed in names
4. When there are multiple words in an identifier we usually capitalize the first alphabets of each word. For example if an identifier represents name of employee then we name it as nameOfEmployee. The first word would remain normal with no capitalization

etc...

Difference between static and non static constructor?

A static constructor is used to do anything you need done before any static methods are called such as static variable initialization. In Java (as in C#) when a static constructor is called is non-deterministic but will always be called before a static method on the same class.

Why java does not support friend function?

One of the main goals kept in mind while Java was being developed was that they wanted it to be like C++, but without all the features which make the language overly complex and messy. These features include things like (true) multiple inheritance, operator overloading, and friend functions.

What is the main feature in object oriented programming?

[Eating] A Pie:

Abstraction: grouping some data and behaviors into a programming unit with semantic similarity (not randomly), e.g, class, struct

Polymorphism: different object with the same name (same name of a method, variable, but in more than 1 form)

Inheritance: the most important characteristics of an OO language (Object base language would not have this one). It allows a derived class to inherit the data and behaviors from the base class(es), as if those data and behaviors are defined within.

Encapsulation: or information hiding. Object has data members that no one outside of the same class would know what type or shape they are. It also applied to the behaviors.

Serialization in java?

Imagine you want to save the state of one or more objects. If Java didn't have serialization, you'd have to use one of the I/O classes to write out the state of the instance variables of all the objects you want to save. The worst part would be trying to reconstruct new objects that were virtually identical to the objects you were trying to save. You'd need your own protocol for the way in which you wrote and restored the state of each object, or you could end up setting variables with the wrong values. For example, imagine you stored an object that has instance variables for height and weight. At the time you save the state of the object, you could write out the height and weight as two ints in a file, but the order in which you write them is crucial. It would be all too easy to re-create the object but mix up the height and weight values-using the saved height as the value for the new object's weight and vice versa.

The purpose of Serialization is to help us achieve whatever complicated scenario we just witnessed in an easier manner.

Working with ObjectOutputStream and ObjectInputStream

The magic of basic serialization happens with just two methods: one to serialize objects and write them to a stream, and a second to read from the stream and deserialize the object.

ObjectOutputStream.writeObject() - serialize and write

ObjectInputStream.readObject() - read and deserialize

The java.io.ObjectOutputStream and java.io.ObjectInputStream classes are considered to be higher-level classes in the java.io package, and as we learned in the previous chapter that means that you'll wrap them around lower-level classes, such as java.io.FileOutputStream and java.io.FileInputStream. Here's a small program that creates an object, serializes it, and then deserializes it:

import java.io.*;

class Car implements Serializable { } // 1

public class SerializeCar {

public static void main(String[] args) {

Car c = new Car(); // 2

try {

FileOutputStream fs = new FileOutputStream("testSer.ser");

ObjectOutputStream OS = new ObjectOutputStream(fs);

OS.writeObject(c); // 3

OS.close();

} Catch (Exception e) { e.printStackTrace(); }

try {

FileInputStream fis = new FileInputStream("testSer.ser");

ObjectInputStream ois = new ObjectInputStream(fis);

c = (Car) ois.readObject(); // 4

ois.close();

} Catch (Exception e) { e.printStackTrace(); }

}

}

Let's take a look at the key points in this example:

1. We declare that the Car class implements the Serializable interface. Serializable is a marker interface; it has no methods to implement.

2. We make a new Car object, which as we know is serializable.

3. We serialize the Car object c by invoking the writeObject() method. First, we had to put all of our I/O-related code in a try/Catch block. Next we had to create a FileOutputStream to write the object to. Then we wrapped the FileOutputStream in an ObjectOutputStream, which is the class that has the magic serialization method that we need. Remember that the invocation of writeObject() performs two tasks: it serializes the object, and then it writes the serialized object to a file.

4. We de-serialize the Car object by invoking the readObject() method. The readObject() method returns an Object, so we have to cast the deserialized object back to a Car. Again, we had to go through the typical I/O hoops to set this up.

This is a simple example of serialization in action.

What is heap size in Java?

Java heap is the heap size allocated to JVM applications which takes care of the new objects being created. If the objects being created exceed the heap size, it will throw an error saying memoryOutof Bound Java's default heap size limit is 128MB. If you need more than this, you should use the -Xms and -Xmx command line arguments when launching your program:

java -Xms -Xmx We can also give like in this format also.format is : -mx256m..Sometimes it will show error if you are using java -Xms -Xmx format..In that case use -mx256m this.value can be changed..

Write a Java program to convert a decimal no to binary?

Here's a simple Java method to perform the conversion from decimal to a binary string representation:
public String toBinaryString(int n) {
StringBuilder sb = new StringBuilder();
while(n != 0) {
sb.insert(0, n % 2 != 0 ? '1' : '0');
n /= 2;
}
return sb.toString();
}

The java.lang.Integer class provides a conversion helper method between decimal (integer) and binary numbers in string form called toBinaryString().

String binaryValue = Integer.toBinaryString(43) // 43-> "101011"

When a variable is declared within a method it ceases to exist when the method ends true or false?

It really depends on the programming language, but in general, this is true. In Java, for example, the scope of a variable declared in a method is the method - outside of the method it is inaccessible, and once the method finishes execution, the variable disappears.

Where are store static variable in memory?

static variables are stored in a special area of the heap called the "permanent generation".

What is the purpose of vector Java?

Vector is a type of collection object that Java has. Vector is a class that implements the AbstractList class and is often used as an alternative to arrays since it automatically extends the length of the list unlike arrays. A Vector can contain a collection of objects of any type. But it has fallen out of use due to the rise of the more convenient ArrayList class, but Vectors are still used for their security in multi threaded environment. Vectors are thread safe but array lists are not. An important fact to note is that Stack extends the Vector class.

How do you write a loop that sums the odd numbers from 1 to 100 in Java format?

Like this:

int sum = 0;

for(int i = 1; i<=100; i+=2){

sum+=i;

}

The "for" loop starts the counter i at 1, continues while it is less than or equal to 100, and increments it by 2 at a time.

Is oracle better than java for the job market?

Java is an object oriented programming language while Oracle is a Relational Database Management System. They are totally different and in no way similar to one another in terms of their features and abilities.

Oracle is also the name of the company which makes and sells the Oracle database. It also owns Java as a result of its acquisition of Sun Microsystems which created Java.

How do you write an if statement on java?

Very simple example of an If statement checking a password just so you can see the syntax..



if (Password.equals("Password123"))
{
System.out.println("Welcome");
}
else
{
System.out.println("Incorrect Password");
}

With an example explain the different string methods in java?

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings. Creating Strings The most direct way to create a string is to write: String greeting = "Hello world!"; In this case, "Hello world!" is a string literal-a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value-in this case, Hello world!. As with any other object, you can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters: char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'}; String helloString = new String(helloArray); System.out.println(helloString); The last line of this code snippet displays hello. Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.

Can private members of a class be inherited?

All fields and methods of a class are inherited:

public class A

{private int x =10;public int XVal{get{return x;}}}

public class B:A

{public B(){x = 20;}}

Why java interpreted?

Java is both compiled and interpreted.

At first, the Java source code (in .java files) is compiled into the so-called Bytecode (.class files). The Bytecode is a pre-compiled, platform independent version of your program. The .class files can be used on any operating system.

When the Java application is started, the Bytecode is interpreted by the Java Virtual Mashine. Because the Bytecode is pre-compiled, Java does not have the disadvantages of classical interpreted languages, like BASIC.

Explain how a private data of a base class can be accessed by publicly derived class?

The only way that private attributes of a base class can be accessed by a derived class (protected or public) is through a protected or public method in the base class.

The protected or public method is the interface through which access to the attributes is defined and controlled.

Is there a Java program for finding the zodiac sign?

I could make one, but "a program of zodiac signs" tells me little.

How do you display hello world java?

The standard "Hello World" program in Java looks like:

class HelloWorld {

public void main(String[] args)

{

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

}

} //end class

C program to find prime number?

I am providing a succinct and easy to understand version of the program. I have run it in 3-4 compilers and it works perfect. Mind you, you should not enter a number more than 2147483647 (which is the largest number a variable can process in C!). If you do, no problem, but it will display all numbers above it, including the even numbers to be prime. So here you are:

#include

#include

main()

{

long int a,b,c;

printf("Enter the number: ");

scanf("%ld",&a);

for (b=2;b

{

c= a%b;

if (c==0)

goto cool;

}

printf("\nThe number is goddamned prime!");

goto fool;

cool: printf("\nThis ain't a prime number you dumbo!");

fool: printf("\n");

}

By the way I am not sure what your query really was. I gave the above program to check whether a number is prime or not. If you mean to generate prime numbers between 2 (which is of course the first prime number) and a given number g and also want to know the number of prime numbers between the two, well here is it:

#include

#include

main()

{

long int a=2,i=2,c,count=0,g;

printf("Prime numbers upto what number should be generated? ");

scanf("%ld",&g);

printf("\nFollowing is the list of prime numbers:\n");

while (a<=g)

{

for (i=2;i

{

c=(a%i);

if (c==0)

goto cool;

else

continue;

}

printf("\n%ld",a);

++count;

cool: ++a;

}

printf("\nTotal number of prime numbers between 2 and %ld is %ld. ",g,count);

}

For both these programs, simply copy-paste them into your compiler and have your result. Hope you got what you wanted...

What is the meaning of System.out.print in java?

System.out.print is a standard output function used in java. where System specifies the package name , out specifies the class name and print is a function in that class. This function is different from the System.out.println() since it does not place a new line after printing the variable. System.out.println("hello"); // prints hello System.out.print("hello"); //also prints hello but if you then

System.out.println("how are you"); //it continues from the last print resulting in

// hellohow are you This also calls the default toString() method of the variable you put as the parameter.

Note: not all Classes have a helpful toString() method, i.e. arrays do not have toString(), thus a nasty memory address is printed.

What is string tokenizer?

A tokeniser splits a string into a number of smaller strings, called tokens.

For instance, a tokeniser might accept "one two three" and produce one, two, and three, discarding the intervening whitespace characters. Another might turn "(2+3)*foo" into (, 2, +, 3, ), *, and foo, splitting according to more complex rules.