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

Index of an element in array?

An array is a group of related elements, with a common variable name. The index is a number that indicates the position of an element within an array: the 1st. element, the 2nd. element, etc. (many languages start counting at zero).

Why java is known as internet programming language?

too many reasons...it is easy to use, it contains built-in support for using computer networks, it can execute code from remote sources securley, it prevents possible errors and anti-pattern design...but there are many limitations for what java can do.

How threads are synchronized in a java?

By using an Runnable and Thread object.

EX:

Runnable r = new Runnable() {

Thread t = new Thread() {

@Override

public void run() {

//place code for new thread here

}

};

@Override

public void run() {

t.start();

}

};

r.run();

Write a program using one print statement to print the asterisks triangle?

#include<stdio.h>

#include<conio.h>

int main()

{

int i,j,k,row,m;

printf("Enter the no of rows:");

scanf("%d",&row);

m=row;

for(i=0;i<m;i++)

{

printf("\n");

for(k=0;k<row;k++)

printf(" ");

for(j=0;j<=i;j++)

printf(" *");

row--;

}

getch();

}

How do you read from an external file in java?

The class I find useful is the FileReader class in java.io. It allows you to read an external file in your program.

For instance,

Consider a file input.txt:

Hello

How are you?

1 2 3 4 5

You can access it by:

FileReader read = new FileReader("input.txt"); // pass the file name as a String

//now the read is the file

//can scan from the file using Scanner

Scanner scan = new Scanner(read);

System.out.println( scan.nextLine()); // prints Hello

System.out.println( scan.nextLine()); // prints How are you?

while(scan.hasNextInt())

System.out.print(scan.nextInt() + " "); // prints 1 2 3 4 5

What is non primitive data types in Java?

"Primitive" data types are integers (char, int, long), floats (float, double) and void. Void is never used for variables, but tells C that a function accepts and/or returns no arguments.

"Non-primitive" data types include arrays, structs and classes. These utilize primitive data types and are called, in general, structured data types.

Data types can become more complicated as you mix the structured data types. For instance, arrays, structs and classes can contain arrays, structs and classes, nested as deep as you wish.

Depending upon who asks the question, a non-primitive data structure may be just a structured type (array, struct, class), or a structured type containing structured types.

What is similarities between Abstract Class and Interface?

If a class has one abstract method ,the class has to be an abstract class.
Methods can be implemented in abstract class.


Whereas a interface is like a abstract class...the only difference being that the methods are never implemented in Interface.

What is the difference between an algorithm and java code?

In Java programming language, an algorithm refers to a sequence of instructions that have been specified to undertake a particular task within a certain time. An algorithm can take no or several inputs but will generate at least one output.

Where can array length be used in Java programming language?

in java the memory allocation can be dynamic in nature. The java array enables the user to store values of the same type in contiguous memory allocations. Arrays are always a fixed length abstracted data structure which can not be altered when required.

Discuss various types of class used in java?

Tools provided in java includes, 1. Jar: Mostly used tool of java, it creates jar archive file(executable file by javaw/java if you have jre installed in your system, lib files to import your classes and reuse). 2. Jarsigner: This utility signs a jar, and can verify a signed jar. 3. Keytool: Tool to create keystore and certificates. 4. servertool: Java IDL server tool. 5. Policytool: Edit and create policy, keystore is required for the same. 6. Javah: Tool to create header file. 7. appletviewer: Tool to view applets. 8. HtmlConverter: Convert applet to html. Common uses: java, javac, javaw, javadoc, javap (get the class structure) etc

A java program to print natural numbers?

#include<iostream>

unsigned print_naturals (unsigned max)

{

unsigned num = 0;

while (num<max)

std::cout << ++num << ' ';

std::cout << std::endl;

}

int main()

{

// print first 10 natural numbers:

print_naturals (10);

// print first 100 natural numbers:

print_naturals (100);

}

What are three difference between visual basic python and java programming languages?

They are completely different languages. Visual Basic is Microsoft's implentation of BASIC, and is tied to the .NET Framework, or Mono if you plan on porting it to other platforms. Python's syntax is dependent on tabs and/or spaces, and Java would have similar syntax to languages inspired by C (C#, Java, JavaScript, and so on). They both have interpreters, and are cross-platform out-of-the-box.

What class is the super class for ALL Java classes?

The Object class, in the java.lang package, sits at the top of the class hierarchy tree. Every class is a descendant, direct or indirect, of the Object class. Every class you use or write inherits the instance methods of Object. You need not use any of these methods, but, if you choose to do so, you may need to override them with code that is specific to your class

What does it mean that Java is not enabled in your browser?

Basically that is telling you to enable javascript in your browser. Come back with your browser name and someone could tell you how to enable javascript in it.

Why should programmer use object oriented language?

Object oriented programming allows programmers to classify data and methods by type. For instance, a shape is a type of object, a rectangle is a type of shape and a square is a type of rectangle. We can also say that a rectangle is a specialisation of a shape and that a square is a specialisation of a rectangle. Object oriented programming allows us to express relationships between types directly in code such that when we hold a reference to a square, we also hold a reference to a rectangle and a shape. As a result, we can pass a square or rectangle object to a function that knows nothing about squares or rectangles but knows everything about shapes.

All shapes can be drawn. Is it necessary for a function to know precisely how a shape is drawn? Of course not, it is only necessary to know that it can be drawn. Knowing this, the function can simply invoke the shape::draw() method regardless of the actual type of shape.

A rectangle inherits all the properties common to all shapes, thus a rectangle inherits the shape::draw() method. Moreover, a rectangle can specialise this method, overriding any default behaviour with its own specialised implementation in rectangle::draw(). Thus when we pass a rectangle object to a function that only knows about shapes and that function invokes the shape::draw() function, we actually invoke the rectangle::draw() function even though our function knows nothing about rectangles!

By the same token, a square inherits all the properties common to all rectangles, including all properties common to all shapes. Thus square::draw() inherits rectangle::draw() which overrides shape::draw(). However, a square does not actually need to override the draw method because the the implementation that applies to a rectangles also applies to a square. This is because rectangles and squares both have 4 vertices with internal angles of 90 degrees. The only thing that actually differentiates a square from a rectangle is that the adjacent vertices of a square are equidistant, but the actual vertices are defined by the rectangle so the rectangle has all the information required to draw a square. Again, the rectangle object does not need to know anything about squares in order to draw one!

Let's now look at how we can define all of these notions in an object-oriented programming language.

class shape {

public:

virtual void draw() = 0;

virtual ~shape() {}

};

class rectangle : public shape {

public:

rectangle (int top, int left, int width, int height): t {top}, l {left}, w {width}, h {height} {}

void draw() override;

void ~rectangle() override {}

private:

int t, l, w, h;

};

class square : public rectangle final {

public:

square (int top, int left, int size): rectangle {top, left, size, size} {}

};

Although this code is relatively short, it contains a lot of information. This is common in object oriented programming, we can glean a lot of information from very little code. A novice programmer might expect a few user-comments to explain everything in a bit more detail, but to a professional programmer this code tells us every we need to know.

For example, the shape::draw() method is declared a pure-virtual method (a virtual method with no implementation). This immediately tells is the shape class an abstract base class and thus prevents general users from instantiating objects of type shape. This reflects the real world where we can imagine a shape but we cannot draw one (we can only draw a specific type of shape). Being a base class (a class with at least one virtual method), the shape class also has to have a virtual destructor to ensure correct tear-down whenever a shape falls from scope. The shape class has no non-static data members thus we can take advantage of the empty class optimisation. That is, any class that inherits from shape will have zero overhead because there are no data members to inherit.

The rectangle class publicly inherits from shape. This means that all public methods of shape are public methods of rectangle. The rectangle specialises shape with the addition of 4 data members, t, l, w and h (top, left, width and height respectively). The constructor initialises these members at the point of instantiation. We also declare overrides for the inherited interfaces, shape::draw() and shape::~shape(). This is essential otherwise rectangle would also be an abstract base class and we wouldn't be able to instantiate rectangles.

The square class public inherits from rectangle and declares it final. This means we cannot inherit from square, it is not intended to be used as a base class. We automatically inherit both the rectangle::draw() and rectangle::~rectangle() interfaces and we do not need to override these. The only specialisation we need is the constructor which invokes the rectangle constructor to implement the invariant that a rectangle's width and height are always equal for squares. The square has no data members of its own, so there is zero overhead and while we do inherit the data members from rectangle, they are private so we cannot access them.

To complete the implementation, we also need to provide an implementation for the rectangle::draw() method. For this we'll assume that a line() function handles the low-level graphics facility. We do not need to know the implementation details of the line() function, we need only know that the function will draw a line between a pair of coordinates.

void rectangle::draw() {

line (t, l, t, l+w);

line (t, l+w, t+h, l+w);

line (t+h, l+w, t+h, l);

line (t+h, l, t, l);

}

Our definition is complete. We can now use these classes. Let's define a function that accepts a vector of shape pointers and invokes each of their draw methods. We'll use a type alias to reduce code verbosity:

using vec_shapes = std::vector<std::unique_ptr<shape>>;

void draw_shapes (vec_shapes& v) {

for (auto s : v) s->draw();

}

Note that this function only needs to "see" the shape definition. That is, the rectangle and square definitions could be defined in another translation unit entirely. We can even add triangles, circles, pentagons and all manner of other shapes into the mix at a later date and this code will still work without any further modification.

Now let's invoke this function:

void foo() {

vec_shapes v;

v.push_back (new square {10, 10 , 5});

v.push_back (new rectangle {20, 15 , 5, 7});

v.push_back (new square {30, 20 , 4});

v.push_back (new rectangle {40, 25 , 6, 8});

draw_shapes (&v);

}

Note that the vec_shapes alias is itself an object, one that encapsulates a vector of resource handles ("smart" pointers). Although we instantiated four new objects on the heap, we didn't actually delete them as we normally would have had to had they been "naked" pointers. That's because we don't have to delete them. When this function ends, the vector falls from scope and this automatically invokes its destructor which subsequently empties the vector. As each smart pointer within the vector is removed, it falls from scope thus invoking its destructor which explicitly invokes the destructor of the pointer it encapsulates (a pointer to shape). Since that destructor is declared virtual, the most-derived object is destroyed first before working back through the hierarchy, destroying each base class until the shape class itself is finally destroyed.

From this we begin to see the importance of object oriented programming. Resource management details can be fully encapsulated within the objects themselves, thus there is less chance of human error creating resource leaks which is a common problem with C-style coding using "naked" pointers. Objects can also encapsulate class invariants, such that only those methods that modify class member data need maintain those invariants, thus eliminating the need to constantly test those invariants at runtime and thus improving performance. Objects can also implement move semantics so that resources can be efficiently transferred from one object to another thus making it possible to perform (almost) perfect swaps without making any unnecessary temporary copies. This also makes it possible to efficiently return objects from functions by value, the default semantic in both C and C++. Our code becomes easier to write because there's much less of it and much easier to maintain because implementation details are easier to encapsulate.

The multiplication operator is represented in Java by what symbol?

In Java, the multiplication operator is represented by the asterisk, "*". This was not invented by Java; most programming languages, as well as programs such as Excel, use the same symbol.

How multiple inheritance achived in java?

Let me explain with a example.

Suppose consider a method funX() which is in class Z.

Suppose a programmer ABC inherited the class Z to class X and overrided the funX().So this class will have the new implementation of funX().

Suppose a programmer DEF inherited the class Z to class Y and overrided the funX().So this class will have the new implementation of funX().

If Multiple Inheritance is permitted in java, then if the new programmer inherited both the classes and he didn't done any overriding of method funX() then if he calls the funX() ,the JVM will not know which method to call i.e., either the method in class X or method in class Y.

Because of this inconsistencies,Multiple inheritance is not permitted in java.

How do you convert c file to jar file?

1:Downlaod jcreator

2: download jdk

3:make a project class in the src folder only like this

import javax.swing.*;

import java.awt.*;

import java.awt.event.ItemEvent;

import java.awt.event.ItemListener;

public class youclassname extends JFrame implements ItemListener {

String colors[] =

{"White", "Black", "Blue", "Red", "Orange", "Green"};

JComboBox cboColors = new JComboBox(colors);

Container cnt = getContentPane();

youclassname (){

super("What ever you want");

cnt.setLayout (null);

cnt.add(cboColors);

cboColors.addItemListener (this);

cboColors.setBounds(30, 20, 80, 30);

setSize(270, 180);

setVisible(true);

}

public void itemStateChanged(ItemEvent e) {

int intN = -1;

if (e.getStateChange() 5) cnt.setBackground(Color.GREEN);

}

public static void main(String[] agrs) {

nameofyourclass myframe = new nameofyourclass();

myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

4:Go to run then type cmd.

5:a black box should open.

If its in a different drive type the letter of the drive where it is saved plus : no \.

It shold be on that drive type dir to see whats in the drive.

Once you found your project type CD thenameofyourproject.

it should say thename of your drive then the name of your project next to it.

type CD src it should look the same bu with src next to it.

type dir to see what you've made.

5:You will have to make the .class file now.

The way to do that is type javac the name of your src project.java.

If it says some kind of error do this (you must hava jdk installed) type where you downloaded your jdk like this my one was in program files and called jdk i would do this.

C:\ProgramFiles\jdk\bin\javac name of your src .java.

if that dosent work sorry but it always does.

if you've made no errors you should have a .class file.

6:Almost done.

now you must have jdk, type jar cfe what ever you want to name it.jar name of your src class without the.class name of your src class with the class so myne would be like.

(my one was called bc.class)

jar cfe Backroundcolours.jar bc bc.class. hit enter and done if it shows a sort of error do the same thing you did to make the .class.

C:\ProgramFiles\jdk\bin\jar cfe Backroundcolours.jar bc bc.class. hit ener and done.

Thanks for reading.

How do you sort letters in java?

Let us assume by "alphabet letters arrays" you mean you have an array of chars.

char[] letters = //some character array

Arrays.sort(letters);

// Letters is now sorted.

// Note that letters will be sorted according to the ASCII values

// of the chars. This means that all capital letters will be sorted

// before lower case. ('Z' will come before 'a')

What is the default value of char in java?

Since in c language char take 1 byte in memory because it support limited no of character set. But in the whole universe there are very large no of character like japinise language support 126 character set . Java char support all the character set in the world so it take 2 byte in memory.

What are the Difference between primitive data types and wrapper classes?

A primitive type is, in a way, built-in, in the language. This often includes different kinds of numbers, strings, and in some languages, dates and boolean. The other data type, other than primitive, is a compound, or user-defined, data type. For example, some languages allow the programmer to define compound data types, called a "struct" in C, or a "record" in Pascal, where the programmer can define (for example) a data of type point, consisting of x, y, and z coordinates. In object-oriented languages, these user-defined types are often defined as classes.

A primitive type is, in a way, built-in, in the language. This often includes different kinds of numbers, strings, and in some languages, dates and boolean. The other data type, other than primitive, is a compound, or user-defined, data type. For example, some languages allow the programmer to define compound data types, called a "struct" in C, or a "record" in Pascal, where the programmer can define (for example) a data of type point, consisting of x, y, and z coordinates. In object-oriented languages, these user-defined types are often defined as classes.

A primitive type is, in a way, built-in, in the language. This often includes different kinds of numbers, strings, and in some languages, dates and boolean. The other data type, other than primitive, is a compound, or user-defined, data type. For example, some languages allow the programmer to define compound data types, called a "struct" in C, or a "record" in Pascal, where the programmer can define (for example) a data of type point, consisting of x, y, and z coordinates. In object-oriented languages, these user-defined types are often defined as classes.

A primitive type is, in a way, built-in, in the language. This often includes different kinds of numbers, strings, and in some languages, dates and boolean. The other data type, other than primitive, is a compound, or user-defined, data type. For example, some languages allow the programmer to define compound data types, called a "struct" in C, or a "record" in Pascal, where the programmer can define (for example) a data of type point, consisting of x, y, and z coordinates. In object-oriented languages, these user-defined types are often defined as classes.

Why the container is an abstract class in java?

A container is a generic term for an object that can contain other objects. It is not a type of object you can construct, and so therefore it is abstract. Specific instances of containers (such as Windows, Frames, and Panels) all share similar functionality, and so they all inherit from the container class so as to reduce the amount of code that had to be written, and allow each container to accept other containers and components without having to code for each specific container and component directly.

What are topics covered in advanced Java?

Some of the concepts covered in Advanced Java are:

  1. Multithreading
  2. Exception Handling
  3. Remote Method Invocation - RMI
  4. Garbage Collection
  5. etc

Can you instantiate an interface?

According to a beginner's book on Java, an interface can't have constructors. Also, the interface itself can't contain the method implementation.