SlideShare a Scribd company logo
1 of 12
Download to read offline
HelloWorld.java
Below is the syntax highlighted version of HelloWorld.java from §1.1 Hello World.



/*************************************************************************
 * Compilation: javac HelloWorld.java
 * Execution:     java HelloWorld
 *
 * Prints "Hello, World". By tradition, this is everyone's first program.
 *
 * % java HelloWorld
 * Hello, World
 *
 * These 17 lines of text are comments. They are not part of the program;
 * they serve to remind us about its properties. The first two lines tell
 * us what to type to compile and test the program. The next line describes
 * the purpose of the program. The next few lines give a sample execution
 * of the program and the resulting output. We will always include such
 * lines in our programs and encourage you to do the same.
 *
 *************************************************************************/

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, World");
    }

}




                        UseArgument.java
Below is the syntax highlighted version of UseArgument.java from §1.1 Hello World.



/*************************************************************************
 * Compilation: javac UseArgument.java
 * Execution:     java UseArgument yourname
 *
 * Prints "Hi, Bob. How are you?" where "Bob" is replaced by the
 * command-line argument.
 *
 * % java UseArgument Bob
 * Hi, Bob. How are you?
*
    * % java UseArgument Alice
    * Hi, Alice. How are you?
    *
    *************************************************************************/

public class UseArgument {

       public static void main(String[] args) {
           System.out.print("Hi, ");
           System.out.print(args[0]);
           System.out.println(". How are you?");
       }

}
IntOps.java



/*************************************************************************
 * Compilation: javac IntOps.java
 * Execution:     java IntOps a b
 *
 * Illustrates the integer operations a * b, a / b, and a % b.
 *
 * % java IntOps 1234 99
 * 1234 + 99 = 1333
 * 1234 * 99 = 122166
 * 1234 / 99 = 12
 * 1234 % 99 = 46
 * 1234 = 12 * 99 + 46
 *
 * % java IntOps 10 -3
 * 10 + -3 = 7
 * 10 * -3 = -30
 * 10 / -3 = -3
 * 10 % -3 = 1
 * 10 = -3 * -3 + 1
 *
 *************************************************************************/

public class IntOps {

    public static void main(String[] args) {
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int sum = a + b;
        int prod = a * b;
        int quot = a / b;
        int rem = a % b;

        System.out.println(a   +   "   +   "   +   b + " = " + sum);
        System.out.println(a   +   "   *   "   +   b + " = " + prod);
        System.out.println(a   +   "   /   "   +   b + " = " + quot);
        System.out.println(a   +   "   %   "   +   b + " = " + rem);
        System.out.println(a   +   "   =   "   +   quot + " * " + b + " + " + rem);
    }
}
Quadratic.java
Below is the syntax highlighted version of Quadratic.java from §1.2 Built-in Types of Data.



/*************************************************************************
 * Compilation: javac Quadratic.java
 * Execution:     java Quadatic b c
 *
 * Given b and c, solves for the roots of x*x + b*x + c.
 * Assumes both roots are real valued.
 *
 * % java Quadratic -3.0 2.0
 * 2.0
 * 1.0
 *
 * % java Quadratic -1.0 -1.0
 * 1.618033988749895
 * -0.6180339887498949
 *
 * Remark: 1.6180339... is the golden ratio.
 *
 * % java Quadratic 1.0 1.0
 * NaN
 * NaN
 *
 *
 *************************************************************************/

public class Quadratic {

    public static void main(String[] args) {
        double b = Double.parseDouble(args[0]);
        double c = Double.parseDouble(args[1]);

         double discriminant = b*b - 4.0*c;
         double sqroot = Math.sqrt(discriminant);

         double root1 = (-b + sqroot) / 2.0;
         double root2 = (-b - sqroot) / 2.0;

         System.out.println(root1);
         System.out.println(root2);
    }
}
LeapYear.java
Below is the syntax highlighted version of LeapYear.java from §1.2 Built-in Types of Data.




/*************************************************************************
 * Compilation: javac LeapYear.java
 * Execution:     java LeapYear N
 *
 * Prints true if N corresponds to a leap year, and false otherwise.
 * Assumes N >= 1582, corresponding to a year in the Gregorian calendar.
 *
 * % java LeapYear 2004
 * true
 *
 * % java LeapYear 1900
 * false
 *
 * % java LeapYear 2000
 * true
 *
 *************************************************************************/

public class LeapYear {
    public static void main(String[] args) {
        int year = Integer.parseInt(args[0]);
        boolean isLeapYear;

         // divisible by 4
         isLeapYear = (year % 4 == 0);

         // divisible by 4 and not 100
         isLeapYear = isLeapYear && (year % 100 != 0);

         // divisible by 4 and not 100 unless divisible by 400
         isLeapYear = isLeapYear || (year % 400 == 0);

         System.out.println(isLeapYear);
    }
}
LeapYear.java



/*************************************************************************
 * Compilation: javac LeapYear.java
 * Execution:     java LeapYear N
 *
 * Prints true if N corresponds to a leap year, and false otherwise.
 * Assumes N >= 1582, corresponding to a year in the Gregorian calendar.
 *
 * % java LeapYear 2004
 * true
 *
 * % java LeapYear 1900
 * false
 *
 * % java LeapYear 2000
 * true
 *
 *************************************************************************/

public class LeapYear {
    public static void main(String[] args) {
        int year = Integer.parseInt(args[0]);
        boolean isLeapYear;

        // divisible by 4
        isLeapYear = (year % 4 == 0);

        // divisible by 4 and not 100
        isLeapYear = isLeapYear && (year % 100 != 0);

        // divisible by 4 and not 100 unless divisible by 400
        isLeapYear = isLeapYear || (year % 400 == 0);

        System.out.println(isLeapYear);
    }
}
Sqrt.java


/*************************************************************************
 * Compilation: javac Sqrt.java
 * Execution:     java Sqrt c
 *
 * Computes the square root of a nonnegative number c using
 * Newton's method:
 *     - initialize t = c
 *     - replace t with the average of c/t and t
 *     - repeat until desired accuracy reached
 *
 * % java Sqrt 2
 * 1.414213562373095
 *
 * % java Sqrt 1000000
 * 1000.0
 *
 * % java Sqrt 0.4
 * 0.6324555320336759
 *
 * % java Sqrt 1048575
 * 1023.9995117186336
 *
 * % java Sqrt 16664444
 * 4082.2106756021303
 *
 * % java Sqrt 0
 * 0.0
 *
 * % java Sqrt 1e-50
 * 9.999999999999999E-26
 *
 *
 * Remarks
 * ----------
 *   - using Math.abs() is required if c < 1
 *
 *
 * Known bugs
 * ----------
 *   - goes into an infinite loop if the input is negative
 *
 *************************************************************************/

public class Sqrt {
    public static void main(String[] args) {

       // read in the command-line argument
       double c = Double.parseDouble(args[0]);
double epsilon = 1e-15;    // relative error tolerance
        double t = c;              // estimate of the square root of c

        // repeatedly apply Newton update step until desired precision is
achieved
        while (Math.abs(t - c/t) > epsilon*t) {
            t = (c/t + t) / 2.0;
        }

        // print out the estimate of the square root of c
        System.out.println(t);
    }

}
Average.java



/*************************************************************************
 * Compilation: javac Average.java
 * Execution:     java Average < data.txt
 * Dependencies: StdIn.java StdOut.java
 *
 * Reads in a sequence of real numbers, and computes their average.
 *
 * % java Average
 * 10.0 5.0 6.0
 * 3.0 7.0 32.0
 * <Ctrl-d>
 * Average is 10.5

    * Note <Ctrl-d> signifies the end of file on Unix.
    * On windows use <Ctrl-z>.
    *
    *************************************************************************/

public class Average {
    public static void main(String[] args) {
        int count = 0;       // number input values
        double sum = 0.0;    // sum of input values

           // read data and compute statistics
           while (!StdIn.isEmpty()) {
               double value = StdIn.readDouble();
               sum += value;
               count++;
           }

           // compute the average
           double average = sum / count;

           // print results
           StdOut.println("Average is " + average);
       }
}
ArrayEquals.java
/************************************************************************

    * Compilation: javac ArrayEquals.java
    * Execution:     java ArrayEquals
    *
    * The function eq() takes two integer array arguments and returns
    * true if they have the same length and all corresponding pairs
    * of integers are equal.
    *
    * % java ArrayEquals
    * true
    * false
    * true
    * false
    *
    *************************************************************************/

public class ArrayEquals {

       // return true if two integer arrays have same length and all
       // corresponding pairs of integers are equal
       public static boolean eq(int[] a, int[] b) {

           // same length?
           if (a.length != b.length) return false;

           // check each corresponding pair
           for (int i = 0; i < a.length; i++) {
               if (a[i] != b[i]) return false;
           }

           // all elements must be equal
           return true;
       }


       // test client
       public static void   main(String[] args) {
           int[] a = { 3,   1, 4, 1, 5 };
           int[] b = { 3,   1, 4, 1 };
           int[] c = { 3,   1, 4, 1, 5 };
           int[] d = { 2,   7, 1, 8, 2 };

           StdOut.println(eq(a,   a));
           StdOut.println(eq(a,   b));
           StdOut.println(eq(a,   c));
           StdOut.println(eq(a,   d));
       }
}
WordCount.java
/*************************************************************************

    * Compilation: javac WordCount.java
    * Execution:     java WordCount
    *         [ input required from standard input                        ]
    *         [ use Ctrl-d (OS X or Dr. Java) or Ctrl-z (Windows) for EOF ]
    *
    * Dependencies: StdIn.java StdOut.java
    *
    * Read in a sequence of strings from standard input and print out
    * the number of strings read in.
    *
    * % java WordCount
    * it was the best of times
    * it was the worst of times
    * number of words = 12
    * Ctrl-d
    *
    * % java WordCount < tale.txt
    * number of words = 139043
    *
    *************************************************************************/

public class WordCount {
    public static void main(String[] args) {

           int count = 0;
           while (!StdIn.isEmpty()) {
               String word = StdIn.readString();
               count++;
           }

           // output
           StdOut.println("number of words   = " + count);
       }
}
RandomSeq.java


/*************************************************************************
 * Compilation: javac RandomSeq.java
 * Execution:     java RandomSeq N
 *
 * Prints N numbers between 0 and 1.
 *
 * % java RandomSeq 5
 * 0.1654760343787165
 * 0.6212262060326124
 * 0.631755596883274
 * 0.4165639935584283
 * 0.4603525361488371
 *
 *************************************************************************/

public class RandomSeq {
    public static void main(String[] args) {

        // command-line argument
        int N = Integer.parseInt(args[0]);

        // generate and print N numbers between 0 and 1
        for (int i = 0; i < N; i++) {
            System.out.println(Math.random());
        }
    }
}

More Related Content

What's hot

Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streamsBartosz Sypytkowski
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Mario Fusco
 
Sql Injection Attacks(Part1 4)
Sql Injection Attacks(Part1 4)Sql Injection Attacks(Part1 4)
Sql Injection Attacks(Part1 4)Hongyang Wang
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design PatternVarun Arora
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Rx for Android & iOS by Harin Trivedi
Rx for Android & iOS  by Harin TrivediRx for Android & iOS  by Harin Trivedi
Rx for Android & iOS by Harin Trivediharintrivedi
 
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...sachin kumar
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hypeMagdiel Duarte
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to HooksSoluto
 
An Experiment with Checking the glibc Library
An Experiment with Checking the glibc LibraryAn Experiment with Checking the glibc Library
An Experiment with Checking the glibc LibraryAndrey Karpov
 

What's hot (20)

Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
 
Rxandroid
RxandroidRxandroid
Rxandroid
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
Enumerable
EnumerableEnumerable
Enumerable
 
Sql Injection Attacks(Part1 4)
Sql Injection Attacks(Part1 4)Sql Injection Attacks(Part1 4)
Sql Injection Attacks(Part1 4)
 
A Taste of Dotty
A Taste of DottyA Taste of Dotty
A Taste of Dotty
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Rx for Android & iOS by Harin Trivedi
Rx for Android & iOS  by Harin TrivediRx for Android & iOS  by Harin Trivedi
Rx for Android & iOS by Harin Trivedi
 
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
New text document
New text documentNew text document
New text document
 
Managing Mocks
Managing MocksManaging Mocks
Managing Mocks
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hype
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
 
An Experiment with Checking the glibc Library
An Experiment with Checking the glibc LibraryAn Experiment with Checking the glibc Library
An Experiment with Checking the glibc Library
 

Viewers also liked

25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI
25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI
25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROIAWeber
 
Get More Email Subscribers
Get More Email SubscribersGet More Email Subscribers
Get More Email SubscribersAWeber
 
Email List-Building 101: How to Reel In New Readers with a Few Simple Steps
Email List-Building 101: How to Reel In New Readers with a Few Simple StepsEmail List-Building 101: How to Reel In New Readers with a Few Simple Steps
Email List-Building 101: How to Reel In New Readers with a Few Simple StepsAWeber
 
Symantec AntiSpam Complete Overview (PowerPoint)
Symantec AntiSpam Complete Overview (PowerPoint)Symantec AntiSpam Complete Overview (PowerPoint)
Symantec AntiSpam Complete Overview (PowerPoint)webhostingguy
 
Cyber crime ppt
Cyber crime pptCyber crime ppt
Cyber crime pptBushra22
 
Email Marketing Ppt Presentation
Email Marketing Ppt PresentationEmail Marketing Ppt Presentation
Email Marketing Ppt PresentationDiseño Domingo
 
Email Marketing Presentation
Email Marketing PresentationEmail Marketing Presentation
Email Marketing PresentationIain Davenport
 

Viewers also liked (7)

25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI
25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI
25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI
 
Get More Email Subscribers
Get More Email SubscribersGet More Email Subscribers
Get More Email Subscribers
 
Email List-Building 101: How to Reel In New Readers with a Few Simple Steps
Email List-Building 101: How to Reel In New Readers with a Few Simple StepsEmail List-Building 101: How to Reel In New Readers with a Few Simple Steps
Email List-Building 101: How to Reel In New Readers with a Few Simple Steps
 
Symantec AntiSpam Complete Overview (PowerPoint)
Symantec AntiSpam Complete Overview (PowerPoint)Symantec AntiSpam Complete Overview (PowerPoint)
Symantec AntiSpam Complete Overview (PowerPoint)
 
Cyber crime ppt
Cyber crime pptCyber crime ppt
Cyber crime ppt
 
Email Marketing Ppt Presentation
Email Marketing Ppt PresentationEmail Marketing Ppt Presentation
Email Marketing Ppt Presentation
 
Email Marketing Presentation
Email Marketing PresentationEmail Marketing Presentation
Email Marketing Presentation
 

Similar to Java code examples from Introduction to Programming in Java

Chapter 2.2
Chapter 2.2Chapter 2.2
Chapter 2.2sotlsoc
 
(In java language)1. Use recursion in implementing the binarySearc.pdf
(In java language)1. Use recursion in implementing the binarySearc.pdf(In java language)1. Use recursion in implementing the binarySearc.pdf
(In java language)1. Use recursion in implementing the binarySearc.pdfrbjain2007
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
 
Treatment, Architecture and Threads
Treatment, Architecture and ThreadsTreatment, Architecture and Threads
Treatment, Architecture and ThreadsMathias Seguy
 
Algoritmos sujei
Algoritmos sujeiAlgoritmos sujei
Algoritmos sujeigersonjack
 
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docxransayo
 
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdfg++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdfarakalamkah11
 
URGENTJavaPlease updated the already existing Java program and m.pdf
URGENTJavaPlease updated the already existing Java program and m.pdfURGENTJavaPlease updated the already existing Java program and m.pdf
URGENTJavaPlease updated the already existing Java program and m.pdferremmfab
 
----------Evaluator-java---------------- package evaluator- import j.docx
----------Evaluator-java---------------- package evaluator-   import j.docx----------Evaluator-java---------------- package evaluator-   import j.docx
----------Evaluator-java---------------- package evaluator- import j.docxjanettjz6sfehrle
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the BasicsJussi Pohjolainen
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
Lewis jssap3 e_labman02
Lewis jssap3 e_labman02Lewis jssap3 e_labman02
Lewis jssap3 e_labman02auswhit
 

Similar to Java code examples from Introduction to Programming in Java (20)

Chapter 2.2
Chapter 2.2Chapter 2.2
Chapter 2.2
 
(In java language)1. Use recursion in implementing the binarySearc.pdf
(In java language)1. Use recursion in implementing the binarySearc.pdf(In java language)1. Use recursion in implementing the binarySearc.pdf
(In java language)1. Use recursion in implementing the binarySearc.pdf
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
 
Java Print method
Java  Print methodJava  Print method
Java Print method
 
Treatment, Architecture and Threads
Treatment, Architecture and ThreadsTreatment, Architecture and Threads
Treatment, Architecture and Threads
 
Vo.pdf
   Vo.pdf   Vo.pdf
Vo.pdf
 
Algoritmos sujei
Algoritmos sujeiAlgoritmos sujei
Algoritmos sujei
 
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
 
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdfg++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
 
URGENTJavaPlease updated the already existing Java program and m.pdf
URGENTJavaPlease updated the already existing Java program and m.pdfURGENTJavaPlease updated the already existing Java program and m.pdf
URGENTJavaPlease updated the already existing Java program and m.pdf
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
----------Evaluator-java---------------- package evaluator- import j.docx
----------Evaluator-java---------------- package evaluator-   import j.docx----------Evaluator-java---------------- package evaluator-   import j.docx
----------Evaluator-java---------------- package evaluator- import j.docx
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
Lewis jssap3 e_labman02
Lewis jssap3 e_labman02Lewis jssap3 e_labman02
Lewis jssap3 e_labman02
 

Recently uploaded

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 

Recently uploaded (20)

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 

Java code examples from Introduction to Programming in Java

  • 1. HelloWorld.java Below is the syntax highlighted version of HelloWorld.java from §1.1 Hello World. /************************************************************************* * Compilation: javac HelloWorld.java * Execution: java HelloWorld * * Prints "Hello, World". By tradition, this is everyone's first program. * * % java HelloWorld * Hello, World * * These 17 lines of text are comments. They are not part of the program; * they serve to remind us about its properties. The first two lines tell * us what to type to compile and test the program. The next line describes * the purpose of the program. The next few lines give a sample execution * of the program and the resulting output. We will always include such * lines in our programs and encourage you to do the same. * *************************************************************************/ public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } } UseArgument.java Below is the syntax highlighted version of UseArgument.java from §1.1 Hello World. /************************************************************************* * Compilation: javac UseArgument.java * Execution: java UseArgument yourname * * Prints "Hi, Bob. How are you?" where "Bob" is replaced by the * command-line argument. * * % java UseArgument Bob * Hi, Bob. How are you?
  • 2. * * % java UseArgument Alice * Hi, Alice. How are you? * *************************************************************************/ public class UseArgument { public static void main(String[] args) { System.out.print("Hi, "); System.out.print(args[0]); System.out.println(". How are you?"); } }
  • 3. IntOps.java /************************************************************************* * Compilation: javac IntOps.java * Execution: java IntOps a b * * Illustrates the integer operations a * b, a / b, and a % b. * * % java IntOps 1234 99 * 1234 + 99 = 1333 * 1234 * 99 = 122166 * 1234 / 99 = 12 * 1234 % 99 = 46 * 1234 = 12 * 99 + 46 * * % java IntOps 10 -3 * 10 + -3 = 7 * 10 * -3 = -30 * 10 / -3 = -3 * 10 % -3 = 1 * 10 = -3 * -3 + 1 * *************************************************************************/ public class IntOps { public static void main(String[] args) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int sum = a + b; int prod = a * b; int quot = a / b; int rem = a % b; System.out.println(a + " + " + b + " = " + sum); System.out.println(a + " * " + b + " = " + prod); System.out.println(a + " / " + b + " = " + quot); System.out.println(a + " % " + b + " = " + rem); System.out.println(a + " = " + quot + " * " + b + " + " + rem); } }
  • 4. Quadratic.java Below is the syntax highlighted version of Quadratic.java from §1.2 Built-in Types of Data. /************************************************************************* * Compilation: javac Quadratic.java * Execution: java Quadatic b c * * Given b and c, solves for the roots of x*x + b*x + c. * Assumes both roots are real valued. * * % java Quadratic -3.0 2.0 * 2.0 * 1.0 * * % java Quadratic -1.0 -1.0 * 1.618033988749895 * -0.6180339887498949 * * Remark: 1.6180339... is the golden ratio. * * % java Quadratic 1.0 1.0 * NaN * NaN * * *************************************************************************/ public class Quadratic { public static void main(String[] args) { double b = Double.parseDouble(args[0]); double c = Double.parseDouble(args[1]); double discriminant = b*b - 4.0*c; double sqroot = Math.sqrt(discriminant); double root1 = (-b + sqroot) / 2.0; double root2 = (-b - sqroot) / 2.0; System.out.println(root1); System.out.println(root2); } }
  • 5. LeapYear.java Below is the syntax highlighted version of LeapYear.java from §1.2 Built-in Types of Data. /************************************************************************* * Compilation: javac LeapYear.java * Execution: java LeapYear N * * Prints true if N corresponds to a leap year, and false otherwise. * Assumes N >= 1582, corresponding to a year in the Gregorian calendar. * * % java LeapYear 2004 * true * * % java LeapYear 1900 * false * * % java LeapYear 2000 * true * *************************************************************************/ public class LeapYear { public static void main(String[] args) { int year = Integer.parseInt(args[0]); boolean isLeapYear; // divisible by 4 isLeapYear = (year % 4 == 0); // divisible by 4 and not 100 isLeapYear = isLeapYear && (year % 100 != 0); // divisible by 4 and not 100 unless divisible by 400 isLeapYear = isLeapYear || (year % 400 == 0); System.out.println(isLeapYear); } }
  • 6. LeapYear.java /************************************************************************* * Compilation: javac LeapYear.java * Execution: java LeapYear N * * Prints true if N corresponds to a leap year, and false otherwise. * Assumes N >= 1582, corresponding to a year in the Gregorian calendar. * * % java LeapYear 2004 * true * * % java LeapYear 1900 * false * * % java LeapYear 2000 * true * *************************************************************************/ public class LeapYear { public static void main(String[] args) { int year = Integer.parseInt(args[0]); boolean isLeapYear; // divisible by 4 isLeapYear = (year % 4 == 0); // divisible by 4 and not 100 isLeapYear = isLeapYear && (year % 100 != 0); // divisible by 4 and not 100 unless divisible by 400 isLeapYear = isLeapYear || (year % 400 == 0); System.out.println(isLeapYear); } }
  • 7. Sqrt.java /************************************************************************* * Compilation: javac Sqrt.java * Execution: java Sqrt c * * Computes the square root of a nonnegative number c using * Newton's method: * - initialize t = c * - replace t with the average of c/t and t * - repeat until desired accuracy reached * * % java Sqrt 2 * 1.414213562373095 * * % java Sqrt 1000000 * 1000.0 * * % java Sqrt 0.4 * 0.6324555320336759 * * % java Sqrt 1048575 * 1023.9995117186336 * * % java Sqrt 16664444 * 4082.2106756021303 * * % java Sqrt 0 * 0.0 * * % java Sqrt 1e-50 * 9.999999999999999E-26 * * * Remarks * ---------- * - using Math.abs() is required if c < 1 * * * Known bugs * ---------- * - goes into an infinite loop if the input is negative * *************************************************************************/ public class Sqrt { public static void main(String[] args) { // read in the command-line argument double c = Double.parseDouble(args[0]);
  • 8. double epsilon = 1e-15; // relative error tolerance double t = c; // estimate of the square root of c // repeatedly apply Newton update step until desired precision is achieved while (Math.abs(t - c/t) > epsilon*t) { t = (c/t + t) / 2.0; } // print out the estimate of the square root of c System.out.println(t); } }
  • 9. Average.java /************************************************************************* * Compilation: javac Average.java * Execution: java Average < data.txt * Dependencies: StdIn.java StdOut.java * * Reads in a sequence of real numbers, and computes their average. * * % java Average * 10.0 5.0 6.0 * 3.0 7.0 32.0 * <Ctrl-d> * Average is 10.5 * Note <Ctrl-d> signifies the end of file on Unix. * On windows use <Ctrl-z>. * *************************************************************************/ public class Average { public static void main(String[] args) { int count = 0; // number input values double sum = 0.0; // sum of input values // read data and compute statistics while (!StdIn.isEmpty()) { double value = StdIn.readDouble(); sum += value; count++; } // compute the average double average = sum / count; // print results StdOut.println("Average is " + average); } }
  • 10. ArrayEquals.java /************************************************************************ * Compilation: javac ArrayEquals.java * Execution: java ArrayEquals * * The function eq() takes two integer array arguments and returns * true if they have the same length and all corresponding pairs * of integers are equal. * * % java ArrayEquals * true * false * true * false * *************************************************************************/ public class ArrayEquals { // return true if two integer arrays have same length and all // corresponding pairs of integers are equal public static boolean eq(int[] a, int[] b) { // same length? if (a.length != b.length) return false; // check each corresponding pair for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } // all elements must be equal return true; } // test client public static void main(String[] args) { int[] a = { 3, 1, 4, 1, 5 }; int[] b = { 3, 1, 4, 1 }; int[] c = { 3, 1, 4, 1, 5 }; int[] d = { 2, 7, 1, 8, 2 }; StdOut.println(eq(a, a)); StdOut.println(eq(a, b)); StdOut.println(eq(a, c)); StdOut.println(eq(a, d)); } }
  • 11. WordCount.java /************************************************************************* * Compilation: javac WordCount.java * Execution: java WordCount * [ input required from standard input ] * [ use Ctrl-d (OS X or Dr. Java) or Ctrl-z (Windows) for EOF ] * * Dependencies: StdIn.java StdOut.java * * Read in a sequence of strings from standard input and print out * the number of strings read in. * * % java WordCount * it was the best of times * it was the worst of times * number of words = 12 * Ctrl-d * * % java WordCount < tale.txt * number of words = 139043 * *************************************************************************/ public class WordCount { public static void main(String[] args) { int count = 0; while (!StdIn.isEmpty()) { String word = StdIn.readString(); count++; } // output StdOut.println("number of words = " + count); } }
  • 12. RandomSeq.java /************************************************************************* * Compilation: javac RandomSeq.java * Execution: java RandomSeq N * * Prints N numbers between 0 and 1. * * % java RandomSeq 5 * 0.1654760343787165 * 0.6212262060326124 * 0.631755596883274 * 0.4165639935584283 * 0.4603525361488371 * *************************************************************************/ public class RandomSeq { public static void main(String[] args) { // command-line argument int N = Integer.parseInt(args[0]); // generate and print N numbers between 0 and 1 for (int i = 0; i < N; i++) { System.out.println(Math.random()); } } }