Why I can't printout value from main method? [duplicate] - java

This question already has answers here:
Calling Non-Static Method In Static Method In Java [duplicate]
(14 answers)
Closed 2 years ago.
//I'd like to now why I can;t printout the return value in below java code
public class client08 {
public static void main(String[] args) {
String w=test();
System.out.println(w);**// I'd like to print out the return value here but it now work**
}
public String test() {
String result="";
String[] words=new String[5];
words[0]="Amy";
words[2]="Tom";
words[4]="Jane";
for(int i=0; i<words.length;i++) {
if(words[i]!=null) {
result=words[i].toUpperCase();
}else {
result="null";
}
}
return result;
}

First of all class names should start with an upper case character. Learn and follow Java conventions.
Next:
Your code doesn't compile.
You can't invoke a method from your "client08" class unless you create an instance of the class or make the method static.
So the code should be:
//String w=test();
client08 client = new client08();
String w= client.test();
Or you need to make the method static:
public static String test() {
Then you would invoke the method using:
String w = client08.test();
System.out.println(w);

Related

JAVA - non-static method add(E) cannot be referenced from a static context [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 3 years ago.
I am trying to insert String values (using a Scanner) into an ArrayList.
I am getting the error:
non-static method add(E) cannot be referenced from a static context.
I assume the add() method is the problem - what other methods can I use to insert into an ArrayList that is static?
import java.util.*;
public class Solution {
private static List<String> strings;
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 5; i++){
String s = scanner.nextLine();
List.add(s);
}
}
}
You try to add a string to List interface (add() method is not static) but should add it to your instance List<String> strings:
strings.add(s);
Also, you should initialize strings
private static List<String> strings = new ArrayList<>();
otherwise, you will get NullPointerException.

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

Storing reference to object [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I would like to store reference to variable in some class, and make operations on it inside this class. Operations should modify original variable.
In particular following code should print 1 instead of 0.
class Test {
private Long metric;
public Test(Long m) {
this.metric = m;
++this.metric;
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Long metric = 0L;
Test test = new Test(metric);
System.out.println(metric);
}
}
How to achieve this behaviour?
You can replace Long with AtomicLong which is mutable. You'll lose autoboxing features though.
The problem in your code is that Integer is an immutable class.
Every time that you change the value you are really building a new instance of Integer.
Doing the same with mutable objects will work.
For example
class Test {
private StringBuilder metric;
public Test(StringBuilder m) {
this.metric = m;
this.metric.append(" Xter");
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
StringBuilder b = new StringBuilder("Hello ");
Test test = new Test(metric);
System.out.println(b.toString());
// Will print Hello Xter
}
}
As already metioned, the primitive wrapper classes are inmutable.
Since your metric is private in Test, and you want to use its value in the calling method main, you should use the java bean guidelines and use a getter for it:
public Long getMetric(){return this.metric;}
And on main:
metric=test.getMetric();
System.out.println(metric);

Java - public class constructor [duplicate]

This question already has answers here:
Java Constructors
(10 answers)
Closed 6 years ago.
I need explain on class.
What is constructor and how write it and what is public namecllase(){
Here all the variable
}
How this is call?
Thank you
Ok simple example
You make one class that name is : Demo
class Demo{
}
Inner you make a constructer, that is what you call if you need it... look below
class Demo{
public Demo(int num, String str)
{
int num;
String str = "This is a parameterized constructor with number ";
System.out.println(str + num);
}
}
You can make more of them for example an empty constructer or with a defined value
Now you can call your class with that constructer something like that :
public static void main(String args[]){
String strrrrr = "This is your value of variable int"
int i = 99;
Demo demo = new Demo(strrrrr, i);
}
So you can see that you console gives you message with your variable String strrrrr and int i
I hope I could help you ;)

StringBuffer method parameter - doesn't change value [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I know that String is immutable and it's value can't be changed, but why does the value of the below StringBuffer doesn't change when sent like a method parameter. From my understanding it should have changed with the new value "bb". Thank you for your help.
class Ideone {
public static void main (String[] args) {
String s = "aa";
StringBuffer sb = new StringBuffer("aa");
modify(s, "bb");
modify2(sb, "bb");
System.out.println(s);
System.out.println(sb);
}
public static void modify(String s, String ss) {
s = ss;
}
public static void modify2(StringBuffer sb, String ss) {
sb = new StringBuffer(ss);
}
}
The universal rule in Java is that you cannot change the reference of an object passed into a method, but you can change its contents.
public static void modify2(StringBuffer sb, String ss){
This method takes a copy of a reference to a StringBuffer. Changing that reference to point to an object has no effect whatsoever on the original object. But if you implemented it as
sb.clear();
sb.append(ss);
then it would work.
Again, the rule is that reassigning an object passed into a method with = does nothing to the original object, but you can change the contents of that object just fine.

Categories