• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Pro Programming

Professional way of Programming: Learn C, C++, Java, Python, Dot Net, Android the professional way

  • Home
  • C MCQs
  • C/C++ Programs
  • Java Programs
  • C#
  • Python
  • MySQL
  • Topics
    • Arrays
    • Strings
    • Link Lists
    • Trees
    • Shapes
  • Projects
  • Articles
  • Games
You are here: Home / Archives for Java

Java

Java ArrayList to String Array Example

Leave a Comment


/*

Java ArrayList to String Array Example

This Java ArrayList to String Array example shows how to convert ArrayList to String array

in Java.

*/

import java.util.ArrayList;

import java.util.Arrays;

public class ArrayListToStringArrayExample {

public static void main(String args[]){

//ArrayList containing string objects

ArrayList<String> aListDays = new ArrayList<String>();

aListDays.add(“Sunday”);

aListDays.add(“Monday”);

aListDays.add(“Tuesday”);

/*

* To convert ArrayList containing String elements to String array, use

* Object[] toArray() method of ArrayList class.

*

* Please note that toArray method returns Object array, not String array.

*/

//First Step: convert ArrayList to an Object array.

Object[] objDays = aListDays.toArray();

//Second Step: convert Object array to String array

String[] strDays = Arrays.copyOf(objDays, objDays.length, String[].class);

System.out.println(“ArrayList converted to String array”);

//print elements of String array

for(int i=0; i < strDays.length; i++){

System.out.println(strDays[i]);

}

}

}

/*

Output of above given ArrayList to String Array example would be

ArrayList converted to String array

Sunday

Monday

Tuesday

*/

Filed Under: Java

Java String Array to String Example

Leave a Comment


/*

Java String Array to String Example

This Java String Array to String Length example shows how to convert String array to

Java String object.

*/

import java.util.Arrays;

public class StringArrayToStringExample {

public static void main(String args[]){

//String array

String[] strArray =

new String[]{“Java”, “String”, “Array”, “To”, “String”, “Example”};

/*

* There are several in which we can convert String array to

* String.

*/

/*

* 1. Using Arrays.toString method

* This method returns string like [element1, element2..]

*/

String str1 = Arrays.toString(strArray);

//replace starting “[” and ending “]” and “,”

str1 = str1.substring(1, str1.length()-1).replaceAll(“,”, “”);

System.out.println(“String 1: “ + str1);

/*

* 2. Using Arrays.asList method followed by toString.

* This method also returns string like [element1, element2..]

*/

String str2 = Arrays.asList(strArray).toString();

//replace starting “[” and ending “]” and “,”

str2 = str2.substring(1, str2.length()-1).replaceAll(“,”, “”);

System.out.println(“String 2: “ + str2);

/*

* PLEASE NOTE that if the any of the array elements contain “,”, it will be

* replaced too. So above both methods does not work 100%.

*/

//3. Using StringBuffer.append method

StringBuffer sbf = new StringBuffer();

if(strArray.length > 0){

sbf.append(strArray[0]);

for(int i=1; i < strArray.length; i++){

sbf.append(” “).append(strArray[i]);

}

}

System.out.println(“String 3: “ + sbf.toString());

}

}

/*

Output of above example would be

String 1: Java String Array To String Example

String 2: Java String Array To String Example

String 3:Java String Array To String Example

*/

Filed Under: Java

14. Two-way data binding with v-model

Leave a Comment


Finally, the day has come, to understand the missing piece of the puzzle, data binding. So far, we have seen how to use interpolations, v-bind for attribute binding and v-on to listen to events. The missing piece was v-model which is used for two-way data binding and this is exactly what we will be concentrating on today!

Big word alert!

Two-way data binding: This is just a relation between the model (data object in the Vue instance) and the view. Any change made in the view (say, by the user) will immediately be reflected in the underlying Vue model and will be updated at all places where this data is being rendered in the view. In other words,

  1. View is updated with the change made to the data property (model)
  2. And, the data property (model) is updated whenever a change is made in the view

Is your head spinning yet? No worries! We will understand this concept by walking through an example.

v-model directive

This two-way binding is usually created with form inputs and controls. And v-model is the directive used to achieve just that! To be more specific, below are the exact HTML elements with which v-model is used,

  • <input>
  • <textarea>
  • <select>
  • Components (we will be covering this topic in the “Advanced VueJS” section)

Example walkthrough

Let us take an example with <input> element to show a text field on the webpage. Let us also have a “message” property in the Vue instance’s data object which acts as our Vue model and a <p> tag to render the value using mustache syntax (text interpolation). Now, we want to,

  1. Populate the text field with the message property’s value, say, “hi” i.e., updating the view with the model.
  2. Whenever the value, “hi” is changed by the user in the text field, it has to be updated in the data property, message in our case i.e., updating the model with changes in view and
  3. Also rendering it in the <p> tag simultaneously

All these three steps can be done by adding the v-model directive to the <input> tag and binding the “message” property to it like so,

<input type="text" v-model="data_property_to_bind"></input>

Index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Hello Vue!</title>
    <!-- including Vue with development version CDN -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <h2>Welcome</h2>
      <div>
        <!-- two-way binding with v-model -->
        Greeting Message:
        <input type="text" v-model="message"></input> 
        <p>The message is: {{ message }}</p>
      </div>
    </div>
    <!-- including index.js file -->
    <script src="../index.js"></script>
  </body>
</html>

Index.js

new Vue({
  el: "#app",
  data: {
    message: "hi"
  }
});

So, the v-model directive tells vue.js to set up a two-way binding for the input field and the message data property mentioned within the quotation marks. All this happens reactively of course!

The initial output is as below.

v-model initial output

The right half in the image shows Vue DevTools pane. The data object with the message property and its value can also be seen.

As we change the message in the text field from “hi” to “hello”, with every character that we type, it will reactively get updated in the underlying data model (shown in the Vue Devtools) and updated in the view where we output using mustache syntax in the <p> tag.

reactivity with v-model

I highly recommend you to open Vue Devtools as shown in the image and change the value in the text field to see this change happening reactively. It will be a feast to your eyes! I can assure that.

Modifiers

v-model comes with three modifiers. In case you missed the modifiers part, check this out.

Usage: Following the v-model directive, add a dot and specify the modifier.

  • .lazy– sync the input with the data after change events instead of input events
<input v-model.lazy="message">
  • .number– used to cast valid input string to numbers
<input v-model.number="age">
  • .trim– to trim the user input automatically
<input v-model.trim="message">

The code is available in the GitHub repo as always.

Play around with that and notice how Vue correctly updates the element based on whether the input type is a text field, checkbox, radio button, select, multi-select, text area element and so on… It looks and sounds magical because all the syntax sugar you need to achieve this elephant-sized task is a single directive, v-model. Feel free to give a shout out in the comments section in case you bump into any issues.

Have a great day ahead!

SERIES NAVIGATION

<< 13. Let’s use shorthands

WRITTEN BY

Chandana Chaitanya

Chandana Chaitanya

Lakshmi Chandana is a Software professional + passion-fueled blogger + novel-reader + artist + tutor to make your day a little brighter than it was before! She is thrilled you are here!
She is on a mission to make sure learning sticks but with the fun part kept intact. She uses certain tricks called BrainBells (inspired from barbells and dumbbells used for workout) to achieve this and she says, “this is not the hardest job! As once minions said, it for sure is working in a bubble wrap factory. Imagine the self-control needed!”
So, dive in to explore the fun-filled World of Learning!!


Filed Under: Java

Java String Array Contains Example

Leave a Comment


/*

Java String Array Contains Example

This Java String Array Contains example shows how to find a String in

String array in Java.

*/

import java.util.Arrays;

public class StringArrayContainsExample {

public static void main(String args[]){

//String array

String[] strMonths = new String[]{“January”, “February”, “March”, “April”, “May”};

//Strings to find

String strFind1 = “March”;

String strFind2 = “December”;

/*

* There are several ways we can check whether a String array

* contains a particular string.

*

* First of them is iterating the array elements and check as given below.

*/

boolean contains = false;

//iterate the String array

for(int i=0; i < strMonths.length; i++){

//check if string array contains the string

if(strMonths[i].equals(strFind1)){

//string found

contains = true;

break;

}

}

if(contains){

System.out.println(“String array contains String “ + strFind1);

}else{

System.out.println(“String array does not contain String “ + strFind1);

}

/*

* Second way to check whether String array contains a string is to use

* Arrays class as given below.

*/

contains = Arrays.asList(strMonths).contains(strFind1);

System.out.println(“Does String array contain “ + strFind1 + “? “ + contains);

contains = Arrays.asList(strMonths).contains(strFind2);

System.out.println(“Does String array contain “ + strFind2 + “? “ + contains);

}

}

/*

Output of above given Java String Array Contains example would be

String array contains String March

Does String array contain March? true

Does String array contain December? false

*/

Filed Under: Java

Cryptocurrency is a digital currency

Leave a Comment


Cryptocurrency can be described as a digital currency in which encryption techniques are used to regulate generation of units of currency and verify the transfer of funds, operating independently of a central bank. They are a type of digital ,alternative and virtual currencies that use decentralized control as opposed to centralized central banking and electronic money. Decentralized cryptocurrencies like the bitcoins provide an outlet for personal wealth beyond confiscation and restriction. In the current world, they have become a global phenomenon and one known to many people. Banks, governments and other companies have become aware of its importance, although to other people it is still a geeky, not well understood concept. With this, many major banks, governments and accounting firms have researched on them and written work on them as well
The first cryptocurrency, the bitcoin, was the first decentralized cryptocurrency, created in 2009 by a developer Satoshi Nakamato. They emerged as a side product of another invention, his goal having being to invent something that many had failed to create before digital money. He said in his announcement of bitcoin, that he had developed “A Peer-to-Peer Electronic Cash System’.
The most important part of his invention was the fact that he found a way of building a decentralized cash system, all the other attempts from various people to create digital money before then having failed. Seeing all the other attempts fail made him try to build a digital money system, which led to the invention of cryptocurrency.
But what really are cryptocurrencies? Simply defined they are limited entries in a database that cannot be changed by anyone without them fulfilling specific conditions. Taking the money on your bank account for instance; it is no more than just entries in a database that are only changed under certain specific conditions. They are basically token explaining entries in decentralized consensus-databases and are called CRYPTOcurrencies since the process of consensus keeping is secured by strong cryptography.
They are made on cryptography and secured mathematically and not by trust or even people. Their properties include, fast and global as their transactions are almost instantly propagated and confirmed within minutes after transacting. They are also irreversible and once a cryptocurrency transaction is made it cannot be reversed. They are also secure in as, only the private key owner can send cryptocurrency since the funds are locked in a public key cryptography system, thus making a bitcoin address very secure and impossible to break the scheme. In addition, they are permissionless since cryptocurrency is just software which can be easily downloaded by anyone for free and upon installation, one can easily send and receive bitcoins and other cryptocurrencies without need to seek consent or permission from anyone. About bitcoins, Being the most famous cryptocurrencies, Bitcoins serve as a digital gold standard in all the cryptocurrency-industry. It is used as means of payment globally, a defacto currency of cyber-crime similar to ransomware and darknet markets. Having existed for seven years, its price value has interestingly increased from null to above 650 dollars and nearly 200,000 transactions per day. The bitcoin is with no doubt here to stay. And how then are Bitcoins mined? It is a process in which transactions are verified and added to a public ledger called a block chain and new bitcoin is released. Anyone can do the mining provided they have internet access and suitable hardware. The mining process involves compiling of recent transactions into blocks and then trying to solve some difficult puzzles. The participant who solves the puzzles first then gets to place the next block on the block chain and claim rewards. The rewards are meant to draw people to keep mining, and are both transaction fees associated with compiled transactions in the block and also newly released bitcoins.
The mining process is expensive, painstaking but also rewarding in some instances. It however has a magnetic draw for many investors interested in the cryptocurrencies. Why then should you mine? Mining enables you to earn cryptocurrency without putting any of your money into it. Crypto can also be obtained through buying using fiat currency, playing video games or even publishing blogs on platforms that use crypto to pay users. Apart from lining miners pockets, mining is also the only way new cryptocurrency can be released into circulation. It is the reason Bitcoin came to be Miners get paid for working as auditors. In their work, they verify previous Bitcoin transactions. This keeps users honest and by verifying transactions, miners also help in prevention of double-spending’ problem which involves illicit spending of same money twice by users.
Cryptocurrencies, owing to their revolutionary properties have become a success that even Satoshi would not have aspired to se. Even with numerous fails at other attempts to create digital cash, Bitcoin had a thing to it that has created fascination and enthusiasm among many. The cryptocurrencies are a digital gold, sound money secure from political influence and one that promises to preserve and appreciate value with time They are also fast and convenient means of payment globally, and a private means that can be used with anonymity when making payments like for black markets and other outlawed economic activities. But even with their increasing use as a mode for payment, its use a means of store of value or speculation dwarfs the payment aspects, as they give rise to a fast growing market for investors and speculators. With Bitcoins still being the most used and most famous cryptocurrency, and other forms having almost zero impact, there is need to be on the look for several other forms like the Ethereum, Ripple, Litecoin and Monero and even many other forms that promise playground for testing innovations in crypto-technology. But even with their advantages to an investor such as stable growth rates, confidence of community, more liquidity of the Bitcoin compared to other cryptocurrency and the high rise in bitcoin exchange in the recent years, there is still need to be on the lookout. With the numerous cryptos existing and even new ones being created every week, there is no doubt that some are scams and Ponzi schemes. The opportunity is immense yes,and the cryptos are not bad therefore this does not mean they shouldn’t be bought. It just means there is too much hype and scammers out there. Also, with their increasing popularity, comes likelihood of more regulation and government scrutiny, eroding the major premise for their existence. And what then is the future for cryptocurrencies? Whereas the number of merchants accepting cryptocurrencies continues to increase, they are still very much in minority. They first have to acquire widespread reception amongst consumers and their relative complexity will deter many apart from for those who are technologically adept.
Cryptocurrencies aspiring to become portion of the conventional financial system will have to satisfy certain criteria, they would require to remain mathematically complex, so as to avoid fraud and hacking, but also easy for users to comprehend; devolved but with enough consumer protection;able to preserve anonymity of users. With criteria to be satisfied, there is possibility, though remote, that in a few years the cryptocurrency most popular could have attributes ranging amid heavily-regulated sanction currencies and today’s cryptocurrencies. Bitcoins success in dealing with its challenges may determine fortune of upcoming cryptocurrencies in coming years.




Filed Under: Java

Java Char Array To String Example

Leave a Comment


/*

Java Char Array To String Example

This Java char array to String example shows how to convert char array to

String in Java.

*/

public class CharArrayToStringExample {

public static void main(String args[]){

//char array

char[] charArray = new char[]{‘J’,‘a’,‘v’,‘a’};

/*

* To convert char array to String in Java, use

* String(Char[] ch) constructor of Java String class.

*/

String str = new String(charArray);

System.out.println(“Char array converted to String: “ + str);

}

}

/*

Output of above given char array to String example would be

Char array converted to String: Java

*/

Filed Under: Java

  • « Previous Page
  • Page 1
  • Page 2
  • Page 3
  • Page 4
  • Page 5
  • …
  • Page 10
  • Next Page »

Primary Sidebar

Recent Posts

  • Engineering Chemistry Questions and Answers – Application of Colloids
  • MongoDB Beginners Tutorial
  • 10 Projects That Every Developer Should Lay Their Hands-On
  • Engineering Chemistry Questions and Answers – Detergents
  • What is Blockchain? How the Blockchain Network Actually Works?
  • Privacy Policy
  • About
  • Contact US

© 2019 ProProgramming
 Privacy Policy About Contact Us