Trending November 2023 # Constructor, Methods And Examples Of Java Printwriter # Suggested December 2023 # Top 11 Popular

You are reading the article Constructor, Methods And Examples Of Java Printwriter updated in November 2023 on the website Minhminhbmm.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested December 2023 Constructor, Methods And Examples Of Java Printwriter

Introduction to Java PrintWriter

The java PrintWriter class is used to print objects in the formatted representation to the text output stream. The PrintWriter class is a built-in class in java that defines the java.io.PrintWriter package. The Writer class is a superclass of the PrintWriter. The PrintWriter class enables to write the formatted object to the underlying Writer class, for example, to write int, double, long and other primitive object or data as in the text, not in the values of the bytes. The PrintWriter class implements all the print method as the PrintStream except the methods which write the raw bytes. As the PrintWriter class intended to write the text, it is useful to generate reports to mix the numbers and text.

Start Your Free Software Development Course

Syntax:

The following is the declaration for chúng tôi PrintWriter class:

public class PrintWriter extends Writer { }

The above is the syntax of the PrintWriter, where it is extended to the Writer class.

Constructors of Java PrintWriter Class

Given below are the constructors mentioned:

PrintWriter(File file): These constructs create the new instance of PrintWriter, with the specified file and which is not automat line flushing.

PrintWriter(File file, String ch): These constructs create the new instance of PrintWriter, with the specified file, charset, and not automatic line flush.

PrintWriter(OutputStream out): These constructs create the new instance of PrintWriter from an existing OutputStream and which is not automat line flush.

PrintWriter(OutputStream out, booleanautoFlush): These constructs create the new instance of PrintWriter from an existing OutputStream.

PrintWriter(String fName): These constructs create the new instance of PrintWriter with the specified file name and which is not automat line flush.

PrintWriter(String fileName, String csn): These constructs create the new instance of PrintWriter with the specified file name and charset, and it is not automat line flush.

PrintWriter(Writer out): These constructs create the new instance of PrintWriter, which is not an automat line flush.

PrintWriter(Writer out, booleanautoFlush): These constructs create the new instance of PrintWriter.

Methods of Java PrintWriter Class

Given below are the methods:

public void print( Object obj): This method prints an object.

public void println(boolean x): This method prints the boolean value.

public void println(char[] x): This method prints an array of characters.

public void println(int x): This method prints an integer. Similar methods to prints for all different primitive objects.

public PrintWriterappend(char ch): This method appends the pass character to the writer.

public PrintWriterappend(CharSequencechseq): This method appends the specified character sequence to the writer.

public PrintWriterappend(CharSequencech, int start, int end): This method appends a subsequence of pass character to the writer.

public booleancheckError(): This method checks its error state and flushes the stream.

public protected void clearError(): This method clears an internal error state of the stream.

public protected void setError(): This method indicates that an error occurs.

public PrintWriterformat(String format, Object..args): This method writes the formatted string to this writer with the passed format string and arguments.

public void flush(): This method flushes the stream.

public void close(): This method closes the stream.

Examples of Java PrintWriter

Given below are the examples mentioned:

Example #1

Here we create a PrintWriter object by using the PrintWriter class constructor and pass the file name to write in it.

package p1; import java.io.File; import java.io.PrintWriter; public class Demo { public static void main( String[] arg) { try { PrintWriter pw =null; pw = new PrintWriter(new File("D:\data.txt")); pw.write("This ia an example text for PrintWriter."+"n"); pw.write("This ia an example number for PrintWriter :" +(int)563+ "."); pw.flush(); pw.close(); System.out.println("Print writer done. you can open the file."); }catch(Exception e) { System.out.println(e); } } }

Output:

When we open the file, we can see the content of the file as below:

As in the above code, the file “data.txt” is opened to write some data with the help of PrintWriter class and its constructor.

Example #2

Code:

package p1; import java.io.File; import java.io.PrintWriter; import java.util.Locale; public class Demo { public static void main( String[] arg) { String str="Hello"; String str2=" World"; char ch='H'; try { PrintWriter pw =null; pw = new PrintWriter(System.out); pw.print("print(inti) : "+ 123); pw.println(); pw.print("print(float f) : " +34.65f); pw.println(); pw.print("print(boolean b) : " +true); pw.println(); pw.print("print(char ch) : "+ch); pw.println(); pw.print("print(String s) : "+str); pw.println(); pw.print("print(Object Obj) : " +pw); pw.println(); pw.print("append(CharSequencecsq) : "); pw.append(str); pw.append(str2); pw.println(); pw.println("checkError() : " +pw.checkError()); pw.print("format() : "); pw.format(Locale.CHINA, " This is an china formatted example for %s text.",str); pw.flush(); pw.close(); }catch(Exception e) { System.out.println(e); } } }

Output:

As in the above code, writing some of the data we can see in the output to the out console (System.out) with PrintWriter class constructor and methods.

Conclusion

The PrintWriter class is a built-in class in java that is defined in the java.io.PrintWriter package, and it is used to print an object in the formatted representation to the text output stream. The PrintWriter class is the subclass of the Writer class.

Recommended Articles

This is a guide to Java PrintWriter. Here we discuss the introduction to java PrintWriter, constructors, methods and examples for better understanding. You may also have a look at the following articles to learn more –

You're reading Constructor, Methods And Examples Of Java Printwriter

Learn Constructors And Methods Of Jprogressbar

Introduction to JProgressBar

Web development, programming languages, Software testing & others

Swing API

Progress Monitoring API of the Swing includes a total of three classes that facilitate the use of the progress bars. The subclass of JProgressBar, JComponent is actually considered to be the graphical component that demonstrates the progress of the operation. Additionally, it also can get embedded within the other graphical components.

Constructors of JProgressBar

The constructors of JProgressBar are as under :

JProgressBar(): This constructor is used to create the progress bar without any text on it.

JProgressBar(int orientation): This constructor is used to create the progress bar along with the mentioned orientation in its parameter. In case VERTICAL is mentioned as a parameter then the vertical progress bar gets created and in case SwingConstants.Horizontal is mentioned as a parameter then the horizontal progress bar gets created.

JProgressBar(int min, int max): This constructor is used to create the progress bar along with the mentioned minimum as well as the maximum value.

JProgressBar(int orientation, int min, int max): This constructor is used to create the progress bar along with the mentioned minimum as well as the maximum value and also the specified orientation in the parameter. If SwingConstants.VERTICAL is mentioned as a parameter then the vertical progress bar gets created and in case SwingConstants. HORIZONTAL is mentioned as a parameter then the horizontal progress bar gets created.

Methods of JProgressBar

The methods of JProgressBar are as under :

int getMaximum(): This method is used to return the maximum value of the progress bar.

int getMinimum(): This method is used to return the minimum value of the progress bar.

String getString(): This method is used to return the string representation of the current value of the progress bar.

void setMaximum(int t): This method is used to set the maximum value of the progress bar to the value of t.

void setMinimum(int t): This method is used to set the minimum value of the progress bar to the value of t.

void setValue(int t): This method is used to set the current value of the progress bar to the value of t.

void setString(String t): This method is used to set the value of the progress String to that of t which is a String.

Below is mentioned the syntax for the javax.swing.JProgressBar class.

Syntax:

public class JProgressBar extends JComponent implements SwingConstants, Accessible Examples of  JProgress

Here are some examples of JProgressBar which are given below with implementation:

Example #1 -Horizontal Progress Bar import java.awt.*; import javax.swing.*; public class Progress { public static void main(String[] args) { final int max = 100; final JFrame frame = new JFrame("JProgress Demo"); final JProgressBar jp = new JProgressBar(); jp.setMinimum(0); jp.setMaximum(max); jp.setStringPainted(true); frame.setLayout(new FlowLayout()); frame.getContentPane().add(jp); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200,200); frame.setVisible(true); for (int i = 0; i <= max; i++) { final int presentValue = i; try { SwingUtilities.invokeLater(new Runnable() { public void run() { jp.setValue(presentValue); } }); java.lang.Thread.sleep(100); } catch (InterruptedException e) { JOptionPane.showMessageDialog(frame, e.getMessage()); } } } }

Output:

`

Example #2 – Vertical Progress bar

Code:

import java.awt.*; import javax.swing.*; import java.awt.event.*; public class progress extends JFrame { static JFrame frame; static JProgressBar bar; public static void main(String[] args) { frame = new JFrame("ProgresBar demo"); JPanel panel = new JPanel(); bar = new JProgressBar(SwingConstants.VERTICAL); bar.setValue(0); bar.setStringPainted(true); panel.add(bar); frame.add(panel); frame.setSize(500, 500); frame.setVisible(true); fill(); } public static void fill() { int j = 0; try { while (j <= 100) { bar.setValue(j + 10); Thread.sleep(1000); j += 20; } } catch (Exception e) { } } }

Output:

Example #3 –  Progress bar with string

Code:

import java.awt.*; import javax.swing.*; public class Jprogress extends JFrame { static JFrame frame; static JProgressBar bar; public static void main(String[] args) { frame = new JFrame("ProgressBar demo"); JPanel panel = new JPanel(); bar = new JProgressBar(); bar.setValue(0); bar.setStringPainted(true); panel.add(bar); frame.add(panel); frame.setSize(500, 500); frame.setVisible(true); fill(); } public static void fill() { int j = 0; try { while (j <= 100) { bar.setString("wait for few soconds"); bar.setString("almost done loading"); else bar.setString("loading initiated"); bar.setValue(j + 10); Thread.sleep(3000); j += 20; } } catch (Exception e) { } } }

Output:

Conclusion

 Thus we can conclude that the progress bar is the key UI element that is needed majorly so as to give feedback to the desired user. The user often doesn’t interact along with the progress bar. The JProgress bar is usually shown whenever the application gets busy, and also it is an indication to the user that the application is performing the task, and it is not frozen.

Recommended Articles

This is a guide to JProgressBar example. Here we discuss the constructors, methods of JProgressBar along with the examples and code implementation. You may also look at the following articles to learn more –

How Java @Inherited Work With Examples To Implement

Introduction to Java @Inherited

The @inherited in Java is an annotation used to mark an annotation to be inherited to subclasses of the annotated class. The @inherited is a built-in annotation, as we know that annotations are like a tag that represents metadata which gives the additional information to the compiler. Same as built-in annotation, which is exits in the Javadoc, it is possible to create another meta-annotation out of existing in the java. There are actually two types of annotations, one type of annotations applied to the java code like @override, and another type of annotations applied to the other annotation like @target @inherited. So @inherited is an annotation that is applied to other annotation whose we want to create subclasses or we want to inherit to make another user define annotation.

Start Your Free Software Development Course

Syntax

The syntax of the @inherited in java is –

@Inherited public @interface MyAnnotation {// code of the MyAnnotation } @MyAnnotation public class SuperClass { public class SubClass extends SuperClass {

As in the above syntax, the class SubClass is inherited from the annotation @MyAnnotation, because it is inherited from SuperClass, and SuperClass has a @MyAnnotation annotation.

How does @Inherited work in Java?

The @Inherited annotation is used or annotated to the annotation (MyAnnotation as in above syntax), which the @interface should prefix. Next, this annotation (MyAnnotation) can be used where ever need to apply as @MyAnnotation. These annotations can be applied just before the declaration of an element and can be applied to any element of the program like variables, class, constructors, methods, etc. When this user-defined annotation is annotated on the superclass, it is automatically inherited to subclasses (subclass as in the above syntax), as we can see in the below examples.

Examples to Implement @Inherited annotation in Java

Next, we write the java code to understand the @Inherited annotation more clearly with the following example where we use @Inherited annotation to inherit in the subclass from the superclass, as below –

Example #1

First, we create an interface for annotation @MyAnnotation, which has two fields, name and code.

Code: chúng tôi

package demo; import java.lang.annotation.Inherited; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Inherited @Target ({ElementType.TYPE, ElementType.METHOD}) @Retention (RetentionPolicy.RUNTIME) public @interface MyAnnotation { String name () default "unknown"; String code () default " "; }

Next, we create a superclass to use the above annotation by annotating any class or method or variable and provide the state name and state code.

Code: package demo; import demo.MyAnnotation; @MyAnnotation (name = "Karnataka", code = "KA") public class Super { public String getstateinfo () { return null; } }

Next, we use an annotation because it is metadata, which means we should be able to get this metadata or information to use the annotation information when we need it.

Code: chúng tôi

package demo; import demo.MyAnnotation; import demo.Super; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; public class Demo extends Super { public static void main ( String[] arg ) throws Exception { new Super (); getstateinfo (obj); Method m = obj.getMethod ("getstateinfo", new Class[]{}); getstateinfo (m); } static void getstateinfo (AnnotatedElement e) { try { System.out.println ("Finding annotations on " + e.getClass ().getName ()); Annotation[] annotations = e.getAnnotations (); for (Annotation a : annotations) { if (a instanceof MyAnnotation) { MyAnnotation stateInfo = (MyAnnotation) a; System.out.println("Name of Annotation :" + stateInfo.annotationType ()); System.out.println("State Name :" + chúng tôi ()); System.out.println("State code :" + chúng tôi ()); System.out.println(new Demo ().getClass ().getAnnotation (MyAnnotation.class)); System.out.println(new Super ().getClass ().getAnnotation (MyAnnotation.class)); } } } catch (Exception ex) { System.out.println( ex ); } } }

Output: When we run the chúng tôi class, the output is.

Explanation: As in the above code, the MyAnnotation annotation is created an also annotated by @Inherited. In the Superclass, the MyAnnotation annotation was using by the statement @MyAnnotation and annotated to the class. And another class Demo is created, which is the subclass of the Superclass because it is extended to Superclass. Farther in the main () method of the Demo class, an object of the Superclass is creating and access its method that is getstateinfo (), through this methoditerating all its annotations and checking whether the annotation is inatnce of MyAnnotation, if yes then printing some of the information as we can see above. But one important thing is that the Demo class or any of its elements not annotated to the MyAnnotation, but it still showing that the MyAnnotation is annotated to this class because it is inherent to the Superclass and Superclass is inherited MyAnnotation.

Next, we rewrite the above java code to understand the @Inherited annotation more clearly with the following example where we will not use @Inherited annotation to annotation MyAnnotation (as annotation created in the above example) to check whether this annotation is inherited in the subclass from its superclass or not, as below –

Example #2

Code: chúng tôi

package demo; import java.lang.annotation.Inherited; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target ({ElementType.TYPE, ElementType.METHOD}) @Retention (RetentionPolicy.RUNTIME) public @interface MyAnnotation { String name () default "unknown"; String code () default " "; }

Output: Next, when we run the chúng tôi class, the output is.

Explanation: As in the above output, we can see that after state code, the “null” value is printed, that is the return value of the statement “new  Demo ().getClass ().getAnnotation (MyAnnotation.class)”, which means that the demo class is not inherited (or annotated) any MyAnnotation annotation from it Superclass, because the @Inherited annotation is not annotated to MyAnnotation to inherit it in the subclass.

Conclusion

The @inherited in java is a built-in annotation applied to another annotation. It is used to marks an annotation to be inherited to subclasses of the annotated class. The @inherited is available in the package java.lang.annotation.Inherited.

Recommended Articles

This is a guide to Java @Inherited. Here we discuss an introduction to Java @Inherited along with the working, appropriate syntax and respective examples to implement. You can also go through our other related articles to learn more –

Working And Examples Of React Render

Introduction to React Render

The following articles provide an outline for React Render. In React, Rendering is one of the most important processes used for making the browser to understand the components used. It is used to transform the react components in the Document Object Model (DOM) nodes which help the browser to understand and display the components on the screen. Elements manipulation is quite faster than manipulating DOM. React creates a Virtual DOM which looks the same as a DOM. Now, it allows us to make changes in the running application. React batches all of the changes made in the virtual DOM and compares it to the original DOM, and then it updates whatever has been changed.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax of React Render

ReactDOM.render()

ReactDOM.render(element, document.getElementById(‘root’));

Working of React Render

React elements are rendered into a DOM node by using ReactDOM.render. When we call for the first time to reactDOM.render(element, domnode). The contents of the DOM Node are replaced by the Element’s content. Now, if we call the render statement again, it updates the content of the DOM node by the new content from the element.

Examples of React Render

Different examples are mentioned below:

Example #1 – Basic Render in Timer

In the example below, we have used Render using a simple statement ReactDOM.render. The example below focuses on showing the time according to IST (Indian Standard Time).

chúng tôi

import React from "react"; import ReactDOM from "react-dom"; function tick() { const element = ( ); ReactDOM.render(element, document.getElementById("root")); } setInterval(tick, 1000);

Output:

Example #2 – Render used in List Rendering

In the example below, we have used render before return to import data from the database link in the chúng tôi file. And in chúng tôi we have imported render from react-dom.

chúng tôi

import React , { Component } from "react"; import axios from "axios"; export default class App extends Component { constructor() { super(); console.log("Constructor"); this.state = { title: "Heyoo! Welcome to Our Database", users: [] }; } callBeforeRender() { console.log( "Called after render 🙁 "); } async loadData() { console.log("Load data"); let { data } = await axios.get( ); this.setState({ users: data }); this.callBeforeRender(); } componentDidMount() { console.log("Did mount"); this.loadData(); }, 2000); } componentWillUpdate() { console.log("Will update"); }); } render() { console.log("Render"); return ( })} ); } }

chúng tôi

import React from "react"; import { render } from "react-dom"; import Main from "./App"; );

Output:

Example #3 – Counter using Render

In the example below, a simple counter with an increment of 1 is implemented, and in our chúng tôi file, render is used through ReactDOM.render.

import React from "react"; import ReactDOM from "react-dom"; function Logger(props) { console.log(`${props.label} rendered`); return null; } function Counter(props) { const [count, setCount] = React.useState(0); return ( {props.logger} ); } ReactDOM.render( document.getElementById("root") );

Output:

Example #4 – Auto Rendering in React

In the example below, render is imported through ‘react-dom’ and used to return the values. The timer automatically increases and tells the time spent by you on the page.

chúng tôi

import React , { Component } from 'react' import { render , createPortal } from 'react-dom' class Foo extends Component { componentDidMount () { this.props.shareState({ foo: 'You have spent time in seconds notified above' }) } render () { return ( Heyoo! {this.props.append} ({this.props.count}) ) } } const target = document.body.appendChild( document.createElement('div') ) const className = `.js-component-${name}` const targets = document.querySelectorAll(className) return [ ...reduced, target )) ] }, []) class App extends Component { constructor (props) { super(props) this.state = { theme: 'cyan', count: 0 } } componentDidMount () { count: count + 1 })) }, 1000) } render () { return ( <Components theme={this.state.theme} count={this.state.count} shareState={this.setState.bind(this)} sharedState={this.state} components={{ foo: Foo }} ) } }

Output:

Example #5 – Implementing 2 Patterns using Renders in React

In the example below, we have 2 props patterns, i.e Counter and List, and are combined in an application using Render through ReactDOM.render in chúng tôi file.

Counter.js and chúng tôi are the files used to implement the counter, and chúng tôi and chúng tôi are the files used to implement the list. Finally, the styling is taken care of using the chúng tôi file.

import React from "react"; import CounterWrapper from "./CounterWrapper"; return ( {({ increment , decrement )} ); }; export { Counter as default };

chúng tôi

import React from "react"; class CounterWrapper extends React.Component { state = { count: 0 }; const { count } = this.state; return this.setState({ count: count + 1 }); }; const { count } = this.state; return this.setState({ count: count - 1 }); }; render() { const { count } = this.state; return ( {this.props.children({ increment: this.increment, decrement: this.decrement, count: count })} ); } } export { CounterWrapper as default };

chúng tôi

import React from "react"; import ListWrapper from "./ListWrapper"; return ( {({ list , isLoading {isLoading ? ( ) : ( ))} )} )} ); }; export { List as default };

chúng tôi

import React from "react"; import axios from "axios"; class ListWrapper extends React.Component { state = { isLoading: true, error: null, list: [] }; fetchData() { axios .get(this.props.link) this.setState({ list: response.data, isLoading: false }); }) .catch( { error , isLoading: false } ) ); } componentDidMount() { this.setState({ isLoading: true }, this.fetchData); } render() { const { children } = this.props; const ui = typeof children === "function" ? children(this.state) : children; } } export { ListWrapper as default };

chúng tôi

import React from "react"; import ReactDOM from "react-dom"; import "./styles.css"; import Counter from "./Counter"; import List from "./List"; class App extends React.Component { render() { return ( ); } } const rootElement = document.getElementById("root");

chúng tôi

.App { font-family: 'Times New Roman' , Times , serif; text-align: center; }

Output:

Conclusion

Based on the above article, we have explained about React Render and its working. We have demonstrated multiple examples to understand how rendering can be used to transform the components into DOM nodes in different situations and requirements of the application.

Recommended Articles

This is a guide to React Render. Here we discuss the introduction, syntax, and working of React Render along with examples and code implementation. You may also have a look at the following articles to learn more –

Syntax And Examples Of Sql Ceiling

Introduction to SQL Ceiling

SQL Ceiling function is the mathematical function available in SQL that is used for the numeric type of values. These numeric values can be either integers or floating-point numbers. If the numeric value is formatted inside the string type of value as parameter then that value is also allowed for Ceiling function. In short, any value or expression that can be deduced to the numeric value can be used as a parameter to the Ceiling() mathematical function in SQL. This function helps us retrieve the minimum integer value that is greater or equivalent to the passed value.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

In this article, we will learn about how Ceiling function can be used to retrieve the integral value not less than the passed numeric value or expression, its syntax, and some of the examples that can help to make the implementation of the Ceiling() function easy and understandable.

The below is the syntax for the mathematical Ceiling() function in SQL –

Ceiling(expressionOrNumber);

expressionOrNumber: expressionOrNumber can be any integer or floating-point value or even a decimal value. In case if this numeric value is wrapped into strings then these string values are also acceptable. Other than the direct specification of numeric value any expression that will ultimately deduce to a numeric value is also allowed as a parameter to the Ceiling() function.

Return value: The return value of the Ceiling() function is the smallest integer value that is greater than or equal to the value that is passed as the parameter to the function. The type of the return value is dependent on the data type of the value that is passed as the parameter to the Ceiling() function. In case if the parameter is or integer data type then the return value is also of integer type. While in other cases if the deduced value of the parameter of the direct specification of the value of the parameter is of floating-point type then the datatype of the return value is of the floating-point data type itself.

Examples of SQL Ceiling

Following are the examples are given below:

1. Using Ceiling() function with Positive Values

We will consider the positive numeric value say 3.59 and then use the Ceiling function to retrieve the smallest integer value that is greater than or equivalent to the 3.59 value. Let us execute the following SQL query statement and observe the output –

SELECT Ceiling(3.59);

Output:

Let us consider one more example of positive value. But in this example, we will use an expression that will evaluate to the value that is of numeric type. Simply consider the expression 5 * 1.65 whose actual value is 8.25 and use this expression in Ceiling() function to retrieve minimum integral value greater than passed value using following query statement –

SELECT Ceiling(5 * 1.65);

Output:

Now, we will consider a positive number wrapped as a string and use it as a parameter to Ceiling() function. For example, consider “56.569” value that is used in the following manner –

SELECT Ceiling(56.569);

Output:

2. Using Ceiling() Function with Negative Values

We will consider the negative numeric value say -65.55 and then use the Ceiling function to retrieve the smallest integer value that is greater than or equivalent to the -65.55 value. Let us execute the following SQL query statement and observe the output –

SELECT Ceiling(-65.55);

Output:

Let us consider one more example of a negative value. But in this example, we will use an expression that will evaluate to the value that is of numeric type. Simply consider the expression 8 * -91.65 whose actual value is −733.2 and use this expression in Ceiling() function to retrieve minimum integral value greater than passed value using following query statement –

SELECT Ceiling(8 * -91.65);

Output:

Now, we will consider a negative number wrapped as a string and use it as a parameter to Ceiling() function. For example, consider “-98.154″value that is used in the following manner –

SELECT Ceiling(-98.154);

Output:

3. Using Ceiling() Function with Values in The Table

Let us now see how we can use the Ceiling() function in the query statements on the values of the columns of the table. We will create one table named workers using following query statement –

CREATE TABLE `workers` ( `developer_id` int(11) NOT NULL AUTO_INCREMENT, `team_id` int(11) NOT NULL, `name` varchar(100) DEFAULT NULL, `position` varchar(100) DEFAULT NULL, `technology` varchar(100) DEFAULT NULL, `salary` int(11) DEFAULT NULL, PRIMARY KEY (`developer_id`), UNIQUE KEY `name` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;

Output:

INSERT INTO `workers` VALUES (1,1,'Payal','Developer','Angular',30000), (2,1,'Heena','Developer','Angular',10000), (3,3,'Vishnu','Manager','Maven',25000), (4,3,'Rahul','Support','Digital Marketing',15000), (5,3,'Siddhesh','Tester','Maven',20000), (6,7,'Siddharth','Manager','Java',25000), (7,4,'Brahma','Developer','Digital Marketing',30000), (8,1,'Arjun','Tester','Angular',19000), (9,2,'Nitin','Developer','SQL',20000), (10,2,'Ramesh','Administrator','SQL',30000), (11,2,'Rohan','Admin',NULL,20000), (12,2,'Raj','Designer',NULL,30000);

Output:

Now we will calculate the average salary using the following query statement –

SELECT avg(salary) from workers;

Output:

If we want to retrieve the average salary in integer format with the greatest value that is greater than or equivalent to the average value using Ceiling() function using the following query statement –

SELECT Ceiling (avg(salary)) from workers;

Output:

Conclusion

Mathematical function Ceiling() is used rounding numeric values in SQL. We can retrieve the minimum value in integer format that is greater or equivalent to the passed numeric number or expression whose results can be either floating value of an integer or decimal value. The working of Ceiling() function is exactly different than Floor() function. Though both of them are used for rounding. Ceiling() funtion rounds up while Floor() function rounds down the numeric value.

Recommended Articles

We hope that this EDUCBA information on “SQL Ceiling” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Find Mean And Median Of An Unsorted Array In Java

In Java, Array is an object. It is a non-primitive data type which stores values of similar data type.

As per the problem statement we have to find mean and median of an unsorted array in Java.

Mean of an array can be derived by calculating the average value of all the elements present inside the array.

Mean= (sum of all elements present in array) / (total number of elements present)

Median of an array represents the middle element present in an odd number sorted array and if the sorted array consists of even number, then median can be found out by calculating the average of middle two numbers.

Let’s explore the article to see how it can be done by using Java programming language.

To show you some instances Instance-1

Given Array= [12, 23, 34, 45, 15].

Mean value of that array= (12 + 23 + 34 + 45 + 15) / (5) = 129 / 5 = 25.8

Sorted array of given array= [12, 15, 24, 34, 45]

As this is an odd numbered array the median is the middle element.

Median = 24

Instance-2

Given Array= [38, 94, 86, 63, 36].

Mean value of that array= (38 + 94 + 86 + 63 + 36) / (5) = 317 / 5 = 63.4

Sorted array of given array= [36, 38, 63, 86, 94]

As this is an odd numbered array the median is the middle element.

Median = 63

Instance-3

Given Array= [54, 67, 23, 95, 24, 60].

Mean value of that array= (54 + 67 + 23 + 95 + 24 + 60) / (6) = 323 / 6 = 53.83

As this is an even numbered array the median is the average value of middle two elements.

Sorted array of given array= [23, 24, 54, 60, 67, 95]

Median = (54 + 60) / 2 = 57

Algorithm

Step 1 − Declare and initialize an array of integer type.

Step 2 − Sort the array in ascending order.

Step 3 − In first user- defined method we find mean value. And in second user- defined method we find the median value.

Step 4 − Call both user-defined method and pass the array and the length value as parameters.

Step 5 − After finding the mean and median values print both the values as output.

Syntax

To get the length of an array (number of elements in that array), there is an inbuilt property of array i.e length

Below refers to the syntax of it −

array.length

where, ‘array’ refers to the array reference.

You can use Arrays.sort() method to sort the array in ascending order.

Arrays.sort(array_name); Multiple Approaches

We have provided the solution in different approaches

By Using Static Input Method

By Using User Input Method

Let’s see the program along with its output one by one.

Approach-1: By Using Static Input Method

In this approach, we declare an array by static input method and pass this array and its length as parameter in our user defined method, then inside the method by using the algorithm we can find the mean and median values.

Example import java.util.*; public class Main { public static void main(String args[]) { int inputArray[] = { 23, 24, 65, 87, 85, 12, 76,21}; int len = inputArray.length; System.out.println("Mean of given array "+ Arrays.toString(inputArray)+ " is = " + mean(inputArray, len)); System.out.println("Median of given array "+ Arrays.toString(inputArray) + " is = " + median(inputArray, len)); } public static double mean(int arr[], int len) { int sum = 0; for (int i = 0; i < len; i++) sum += arr[i]; return (double)(arr[(len - 1) / 2] + arr[len / 2]) / 2.0; } public static double median(int arr[], int len) { Arrays.sort(arr); if (len % 2 != 0) { return (double)arr[len / 2]; } return (double)(arr[(len - 1) / 2] + arr[len / 2]) / 2.0; } } Output Mean of given array [23, 24, 65, 87, 85, 12, 76, 21] is = 49.125 Median of given array [23, 24, 65, 87, 85, 12, 76, 21] is = 44.5 Approach-2: By Using User Input Method

In this approach, we declare an array by user input method and pass this array and its length as parameter in our user defined method, then inside the method by using the algorithm we can find the mean and median values.

Example import java.util.*; public class Main { public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.print("Enter the number of elements: "); int len=sc.nextInt(); int[] inputArray = new int[len]; System.out.println("Enter the elements: "); for(int i=0; i < len; i++) { inputArray[i]=sc.nextInt(); } System.out.println("Mean of given array "+ Arrays.toString(inputArray) + " is = " + mean(inputArray, len)); System.out.println("Median of given array "+ Arrays.toString(inputArray) + " is = " + median(inputArray, len)); } public static double mean(int arr[], int len) { int sum = 0; for (int i = 0; i < len; i++) sum += arr[i]; return (double)sum / (double)len; } public static double median(int arr[], int len) { Arrays.sort(arr); if (len % 2 != 0){ return (double)arr[len / 2]; } System.out.println(arr[(len - 1)]); System.out.println(arr[(len - 1)]); return (double)(arr[(len - 1) / 2] + arr[len / 2]) / 2.0; } } Output Enter the number of elements: 8 Enter the elements: 2 5 3 7 1 6 8 4 Mean of given array [2, 5, 3, 7, 1, 6, 8, 4] is = 4.5 Median of given array [2, 5, 3, 7, 1, 6, 8, 4] is = 4.5

In this article, we explored how to find mean and median of an array in an unsorted array by using Java programming language.

Update the detailed information about Constructor, Methods And Examples Of Java Printwriter on the Minhminhbmm.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!