Test your Java skills – Series IV

Java Coding Skills

Java Coding Skills – Test your knowledge

Въвеждане: This is another Java tips series. We have mainly focused on the coding and implementation part. We have discussed different common Java implementations with coding examples. You can test it directly by creating your own Java code. Hope this will help you understand the basic things in core Java.







How to convert an infix expression to postfix expression?

A: Following example demonstrates how to convert an infix to postfix expression by using the concept of stack. Here push (), pop () and peek () methods are used to perform the task. And the Stack class is used to hold the expressions.

внос java.io.IOException;

public class InToPost {

private Stack theStack;

private String input;

private String output = “”;

public InToPost(String in) {

input = in;

int stackSize = input.length();

theStack = new Stack(stackSize);

}

public String doTrans() {

за (INT J = 0; J < input.length(); J ) {

char ch = input.charAt(J);

switch (ch) {

case ‘ ’:

case ‘-‘:

gotOper(ch, 1);

break;

case ‘*’:

case ‘/’:

gotOper(ch, 2);

break;

case ‘(&#8216;:

theStack.push(ch);

break;

case ‘)’:

gotParen(ch);

break;

default:

output = output + ch;

break;

}

}

докато (!theStack.isEmpty()) {

output = output + theStack.pop();

}

System.out.println(output);

return output;

}

public void gotOper(char opThis, int prec1) {

докато (!theStack.isEmpty()) {

char opTop = theStack.pop();

ако (opTop == ‘(&#8216;) {

theStack.push(opTop);

break;

}

още {

int prec2;

ако (opTop == ‘ ’ || opTop == ‘-‘)

prec2 = 1;

още

prec2 = 2;

ако (prec2 < prec1)

{

theStack.push(opTop);

break;

} още

output = output + opTop;

}

}

theStack.push(opThis);

}

public void gotParen(char ch){

докато (!theStack.isEmpty()) {

char chx = theStack.pop();

ако (chx == ‘(&#8216;)

break;

още

output = output + chx;

}

}

публично статично невалидни основни(Низ[] опцията) хвърля IOException {

String input = “1+2*4/5-7+3/6”;

String output;

InToPost theTrans = new InToPost(input);

output = theTrans.doTrans();

System.out.println(“Postfix is ” + output + ‘n’);

}

class Stack {

private int maxSize;

private char[] stackArray;

private int top;

public Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

top = -1;

}

public void push(char j) {

stackArray[++top] = j;

}

public char pop() {

return stackArray[top–];

}

public char peek() {

return stackArray[top];

}

public boolean isEmpty() {

return (top == -1);

}

}

}

The above code sample will produce the following result.

124*5/+7-36/+

Postfix is 124*5/+7-36/+

How to implement Queue?

A: Following example shows how to implement a queue in an employee structure. Linked list is an implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface.The LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue.

import java.util.LinkedList;

class GenQueue {

private LinkedList list = new LinkedList();

public void enqueue(E item) {

list.addLast(вещ);

}

public E dequeue() {

return list.poll();

}

public boolean hasItems() {

return !list.isEmpty();

}

public int size() {

return list.size();

}

public void addItems(GenQueue q) {

докато (q.hasItems())

list.addLast(q.dequeue());

}

}

public class GenQueueTest {

публично статично невалидни основни(Низ[] опцията) {

GenQueue empList;

empList = new GenQueue();

GenQueue hList;

hList = new GenQueue();

hList.enqueue(new HourlyEmployee(“T”, “D”));

hList.enqueue(new HourlyEmployee(“G”, “B”));

hList.enqueue(new HourlyEmployee(“F”, “S”));

empList.addItems(hList);

System.out.println(“The employees’ names are:”);

докато (empList.hasItems()) {

Employee emp = empList.dequeue();

System.out.println(emp.firstName + ” ” + emp.lastName);

}

}

}

class Employee {

` public String lastName;

public String firstName;

обществен служител() {

}

обществен служител(String last, String first) {

this.lastName = last;

this.firstName = first;

}

public String toString() {

return firstName + ” ” + lastName;

}

}

class HourlyEmployee extends Employee {

public double hourlyRate;

public HourlyEmployee(String last, String first) {

супер(last, first);

}

}

The above code sample will produce the following result.

The employees’ names are:

T D

G B

F S

How to reverse a string using stack?

A: Following example shows how to reverse a string using stack with the help of user defined method StringReverserThroughStack ().A simple Stack in Java, implemented as an object-oriented, recursive data structure, a singly linked list. Note that Java already provides a Stack class

внос java.io.IOException;

public class StringReverserThroughStack {

private String input;

private String output;

public StringReverserThroughStack(String in) {

input = in;

}

public String doRev() {

int stackSize = input.length();

Stack theStack = new Stack(stackSize);

за (Int I = 0; аз < input.length(); I ) {

char ch = input.charAt(аз);

theStack.push(ch);

}

output = “”;

докато (!theStack.isEmpty()) {

char ch = theStack.pop();

output = output + ch;

}

return output;

}

публично статично невалидни основни(Низ[] опцията) хвърля IOException {

String input = “Java Source and Support”;

String output;

StringReverserThroughStack theReverser =

new StringReverserThroughStack(input);

output = theReverser.doRev();

System.out.println(“Reversed: ” + output);

}

class Stack {

private int maxSize;

private char[] stackArray;

private int top;

public Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

top = -1;

}

public void push(char j) {

stackArray[++top] = j;

}

public char pop() {

return stackArray[top–];

}

public char peek() {

return stackArray[top];

}

public boolean isEmpty() {

return (top == -1);

}

 

}

}

The above code sample will produce the following result.

JavaStringReversal

Reversed:lasreveRgnirtSavaJ







How to check whether antialiasing is enabled or not?

A: Following example demonstrates how to check if antialiasing is turned on or not using RenderingHints Class. Aliasing occurs when a signal (in this case, a 2D graphics signal) is sampled and quantized from a continuous space into a discretized space. Sampling is the process of reading a value from a continuously varying signal. Quantization is the process by which these continuous sampled values are assigned a discrete value in the finite space represented by digital (binary-based) systems.

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import javax.swing.JComponent;

внос javax.swing.JFrame;

обществени клас Main {

публично статично невалидни основни(Низ[] опцията) {

JFrame frame = new JFrame();

frame.add(new MyComponent());

frame.setSize(300, 300);

frame.setVisible(вярно);

}

}

class MyComponent extends JComponent {

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

RenderingHints rh = g2d.getRenderingHints();

boolean bl = rh.containsValue

(RenderingHints.VALUE_ANTIALIAS_ON);

System.out.println(bl);

g2.setRenderingHint(RenderingHints.

KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

}

}

The above code sample will produce the following result.

False

False

False

How to display colors in a frame?

A: Following example displays how to a display all the colors in a frame using setRGB method of image class. The abstract class Image is the superclass of all classes that represent graphical images. The image must be obtained in a platform-specific manner.

import java.awt.Graphics;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.awt.image.BufferedImage;

import javax.swing.JComponent;

внос javax.swing.JFrame;

public class Main extends JComponent {

BufferedImage image;

public void initialize() {

int width = getSize().width;

int height = getSize().height;

Int[] data = new int[width * height];

int index = 0;

за (Int I = 0; аз < height; I ) {

int red = (аз * 255) / (height – 1);

за (INT J = 0; J < width; J ) {

int green = (J * 255) / (width – 1);

int blue = 128;

data[index ] = (red < < 16) | (green < < 8) | blue;

}

}

image = new BufferedImage

(width, height, BufferedImage.TYPE_INT_RGB);

image.setRGB(0, 0, width, height, data, 0, width);

}

public void paint(Graphics g) {

ако (image == null)

initialize();

g.drawImage(image, 0, 0, this);

}

публично статично невалидни основни(Низ[] опцията) {

JFrame f = new JFrame(“Display Colours”);

f.getContentPane().добави(new Main());

f.setSize(300, 300);

f.setLocation(100, 100);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

f.setVisible(вярно);

}

}

The above code sample will produce the following result.

Displays all the colours in a frame.








What is threading in java?

A: A Java program can contain many threads, all of which may be created without the explicit knowledge of the developer. For now, all you need to consider is that when you write a Java application, there is an initial thread that begins its operation by executing the main() method of your application. When you write a Java applet, there is a thread that is executing the callback methods (init(), actionPerformed(), etc.) of your applet; we speak of this thread as the applet’s thread. In either case, your program starts with what you can consider as a single thread. If you want to perform I/O (particularly if the I/O might block), start a timer, or do any other task in parallel with the initial thread, you must start a new thread to perform that task.

How to display text in different fonts?

A: Following example demonstrates how to display text in different fonts using setFont () method of Font class. The Font class represents fonts, which are used to render text in a visible way. A font provides the information needed to map sequences of characters to sequences of glyphs and to render sequences of glyphs on Graphics and Component objects.

внос java.awt. *;

import java.awt.event.*

внасят javax.swing. *

public class Main extends JPanel {

Низ[] тип = { “Serif”,”SansSerif”};

Int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD,

Font.ITALIC + Font.BOLD };

Низ[] stylenames =

{ “Plain”, “Italic”, “Bold”, “Bold & Italic” };

public void paint(Graphics g) {

за (int f = 0; F < type.length; f ) {

за (int s = 0; s < styles.length; s ) {

Font font = new Font(type[F], styles[s], 18);

g.setFont(font);

String name = type[F] + ” ” + stylenames[s];

g.drawString(име, 20, (F * 4 + s + 1) * 20);

}

}

}

публично статично невалидни основни(Низ[] на) {

JFrame f = new JFrame();

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

}

);

f.setContentPane(new Main());

f.setSize(400,400);

f.setVisible(вярно);

}

}

The above code sample will produce the following result.

Different font names are displayed in a frame.

How to draw a line using GUI?

A: Following example demonstrates how to draw a line using draw() method of Graphics2D class with Line2D object as an argument. The setPaint () method of the Graphics2D class has been used to paint the line. Here java applet is used to display the line on a JFrame.

внос java.awt. *;

import java.awt.event.*;

import java.awt.geom.Line2D;

import javax.swing.JApplet;

внос javax.swing.JFrame;

public class Main extends JApplet {

public void init() {

setBackground(Color.white);

setForeground(Color.white);

}

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setPaint(Color.gray);

int x = 5;

int y = 7;

g2.draw(new Line2D.Double(x, y, 200, 200));

g2.drawString(“Line”, x, 250);

}

публично статично невалидни основни(String s[]) {

JFrame f = new JFrame(“Line”);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

JApplet applet = new Main();

f.getContentPane().добави(“Center”, applet);

applet.init();

f.pack();

f.setSize(ново измерение(300, 300));

f.setVisible(вярно);

}

}

The above code sample will produce the following result.

Line is displayed in a frame.

How to display a message in a new frame?

A: Following example demonstrates how to display message in a new frame by creating a frame using JFrame() & using JFrames getContentPanel(), setSize() & setVisible() methods to display this on the frame. Here Graphics2D and Rectangle2D classes have been ued to make the initial component. And then the message is displayed on a JPanel component.

внос java.awt. *;

import java.awt.font.FontRenderContext;

размер java.awt.geom.Rectangle2D;

внос javax.swing.JFrame;

import javax.swing.JPanel;

public class Main extends JPanel {

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setFont(new Font(“Serif”, Font.PLAIN, 48));

paintHorizontallyCenteredText(g2, “Java Source”, 200, 75);

paintHorizontallyCenteredText(g2, “и”, 200, 125);

paintHorizontallyCenteredText(g2, “Support”, 200, 175);

}

protected void paintHorizontallyCenteredText(Graphics2D g2,

String s, float centerX, float baselineY) {

FontRenderContext frc = g2.getFontRenderContext();

Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);

float width = (float) bounds.getWidth();

g2.drawString(s, centerX – width / 2, baselineY);

}

публично статично невалидни основни(Низ[] опцията) {

JFrame f = new JFrame();

f.getContentPane().добави(new Main());

f.setSize(450, 350);

f.setVisible(вярно);

}

}

The above code sample will produce the following result.

JAVA and J2EE displayed in a new Frame.







How to display a pie chart using a frame?

A: Following example displays how to a display a piechart by making Slices class & creating arc depending on the slices. In this example AWT and swing components are used to draw the chart. Arguments are passed to the drawPie () method from the main () метод. And the completed chart is displayed on a JFrame.

внос java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import javax.swing.JComponent;

внос javax.swing.JFrame;

class Slice {

double value;

Color color;

public Slice(double value, Color color) {

this.value = value;

this.color = color;

}

}

class MyComponent extends JComponent {

Slice[] slices = { new Slice(5, Color.black),

new Slice(33, Color.green),

new Slice(20, Color.yellow), new Slice(15, Color.red) };

MyComponent() {}

public void paint(Graphics g) {

drawPie((Graphics2D) g, getBounds(), slices);

}

void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {

double total = 0.0D;

за (Int I = 0; аз < slices.length; I ) {

total = slices[аз].стойност;

}

double curValue = 0.0D;

int startAngle = 0;

за (Int I = 0; аз < slices.length; I ) {

startAngle = (Int) (curValue * 360 / обща сума);

int arcAngle = (Int) (slices[аз].стойност * 360 / обща сума);

g.setColor(slices[аз].color);

g.fillArc(area.x, area.y, area.width, area.height,

startAngle, arcAngle);

curValue = slices[аз].стойност;

}

}

}

обществени клас Main {

публично статично невалидни основни(Низ[] argv) {

JFrame frame = new JFrame();

frame.getContentPane().добави(new MyComponent());

frame.setSize(300, 200);

frame.setVisible(вярно);

}

}

The above code sample will produce the following result.

Displays a piechart on a frame.

 

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share