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

Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 

Recently uploaded (20)

Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 

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()); } } }