Beginner: Static Methods - java

I am asked to "Write a static method which, given a String as an input parameter, will return another String representing the input string with all vowels removed."
I'm not exactly sure what they mean by this. I wrote this below. What would I need to change to the answer? Thanks
public static void main(String[] args) {
String s = "Hello there";
String s1 = s.replaceAll("[AaEeIiOoUu]", "");
System.out.print(s1);
}

Check answers from #NicksTyagi and others for the static method. However, I wanted to point out that you can optimize your regex like this: (?i)[aeiouy].
(?i) is an inline flag that indicates that the part of the regex that follows it, is case insensitive. By using this flag it's not necessary to put the letters in upper case.
Feel free to remove the y from the regex if it isn't considered as a vowel in your language.
Sample code
public static String removeVowels(String input) {
return input.replaceAll("(?i)[aeiouy]", "");
}

The static method you copied and pasted into your question is called main. It's kind of special, it takes a string[] as an argument, and it always returns void. In order to complete your assignment, you need to write another static method.
First, you need to give it a name.
static myFunction() {
}
Next, give it a return (output) type. Your assignment was to return a String.
static String myfunction() {
}
Then, you need to let it accept a parameter (input) of type String.
static String myFunction(String input) {
}
Almost last, we'll add in the logic to transform the input into an output.
static String myFunction(String input) {
input = input.replaceAll("[AaEeIiOoUu]", "");
}
Finally, we need to return the output.
static String myFunction(String input) {
String output = input.replaceAll("[AaEeIiOoUu]", "");
return output;
}
Viola. You are done! You won't need to know much more about the static keyword until you study object-oriented programming. The correct definition is that static methods are bound to a class, while non-static methods are bound to an instance of a class. Here is a gruesome example.
A static method could accept a Person and return a Person with all of its arms chopped off.
I am a person. I could use my very own non-static method to remove all of my arms.
Hope that helps you remember!

The class must be as below :
public class Demo {
public static String replaceVowel(String input)
{
input = input.replaceAll("[AaEeIiOoUu]", "");
return input;
}
public static void main(String[] args) {
String output = Demo.replaceVowel("Hello World");
System.out.println(output);
}
}

You just need to create another method with the static keyword. Call this method from main.
public static void main(Strings args[]){
removeVowels("Hello World");
}
public static String removeVowels(String textWithVowels){
return textWithVowels.replaceAll("[AaEeIiOoUu]", "");
}

Related

How to print string method, idk how to phrase this sorry

package com.example.test1;
import java.util.Scanner;
public class class1{
public static String methodOne(String name){
String studentName = name + " is his name";
return (studentName);
}
public static void main(String[] args) {
methodOne("John");
}
}
How can I get this method to print out name + " is his name"? It shows nothing when I run this. I also can't add a System.out.println in the String studentName. I'm new to all of this sorry. EDIT: I want to somehow input the print function into the method and not type out System.out.println to print out methodOne, is it possible?
package com.example.test1;
import java.util.Scanner;
public class class1{
public static String methodOne(String name){
String studentName = name + " is his name";
return (studentName);
}
public static void main(String[] args) {
System.out.println(methodOne("John")); // Print string in this console
}
}
The function of returns a value that is string, so when you call her like that :
methodOne("John");
You didn't use the string value, you didn't say print it or anything.
You can use the returned value like this:
package com.example.test1;
import java.util.Scanner;
public class class1{
public static String methodOne(String name){
String studentName = name + " is his name";
return (studentName);
}
public static void main(String[] args) {
String nameStudent = methodOne("John"); // Saves the returned value in a variable
System.out.println(nameStudent ); // Prints the returned value stored in the variable
}
}
You can also print straight without storing a variable, as they say here already.
I want to somehow input the print function into the method.
There are two ways I could interpret it.
You could just mean that you want print within the methodOne method. That is easy:
public static String methodOne(String name){
String studentName = name + " is his name";
System.out.println(studentName);
return studentName;
}
Comments:
If you are going to do it this way, there isn't an obvious reason why methodOne needs to return anything. You could declare it as a void method.
Doing this is probably bad design. Generally speaking, a method should do one thing. (The design principle is Separation of Concerns (SoC).) But this modified method is doing two things. It is forming the string, and it is printing it. And since it is printing it to a specific place (standard output), it's utility is limited. (What if I wanted to create that string without printing it? What if I wanted to print it to a different stream?)
The second interpretation is that you literally want to pass the println method to the methodOne method ... so that it can call it. This is how you could do it:
public static String methodOne(String name,
java.util.function.Consumer<String> fn){
String studentName = name + " is his name";
fn(studentName);
return studentName;
}
and call it like this
methodOne("Fred", System.out::println);

StringUtils Overload chop method

I want to overload the chop method of StringUtils to remove the last character if it is a backslash(\).
Is it possible to overload the function or I need to use an if condition?
Why not this instead?
StringUtils.removeEnd(s,"\\")
yes, use an if statement. You can't override a static method and it would be too much anyway to create it's own class just for that.
I have an alternative that I personally like:
public static String chopIf(Predicate<String> p, String s) {
if (p.test(s)) {
return s.substring(0, s.length()-1); //or StringUtils.chop(s)
}
return s;
}
public static void main(String[] args) {
String test = "qwert\\";
System.out.println(chopIf(s -> s.endsWith("\\"), test));
}
Something like that. Then you can use it for any character. Tweak it according to need.

How can I get a string passed from main function to another function back again to main after processing the string? [duplicate]

This question already has answers here:
What does "void" mean as the return type of a method? [duplicate]
(5 answers)
Closed 5 years ago.
I have done a simple code to reverse a string in Java without using the inbuilt functions. But I have observed that unlike C where we can get a changed string back in the same variable using pointers, which it is not possible in Java due to the absence of pointer concept. So please show me what alternative way can I get back the string in the main function in Java.
class RevFun{
public void revFun(StringBuilder str)
{
for(int i=str.length()-1;i>=0;i--)
{
System.out.println(str.charAt(i));//Here I am able to print it!
}
return;
}
}
class Rev
{
public static void main(String args[])
{
RevFun rev = new RevFun();
StringBuilder str = new StringBuilder("Hello");
System.out.println("Before reversing : "+str);
rev.revFun(str);
System.out.println("After reversing : "+str);//Here what should I do to get the reversed string from RevFun
}
}
give the second method returntype String
public static String handleString(String input){
// modify input
input += " test";
return input;
}
and either use, or assign the (new) value in your main:
public static void main(String[] args){
String a = "hello";
String b = handleString(a);
System.out.println(a);
System.out.println(b);
}
another way is to have your variable on class level:
static String test = "hi";
public static void main(String[] args){
System.out.println(test);
handleString();
System.out.println(test);
}
public static void handleString(){
test += " and bye";
}
both methods have access to the variable, so you won't even need to pass it as a parameter.
In Java Strings are immutable. This means that you can't change them. You can read more here
So if you want to "manipulate" an String you will have to return a new object

How do i get a string to get an integer that is inside a method

I have created an example class for my problem below.
public class testClass {
public void testMethod()
{
int testInteger = 5;
}
String testString = "Hello World" + testInteger;
}
I have an integer inside a method and a string that is in no method as seen above. I want the string to get the integer that inside the method but it cannot. Can someone please help explain why that is so and tell me how to make the string the integer. thanks.
For example:
public class testClass {
public int testMethod()
{
int testInteger = 5;
return testInteger;
}
String testString = "Hello World" + testMethod();
}
The integer is a variable inside the method; it has scope of the method which means it can't be accessed from outside the method. The String is a field; it has scope of the class, so it can be accessed from anywhere inside the class including inside the method.
It's basic Java... the testInteger is defined in the method so not available out of the method. You could let the method return an int (being your testInteger) and call that method.
You cannot access a local variable from another method without returning it.
public int testMethod()
{
int testInteger = 5;
return testInteger;
}
Then you can get the value by calling the method (assuming you have an instance of your class in a reference instance),
String testString = "Hello World" + instance.testMethod();
From The Java Tutorials: Variables,
Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
Lets break down your code to see what is going on
you have such a function
public void testMethod()
{
int testInteger = 5;
}
as you see the return type is void so nothing will be return to anywhere that is called this method.
you have this line after your testMethod
String testString = "Hello World" + testInteger;
first it looks odd why?
because you do not have any main method so I do not know how your code runs
but Imagine you have main method like this
public static void main(String[] args){
String testString = "Hello World" + testInteger;
}
second, you did not even call your testMethod in order to utilize it inside your main method
Issues
1. you did not call your testMethod at all
2. Even if you called it, it would not help you because your return type is void
3. you need main method in order your code to be ran
Remedies
1. change your return type to int
your function signature:
public int testMethod()
2. if you want to use your method, you have to use it in your main method like
for example:
String testString = "Hello World" + testMethod();
3. do not forget to have your main method because it is necessary for your code to be ran
your main method signature is
public static void main(String[] args)

Can "main" in java return a String?

Is it possible that public static void main(String[] args) in java returns String instead of void? If yes, how?
public static String main(String[] args)
instead of:
public static void main(String[] args)
when I change my code as below:
public static String main(String[] args) throws IOException {
String str = null;
TurkishMorphParser parser = TurkishMorphParser.createWithDefaults();
str = new Stm(parser).parse("bizler");
System.out.println("str = " + str);
String replace = str.replace("[","");
String replace1 = replace.replace("]","");
List<String> result1 = new ArrayList<String>(Arrays.asList(replace1.split(",")));
String result = result1.get(0);
System.out.println("Result = " + result);
return result;
}
I receive this error:
Error: Main method must return a value of type void in class Stm, please define the main method as:
public static void main(String[] args)
In short - no, it can't.
You can always print to stdout from the main method (using System.out.print or System.out.println), but you can't change the return type of main.
The main method's return type must be void, because the java language specification enforces it. See 12.1.4.
For interprocess communication you can either use:
System.in and System.out
Sockets
No you can't... once the main is finished the program is dead.. So you don't have any benefit from that.. What is you purpose? What you are trying to achieve?
You can wrap all in other method that will return String to your main.
public static void main(String[] args) throws IOException {
String result = doSomething();
return result;
}
public static String doSomething() {
String str = null;
TurkishMorphParser parser = TurkishMorphParser.createWithDefaults();
str = new Stm(parser).parse("bizler");
System.out.println("str = " + str);
String replace = str.replace("[","");
String replace1 = replace.replace("]","");
List<String> result1 = new ArrayList<String>(Arrays.asList(replace1.split(",")));
String result = result1.get(0);
System.out.println("Result = " + result);
}
Yes you can but you can't run that class. You will get error
class Test {
public static String main(String[] args) {
return "1";
}
}
You will get error as
Error: Main method must return a value of type void in class Test, please
define the main method as:
public static void main(String[] args)
No. The to be a main() method, it must return nothing (ie be void).
However, you could refactor your code if you need the functionality of your method returning something:
public static void main(String[] args) throws IOException {
myMain(args);
}
public static String myMain(String[] args) throws IOException {
// your method, which can now be called from anywhere in your code
}
This is a very interesting scenario. While in general, we can change any method which is returning void to return anything else without much impact, main method is a special case.
In earlier programming languages, the return from main method was supposed to return exit values to the OS or calling environment.
But in case of Java (where multi-threading concept case into picture), returning a value from main method would not be right, as the main method returns to JVM instead of OS. JVM then finishes other threads e.g. deamon threads (if any) and performs other exit tasks before exit to OS.
Hence allowing main method to return, would have lead to a false expectation with the developers. hence it is not allowed.
Yes, it's definitely possible. That is, you can define a method public static String main(String[] args). It's just like defining any other method.
However, it won't be a main method despite its name, and thus won't be run when executing a program like a main method would. Quoting Java language specification, §12.14:
The method main must be declared public, static, and void.
Emphasis mine. You can't have non-void main methods in Java.
If you really, really need it to return something (which you don't), assign the output to a static variable. Then you won't need to return. i.e
static String a = "";
public static void main(String[] args){
//do sth
a = "whatever you want";
}
Now you have String a, use it whereever you want to use but I don't see any usage for this.
Answer is no.
When the program is run, the JVM looks for a method named main() which takes an array of Strings as input and returns nothing (i.e. the return type is void). But if it doesn't find such a method ( the main() method is returning String for example ) so it throws a java.lang.NoSuchMethodError
Before java, in C or C++, main function could be declared int or void. Why? Because main method is invoked by OS which is not responsible for the successful/unsuccessful execution of program. So, to let the OS know that the program executed successfully we provide a return value.
Now, in java, program is loaded by OS, but the execution is done by JRE. JRE itself is responsible for the successful execution of program. So, no need to change the return type.
It will be like telling your problems to god, when god himself is giving you problems to solve them.
;)

Categories