What does public static void mean? What is a class? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I just accepted that all my programs I made have to start with this. Then I was looking at a example #2 here regarding generation of a random number.
import java.util.Random;
/** Generate random integers in a certain range. */
public final class RandomRange {
public static final void main(String... aArgs){
log("Generating random integers in the range 1..10.");
int START = 1;
int END = 10;
Random random = new Random();
for (int idx = 1; idx <= 10; ++idx){
showRandomInteger(START, END, random);
}
log("Done.");
}
private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
int randomNumber = (int)(fraction + aStart);
log("Generated : " + randomNumber);
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}
I noticed that this had a public static void and a private static void. Why not just combine the code into one thing under public static void? More importantly, what do these mean? I did research and saw the word "class" pop up often. What is a class? I hope my question meets the guidelines, this is my first time posting here. Thanks.

I will assume you asked here because you wanted a concise answer that gives you some intuition, rather than a deep dive into OOP which you can pull from the tutorial.
A class is a template from which objects are built. However, until you understand OOP, the class is just a necessary wrapper around the imperative code you are writing because Java requires all code to live inside a class.
public means the method is publicly accessible. Methods which are defined in classes other than this one can access it. private has the opposite meaning.
static means that this is a class-level function that is not tied to any particular instance of the class.
void means the method returns nothing.
You can certainly put all the code under a single method, but that carries at least the following problems.
Code is harder to read because the intent of the code is hidden by the details of the implementation.
Code is harder to reuse because you have to copy and paste whenever you need the same functionality in multiple places.

The following is not fully correct, it is very simplified:
Mostly one class equals one file. Even so they can access each other (if in the same project/folder) Here are 3 example classes:
Class withe the main method:
package ooexample;
public class OOExample {
public static void main(String[] args) {
int min = 2;
int max = 101;
// use of static method
int randomNumberA = MyMath.generateRandomNumber(min, max);
// use of non static method
RandomNumberGenerator generator = new RandomNumberGenerator();
int randomNumberB = generator.randomNumber(min, max);
/**
* does not work, method is private, can not be accessed from an outise class
* only RandomNumberGenerator can access it
*/
// generator.printSomeNumber(123);
}
}
Class with a static method. The method can be access by writing classname.nameOfStaticMethod(...) see main method.
package ooexample;
public class MyMath {
public static int generateRandomNumber(int min, int max) {
return min + (int) (Math.random() * ((max - min) + 1));
}
}
Class without static method. You have to create the class in the main method, using the new operator and assign the created class to a variable. Then you can use the variable to access PUBLIC methods of that class. You can not access private methods anywhere else but inside of the class itself. See main method.
package ooexample;
public class RandomNumberGenerator {
public RandomNumberGenerator() {
}
public int randomNumber(int min, int max) {
int randomNumber = min + (int) (Math.random() * ((max - min) + 1));
printSomeNumber(randomNumber);
return randomNumber;
}
private void printSomeNumber(int number) {
System.out.println(number);
}
}

Related

How would I test this public static method using Junit? [duplicate]

This question already has answers here:
How to write a Unit Test?
(5 answers)
Closed 4 years ago.
How would I test this public static method using Junit?
I want to test the ResetFactory static method using Junit 4 but I am not sure how to. Any tips? Any help would be appreciated. I have tested the Ticketing constructor and it works perfectly. I had to write the question in a little strange way since it wanted more words for the question.
/**
* Resets the factory.
*/
public static void resetFactory() {
time = 0;
randomNumber = new Random(10);
}
public class Ticketing {
/** Absolute time for passengers created for the simulation. The time starts at zero
* and increases by up to MAX_PASSENGER_GENERATION_DELAY for each passenger created. */
private static int time = 0;
/** Random object with seed that allows for testing of simulation */
private static Random randomNumber = new Random(10);
/** Maximum delay between creation of passengers */
private static final double MAX_GENERATION_DELAY = 15;
/** Percentage of time a Fast Track passenger should be created */
private static double pctExpedite = .50; // initialize with default value
/** Percentage of time a trusted traveler/TSA PreCheck passenger should be created */
private static double pctTrust = .05; // initialize with default value
/**
* Set the proportions of fast track, trusted traveler, and (by inference) ordinary passengers
* that should be generated. Proportion of ordinary passengers is 1 - (pctFast + pctTrusted).
* #param pctTrusted - proportion of passengers that are TrustedTravelers
* #param pctFast - proportion of passengers that are FastTrackPassengers
*/
public static void setDistribution(int pctTrusted, int pctFast) {
pctExpedite = pctFast * .01;
pctTrust = pctTrusted * .01;
}
/**
* Generate a new passenger as described in the class comments.
* #param log - where the passenger will log his/her data
* #return the passenger created
*/
public static Passenger generatePassenger(Reporter log) {
// Update the overall time with up to the floor of MAX_PASSENGER_GENERATION_DELAY seconds.
// The value is cast to an int, which is the floor of the original double.
time += (int)(1 + randomNumber.nextDouble() * MAX_GENERATION_DELAY);
// Random number x determines which type of passenger will be created. The generated number
// is between 0 and 1.0. By splitting across the range of numbers generated, you can simulate
// creation of different passengers of appropriate types.
double x = randomNumber.nextDouble();
if (x < pctExpedite) { // Create a Fast Track passenger
int ftMin = FastTrackPassenger.MIN_PROCESS_TIME;
int ftMax = FastTrackPassenger.MAX_EXPECTED_PROCESS_TIME;
// If the generated number is less than pctExpedite, create a passenger with expedited security
// with a process time between FastTrack.MIN_PROCESS_TIME and FastTrack.MAX_PROCESS_TIME.
return new FastTrackPassenger(time, // FastTrackPassenger.MIN_PROCESS_TIME +
(int) (randomNumber.nextDouble() * (ftMax - ftMin)) + ftMin,
log);
}
else if (x < pctExpedite + pctTrust) { // Create a Trusted Traveler
int tsaMax = TrustedTraveler.MAX_EXPECTED_PROCESS_TIME;
int tsaMin = TrustedTraveler.MIN_PROCESS_TIME;
// Else if the generated number is less than pctExpedite + pcTrust, create a trusted
// traveler with a process time between TrustedTraveler.MIN_PROCESS TIME and TrustedTraveler.MAX_PROCESS_TIME.
return new TrustedTraveler(time, // TrustedTraveler.MIN_PROCESS_TIME +
(int) (randomNumber.nextDouble() * (tsaMax - tsaMin)) + tsaMin,
log);
}
else { // Create an ordinary passenger
int ordMax = OrdinaryPassenger.MAX_EXPECTED_PROCESS_TIME;
int ordMin = OrdinaryPassenger.MIN_PROCESS_TIME;
// Otherwise, create an ordinary passenger with a process time between OrdinaryPassenger.MIN_PROCESS TIME
// and OrdinaryPassenger.MAX_PROCESS_TIME
return new OrdinaryPassenger(time, // OrdinaryPassenger.MIN_PROCESS_TIME +
(int) (randomNumber.nextDouble() * (ordMax - ordMin)) + ordMin,
log);
}
}
/**
* Resets the factory.
*/
public static void resetFactory() {
time = 0;
randomNumber = new Random(10);
}
}
In order to test a static method, you need a static context on Junit.
JUnit includes these useful methods.
#BeforeClass
public static void beforeClass() {}
#AfterClass
public static void afterClass() {}
Trying something like this,
import your.own.project.package;
import static org.junit.Assert.assertEquals;
#BeforeClass
public static void beforeClass() {
Ticketing.resetFactory()
}
Your static method would be executed before or after the whole test. Keep in mind that likely this isn't the desired behavior. You can also try coding a wrapper class as this answer shows. Are static methods offered by wrapper classes often used?
bests.

error: multiply(long) is not public in BigInteger; cannot be accessed from outside package

I'm trying to write a Java method that uses counts the number of ways to sequentially order n distinct objects - a permutation. Every time I try to complile my code, I get an error saying:
multiply(long) is not public in BigInteger; cannot be accessed from outside package.
I tried replacing the line fact = fact.multiply(i); with fact = fact.multiply((long) i); which didn't work either. Does anyone have any ideas?
import java.math.BigInteger;
public class Combinatorics {
public static void main(String[] args) {
// 2.1
System.out.println(CountPerm(9));
}
public static BigInteger CountPerm(int n) {
BigInteger fact = BigInteger.valueOf((long) 1);
for(int i = 1; i <= n; i++){
fact = fact.multiply(i);
}
return fact;
}
}
To multiply BigIntegers, you need give a BigInteger parameter, not a long parameter. The method is BigInteger.multiply(BigInteger).
Change your code to:
fact = fact.multiply(BigInteger.valueOf(i));
As a side note:
BigInteger.valueOf((long) 1); should be replaced by BigInteger.ONE. There is already a predefined constant for one.
Be sure to respect Java naming conventions: CountPerm method should be called countPerm.

Java - Subclasses of Array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Disclaimer: I'm a beginner so feel free to point stuff out...
I have a superclass composed by an array of int with 8 values, now i want to create a subclass to randomly pick 4 items in the array and store them in another Object.
Superclass:
public class SideDeck{
public static final int MaxValue = 6;
public static final int MinValue = -6;
public static final int MaxArrayValue = 8;
public final int[] sidecards = new int[MaxArrayValue];
public SideDeck(){
for(int i=0;i<MaxArrayValue;i++){
sidecards[i]=0;
}
}
public SideDeck(int sidecards1,int sidecards2,int sidecards3,int sidecards4,int sidecards5,int sidecards6, int sidecards7, int sidecards8){
sidecards[0]=sidecards1;
sidecards[1]=sidecards2;
sidecards[2]=sidecards3;
sidecards[3]=sidecards4;
sidecards[4]=sidecards5;
sidecards[5]=sidecards6;
sidecards[6]=sidecards7;
sidecards[7]=sidecards8;
}
public boolean ValidSidedeck(){
int check=0;
if (sidecards[0]!=0) {
for(int i=0;i<MaxArrayValue;i++){
if ((sidecards[i] > MinValue) && (sidecards[i] < MaxValue)){
check=1;
} else{
check=0;
break;
}
}
} else {
check=0;
}
if (check==1){
return true;
} else {
return false;
}
}
public String toString(){
String s="";
for(int i=0;i<MaxArrayValue;i++){
s+=(" || Card n° " + (i+1) + " = " + sidecards[i]);
}
return s;
}
public void ResetSidedeck(){
if (sidecards[0]!=0) {//why check it? what if we just run it?
for(int i=0;i<MaxArrayValue;i++){
sidecards[i]=0;
}
}
}
}
Subclass: (Not really sure what to do here… ) Basically it should pick 4 random positions from the .super and store them here, just that i have no clue how to create the object this way. And passing the super as constructor doesn't seem right since it's gonna pass the Object and not the array(and i don't need the full array anyway). Main thing is that i wanna keep the superclss like that, maybe just adding a method there so extract the 4 values..and passing them as arguments…?
import java.lang.Math;
public final class PlayableSideDeck extends SideDeck{
private final static int MaxCArrayValue=4;
public final int[] sidecardsPlay = new int[MaxCArrayValue];
public PlayableSideDeck(SideDeck sidecards){
/* sidecardsPlay[0]=0;
sidecardsPlay[1]=0;
sidecardsPlay[2]=0;
sidecardsPlay[3]=0;*/
// SetDeck();//<-Can i call a private method in the constructor
}
public void SetDeck(){
/* for(int j=0;j<4;j++){
int position=(super.sidecards[PickDeck()]);//<--this is the main problem.. since it's gonna call the object i guess.
sidecards[j]=position;
System.out.println(/*"i= " + i + *//* " ||| j= " + j + "|||| new sidecard= " + sidecards[j] + " |||| old sidecard=" + super.sidecards[PickDeck()]);
}*/
for(int j=0;j<MaxCArrayValue;j++){
sidecardsPlay[j]=(super.sidecards[PickDeck()]);
System.out.println(/*"i= " + i + */ " ||| j= " + j + "|||| new sidecard= " + sidecardsPlay[j] + " |||| old sidecard=" + super.sidecards[PickDeck()] + "|| random= " + PickDeck());
}
}
public int PickDeck(){
return ((int)(Math.random() * 8));
}
public String toString(){
String s="";
for(int i=0;i<MaxCArrayValue;i++){
s+=(" || Card n° " + (i+1) + " = " + sidecards[i]);
}
return s;
}
}
Thanks.
I'm not sure how you plan to use PlayableSideDeck, so I'll answer answer this two ways and you can pick the most fitting answer.
First, as the book Effective Java (by Josh Bloch) points out, you should favor composition over inheritance. By using composition you have your answer to the question of whether you should pass an instance of SideDeck to the constructor of PlayableSideDeck - you will have to since you won't be inheriting any access to SideDeck. Anyway, I'd recommend reading Item 16 in the book (google for it, there are copies available online) and see if composition doesn't better fit your needs.
Second, if you decide to go with inheritance, you don't need to pass an instance of SideDeck to the constructor of PlayableSideDeck. This is because when you create an instance of PlayableSideDeck you are automatically creating an instance of SideDeck along with it. All constructors in Java will implicitly call super() (which is the superclasses's default constructor) if you don't explicitly provide another such call yourself. For example, you could prevent the implicit call to super() like so:
public class BaseClass {
protected String strValue;
public BaseClass () {
strValue = "";
}
public BaseClass (String str) {
strValue = str;
}
}
public class SubClass extends BaseClass {
private int intValue;
SubClass (String str, int i) {
super (str);
intValue = i;
// note that since strValue is protected, SubClass can access directly
System.out.println ("strValue = " + strValue);
}
}
In this example, if you call new SubClass ("foobar") then you will see strValue = foobar printed on the console.
If BaseClass didn't have a zero argument constructor you would, in fact, be required to call super(str) since the compiler wouldn't be able to figure out how to do it for you.
Also, since you asked, here are a few other tips and pointers:
In the constructor SideDeck() you explicitly initialize all values of the array to 0, which isn't necessary. They will already all be 0. If you needed to init them to 0 then you'd be better off avoiding code duplication by calling ResetSideDeck. Speaking of which, you can shorten that code to Arrays.fill (sidecards, 0); (be sure to import java.util.Arrays).
Yes, you can call private methods from a constructor - but only private methods that are part of the local class, not any of the superclasses (you can, however, call protected methods of superclasses).
You're right about not checking sidecards[0] == 0 since there's little efficiency to be gained unless MaxArrayValue becomes very large.
Your class member variables such as sidecards should be private (or maybe protected if you need to access them from a subclass). Use getter/setter methods to access them.
Lastly, Java naming conventions would tell you to use a lower-case letter for method names (e.g. setDeck, pickDeck, resetDeck, etc.), and for even more idiomatic Java you could rename ValidaDeck to isValidDeck (since it returns a boolean). For the constants such as MaxArrayValue the convention is to use all upper-case with underscores between words, e.g. MAX_ARRAY_VALUE.
Hope this all helps!

I'm having difficulty implementing a static factory for a number generator

I've read all of the cries for "don't use static" and I understand that it reduces OOP and screws up unit tests and can break code when multi-threading. However, I'm attempting none of those.
I'm building a Java singleton utility that contains a public static number generator for issuing ID's - numbers which cannot be duplicated. I chose singleton so it can keep track of the numbers issued throughout the life of the program w/o having to reconstruct a million and having to worry about someone not de-referencing multiple instances. The initialization works, though it doesn't ever increment beyond its first invocation.
I've tried it this way:
public class SClass {
public static final SClass SINGLETON = getInstance();
...
public static final int GEN_ID = genID();
private static int base = 999999;
...
...
private static int genID() {
SClass.SINGLETON.base += 1;
return base
}
}
and I've tried it this way:
public class SClass {
public static final SClass SINGLETON = getInstance();
...
public static int GEN_ID = genID();
private int base;
...
private SClass () {
...
this.base = 999999;
...
}
...
...
private int genID() {
this.base += 1;
return base;
}
}
Yes, I've tried it with 'final' removed from everything...
In each implementation I invoke either strictly statically or I use an instance (SClass s = SClass.SINGLETON; s.Gen_ID) with both the static and object implementations described abaove. I only get "1000000" with both any initial and any consecutive invocations (of either methodology). Would someone be willing to explain what's going on here?
I'm not asking whether or not I should implement static (there's tons of pages with that already) - I'm only asking how to make this work, simply. Though I'm open to more elegant solutions.. Thanks in advance!
You could try this
class SClass {
static final AtomicInteger COUNTER = new AtomicInteger();
final int id = 1000000 + COUNTER.getAndIncrement();
}
No need to use synchronized as AtomicInteger is thread safe.
try this
public class IdGenerator {
public static IdGenerator generator = new IdGenerator();
private IdGenerator(){}
private static int currentID=0;
private int getNextID(){
synchronized (this) {
currentID=currentID+1;
}
return currentID;
}
public static IdGenerator getInstance(){
return generator;
}
public static void main(String[] args) {
IdGenerator generator = IdGenerator.getInstance();
for(int i=0;i<10;i++)
System.out.println(generator.getNextID());
}
}
Thank you to Jon, Peter and Upog for helping me on my issue. I wanted to show the real code for what my original issue was, and then show code for what solved it in the hopes that others may benefit from this particular case.
My original problem was that I couldn't increment a static, unrepeatable counter:
/**
* Generate numbers and increment
*/
public class BuggedGenerator {
/************** Public Constants / Factory ***********/
private static BuggedGenerator INSTANCE = null; // to contain the single instance
/**
* The single instance of BuggedGenerator.
*/
public static final BuggedGenerator READ_IN = getInstance();
public static final int GEN_ID = genID();
private static int base = 999999;
/************ Singleton SetUp ************/
/**
* Utility Constructor.
*/
private BuggedGenerator() {
super(); // unnessesary, but I always invoke super()
}
/**
* Initialize the counter singleton
*/
private static int genID() {
BuggedGenerator.SINGLETON.base += 1;
return base
}
/**
* Determine whether BuggedGenerator already has an instance
* and return that instance.
*/
public static BuggedGenerator getInstance() {
if (null == BuggedGenerator.INSTANCE) {
BuggedGenerator.INSTANCE = new BuggedGenerator();
}
return BuggedGenerator.INSTANCE;
} // end getInstance()
}
This is what I was getting from this implementation:
> BuggedGenerator.READ_IN.GEN_ID
> 1000000
> BuggedGenerator.READ_IN.GEN_ID
> 1000000
> BuggedGenerator b = BuggedGenerator.READ_IN
> b.GEN_ID
> 1000000
When prompted with assistance, I used the AtomicInteger class to replace the GEN_ID implementation as shown in Peter's example, but I recieved compile-time errors about static initializations. I decided that it was too much of a pain to go against OOP and implemented the AtomicInteger as a conventional singleton, being a property of the object. Per Jon's suggestion I've included the whole of the code instead of a snapshot. Feel free to use:
/**
* Copyright 2013, Phil Reason. preason intisive com
* Permission to copy, modify, resell and or freely distribute - provided an
* exact copy of this file is explicitly accompanied and unaltered alongside
* of any distribution of works using this file or any modified version of
* this file.
*/
import java.util.concurrent.atomic.AtomicInteger;
/**
* This is a class to generate numbers for various purposes.
* #author Phil Reason
* #conceptionDate 9/6/13
* #version 1.1
* #revisionDate 9/8/13
*/
public class Generator {
/************** Constants *********************/
/**
* The single instance of Generator.
*/
public static final Generator READ_IN = getInstance();
private static Generator INSTANCE = null; // to contain the single instance
/******** Instance Vars: *******************/
private AtomicInteger counter; // construct an AtomicInteger
private int iDRange;
/************ Singleton SetUp ************/
/**
* non-public default constructor override.
*/
private Generator() {
super(); // unnessesary, but I always invoke super()
this.iDRange = 1000000; // the starting number to range increments
this.counter = new AtomicInteger(); // the AtomicInteger instance
} //END Generator()
/**
* Determine whether Generator already has an instance
* and return that instance.
*/
private static Generator getInstance() {
if (null == Generator.INSTANCE) { // upon first use...
Generator.INSTANCE = new Generator(); // construct the single instance
}
return Generator.INSTANCE; // return ony that instance
} // END Generator getInstance()
/**
* Generate non-repeating numbers. This can be useful for serializing when
* inherited serialization isn't useful or needed.
*
* Return the current count generation then increment the AtomicInteger.
* #ensure genID() >= 1000000 && genID() != genID() (never repeats a number)
*/
public int genID () {
return iDRange + counter.getAndIncrement(); // increments the sum of counter
} // END int genID()
}
The output from this implementation is exactly what I needed, as it works for the lifespan of the class' memory residency. For that property, I only had to forecast each increment for JUnit in between tests when setUp() gets rerun - which does not de-reference the static class reference from memory. For the package I was testing, this was actually to my benefit. Here's what I got from output on this latter implement:
> Generator.READ_IN.GEN_ID
> 1000000
> Generator.READ_IN.GEN_ID
> 1000001
> Generator b = Generator.READ_IN
> b.GEN_ID
> 1000002
... and so on ...
In this implementation the AtomicInteger is used as like in any other object with traditional method invocation, though as a singleton. Not only did it work for what I needed, but I was also able to avoid breaking OOP design. I will need more practice before I'm comfortable enough to committing to static factories. Thanks again to you three for taking your time to answer my question!
~phil

Java True Global Variables (Eclipse for Android)

This should be relatively straight forward however I'm being swamped in SQL information whenever I search for help with this.
Basically I have 3 classes and they each generate a number and I want to get the total number at the end. Is there a way to make a variable which all 3 classes can add to without generating a SQLite Database?
example
Page1.java creates 5 -> adds to Total
Page2.java creates 12 -> adds to Total
Page3.java creates 10 -> adds to Total
Page4.java opens total
Like I said, its likely a simple problem but SQLite is dominating my searches.
Hope you can help, Thanks.
You can use a static variable for that.
If you don't care about encapsulation you could even use one single public static variable for this purpose.
Example:
private static int mCounter = 0;
public static void addToCounter(int i)
{
mCounter += i;
}
public static int getCount()
{
return mCounter;
}
What you could do would be to have a private value, say, private int count in each of your class and its respective getter. You would then also have a method in each class, say, public void doSomething(){... count = ...}.
Once you have all these, in Page4 you could do something like:
public class Page4
{
Page1 pg1 = new Page1();
Page2 pg2 = new Page2();
Page3 pg3 = new Page3();
pg1.doSomething();
pg2.doSomething();
pg3.doSomething();
int total = pg1.getCount() + pg2.getCount() + pg3.getCount();
}
On the other hand, you could pass in an integer variable to the class which gets modified and passed on to the next class.
You could also pass in a reference to some class which contains the actual counter, and once that each class (Page1, Page2...) has finished doing what it needs it would simply reference that class and update the value itself.
It's not that clear how you call your classes.
However if you have just 3 simple classes and one place to call the classes you could pass your variable between the classes and add the values to it.
public class Page1 {
public void addToVariable(int var) {
var = var + 5;
}
}
public class Page2 {
public void addToVariable(int var) {
var = var + 12;
}
}
...
And then call the class methods with your variable:
int yourVariable = 0;
Page1 p1 = new Page1();
Page2 p2 = new Page2();
p1.addToVariable(yourVariable);
p2.addToVariable(yourVariable);
yourVariable will hold the total you're looking for.

Categories

Resources